Strings:: Java Programming UNIT-2
Strings:: Java Programming UNIT-2
Strings:
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string.
String is a class in java.lang package. But in java, all classes are also considered as data
types. So, we can take string as a data type also. A class is also called as user-defined data
type.
Creating Strings:
There are three ways to create strings in Java:
We can create a string just by assigning a group of characters to a string type variable:
String s;
s = "Hello";
Preceding two statements can be combined and written as:
String s = "Hello";
In this, case JVM creates an object and stores the string: "Hello" in that object. This object is
referenced by the variable's'. Remember, creating object means allotting memory for storing
data.
We can create an object to String class by allocating memory using new operator. This
is just like creating an object to any class, like given here:
String s = new String("Hello");
Here, we are doing two things. First, we are creating object using new operator. Then,
we are storing the string: "Hello" into the object.
The third way of creating the strings is by converting the character arrays into strings.
Let us take a character type array: arr[] With some characters, as:
char arr[]={'H','e','l','l','o'};
Now create a string object, by pass.ing the array name to it, as:
String s = new String(arr);
String Methods:
No. Method Description
char charAt(int index) returns char value for the particular
1
index
2 int length() returns string length
3
static String format(String returns formatted string
format, Object... args)
String substring(int beginIndex, returns substring for given begin index
4 int endIndex) and end index
boolean contains(CharSequence s) returns true or false after matching the
5
sequence of char value
static String join(CharSequence returns a joined string
6 delimiter, CharSequence...
elements)
7 boolean equals(Object another) checks the equality of string with object
8 boolean isEmpty() checks if string is empty
9 String concat(String str) concatenates specified string
String replace(char old, char replaces all occurrences of specified
10 new) char value
static String Compares another string. It doesn't
11 equalsIgnoreCase(String another) check case.
Page 1
String[] split(String regex, int returns splitted string matching regex
12 limit) and limit
13 int indexOf(int ch) returns specified char value index
14 String toLowerCase() Returns string in lowercase.
15 String toUpperCase() Returns string in uppercase.
String trim() Removes beginning and ending spaces
16
of this string.
static String valueOf(int value) Converts given type into string. It is
17
overloaded.
equals method in java:
Program:
class StringComapre
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //true
}
}
Immutability of String:
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");
System.out.println(s);
}
}
Output: Sachin
But if we explicitely assign it to the reference variable, it will refer to "Sachin
Tendulkar" object.For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output: Sachin Tendulkar
StringBuffer Class:
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
String class objects are immutable and hence their contents cannot be modified.
StringBuffer class objects are mutable; so they can be modified. Moreover the methods
that directly manipulate data of the object are not available in String class. Such methods
are available in StringBuffer class.
Creating StringBuffer objects:
We can create StringBuffer object by using new operator and pass the string to the object, as:
StringBuffer sb = new StringBuffer("Hello");
class Person
{
String name="Raju";
int age=22;
void talk()
{
System.out.println("My Name is "+name);
System.out.println("My Age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p1 = new Person();
System.out.println("p1 hashcode "+p1.hashCode());
p1.talk();
Person p2 = new Person();
System.out.println("p2 hashcode "+p2.hashCode());
p2.talk();
}
}
Output:
p1 hashcode 705927765
My Name is Raju
My Age is 22
p2 hashcode 705934457
My Name is Raju
My Age is 22
But, the problem in this way of initialization is that all the objects are initializing with same
data.
Constructors:
The third possibility of initialization is using constructors. A constructor is similar to a
method is used to initialize the instance variables. The sole purpose of a constructor is to
initialize the instance variables. A constructor has the following characteristics:
The constructor's name and class name should be same. And the constructor's name
should end with a pair of simple braces.
Person()
{
}
A constructor may have or may not have parameters: Parameters are variables to
receive data from outside into the constructor. If a constructor does not have any
parameters, it is called ‘Default constructor’. If a constructor has 1 or more parameters,
it is called ‘parameterized constructor’; For example, we can write a default constructor
as:
Person()
{
}
And a Parameterized constructor with two parameters, as:
Person(String s, int i)
{
}
A constructor does not return any value, not even 'void'. Recollect, if a method does not
return any value, we write 'void' before the method name. That means, the method is
returning ‘void’ which means 'nothing'. But in case of a constructor, we should not even
write 'void' before the constructor.
A constructor is automatically called and executed at the time of creating an object.
While creating an object, if nothing is passed to, the object, the default constructor is
called and executed. If-some values are passed to the object, then the parameterized
constructor is called. For example, if we create the object as:
Person p = new Person(); // Default Constructor
Person p = new Person(Raju, 22); // Parameterized Constructor
A constructor is called and executed only once per object. This means .when we create
an object, the constructor is called. When we create second object, again the constructor
is called second time.
class Person
{
String name;
int age;
Person()
{
name="Raju";
age=22;
}
void talk()
{
System.out.println("Hello my name is "+name);
System.out.println("and my age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p = new Person(); // Default Constructor
System.out.println("p hashcode "+p.hashCode());
p.talk();
Person p1 = new Person();
System.out.println(p1.hashCode());
p1.talk();
}
}
Output:
p hashcode 705927765
My Name is Raju
My Age is 22
p1 hashcode 705934457
My Name is Raju
My Age is 22
From the output, we can understand that the same data "Raju" and 22 are store in both
objects p1 and p2. p2 object should get p2’s data, not p1’s data. Isn't it? To mitigate the
problem, let us try parameterized constructor, which accepts data from outside and initializes
instance variables with that data.
class Person
{
String name;
int age;
Person()
{
name="Raju";
age=22;
}
Person(String s, int i)
{
name=s;
age=i;
}
void talk()
{
System.out.println("My Name is "+name);
System.out.println("My Age is "+age);
}
}
class Demo
{
public static void main(String args[])
{
Person p1 = new Person();
System.out.println("p1 hashcode "+p1.hashCode());
p1.talk();
Person p2 = new
Person("Sita",23);
System.out.println(p2.hashCode());
p2.talk();
}
Output:
p1 hashcode 705927765
My Name is Raju
My Age is 22
p2 hashcode 705934457
My Name is Sita
My Age is 23
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mybox3 is 343.0
}
}
Output:
Addition is 62
b) Static Methods:
Static methods are the methods which do not act on the instance variables of
the class. static methods are declared as ‘static’. To call the static methods, we need
not create the object. we call a static method, as:
ClassName. methodname ();
Example-1: Write a program to perform addition of two numbers using static method
without return statement.
class Addition
{
static void add(double a,double b)
{
double c=a+b;
System.out.println("Addition is "+c);
}
}
class MethodDemo
{
public static void main(String args[])
{
Addition.add(27,35);
}
}
Output:
Addition is 62
Example-2: Write a program to perform addition of two numbers using static method
with return statement.
class Addition
{
static double add(double a,double b)
{
double c=a+b;
return c;
}
}
class MethodDemo
{
public static void main(String args[])
{
double c= Addition.add(27,35);
System.out.println("Addition is "+c);
}
}
Output:
Addition is 62
Static Block:
A static block is a block of statements declared as ‘static’.
static {
statements;
}
JVM executes a static block on highest priority basis. This means JVM first goes to
static block even before it looks for the main() method in the program.
Example-1: Write a program to test which one is-executed first by JVM, the static block or
the static method.
class Demo
{
static
{
System.out.println("Static block");
}
public static void main(String args[])
{
System.out.println("Static Method");
}
}
Output:
Static block
Static Method
Example-2: Write a java program without main() method.
class Demo
{
static
{
System.out.println("Static block");
}
}
Output:
Static block
Q: Is it possible to compile and run a Java program without writing main()
method? Ans: Yes, it is possible by using a static block in theJava program.
'this' keyword:
'this' is a keyword that refers to the object of the class where it is used. In other words,
'this' refers the object of the present class.
Generally, we write instance variables, constructors and methods in a class. All these
members are referenced by 'this'. When an object is created to a class, a default
reference is also created internally to the object.
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Declaring Single Dimensional Array:
To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for declaring
an array variable −
Syntax:
dataType[] varName;
or
dataType varName[];
Example:
int a[]; or int[] a;
Instantiating an Array in Java
When an array us declared, only a reference of array is created. To actually create or
give memory to array, you create an array like this: The general form of new as it applies to
one-dimensional arrays appears as follows:
varName = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and varName is the name of array variable that is linked to the array.
That is, to use new to allocate an array, you must specify the type and number of elements to
allocate.
Two-Dimensional Array:
The declaration and instantiating of an 1-D array is, as follows
Example:
int[][] a=new int[2][3];
Example: Write a java Program to perform Matrix addition.
import java.util.Scanner;
class MatrixAddition
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int[][] a=new int[2][2];
int[][] b=new int[2][2];
int[][] c=new int[2][2];
System.out.println("Enter the A Matrix elements ");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++) a[i]
[j]=sc.nextInt();
System.out.println("Enter the B Matrix elements ");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++) b[i]
[j]=sc.nextInt();
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
c[i][j]=a[i][j]+b[i][j];
System.out.println("The Addition of Matrix is ");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.print("\n");
}
}
}
Output:
Enter the A Matrix elements
12
34
Enter the B Matrix elements
56
78
The Addition of Matrix is
68
10 12
Example: Write a java Program to perform Matrix multiplication.
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int[][] a=new int[2][2];
int[][] b=new int[2][2];
int[][] c=new int[2][2];
System.out.println("Enter the A Matrix elements ");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++) a[i]
[j]=sc.nextInt();
System.out.println("Enter the B Matrix elements ");
for(int i=0;i<2;i++)
for(int j=0;j<2;j++) b[i]
[j]=sc.nextInt();
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++) c[i]
[j]+=a[i][k]*b[k][j];
System.out.println("The Multiplication of Matrix is ");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.print("\n");
}
}
}
Output:
Enter the A Matrix elements
12
34
Enter the B Matrix elements
56
78
The Multiplication of Matrix is
19 22
43 50
Command line arguments:
The java command-line argument is an argument i.e. passed at the time of running the
java program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behaviour of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Example: Write a JAVA Program to read input from command line.
class CommandLine
{
public static void main(String[] args)
{
System.out.println("Command line argument values are ");
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
Output:
Command line argument values are
27
2.5
krishna
Nested Classes:
Nested classes are the classes that contain other classes like inner classes. Inner class is
basically a safety mechanism since it is hidden from other classes in its outer class.
To make instance variables not available outside the class, we use 'private' access
specifier before the variables. This is how we provide the security mechanism to
variables. Similarly, in some cases we want to provide security for the entire class.
In this case, can we use 'private' access specifier before the class? The problem is, if we
use private access specifier before a class, the class is not available to the Java compiler
or JVM. SO it is illegal to use 'private' before a class name in Java.
But, private specifier is allowed before an inner class and thus it is useful to provide
security for the entire inner class.
An inner class is a class that is defined inside another class.
Inner class is a safety mechanism.
Inner class is hidden from other classes in its outer class.
An object to inner class cannot be created in other classes.
An object to inner class can be created only in its outer class.
Inner class _can access the members of outer class directly.
Inner class object and outer class objects are created in separate memory locations.
Example: Write a JAVA program to create the outer class BankAccount and the inner class
Interest in it.
import java.util.Scanner;
class BankAccount
{
double bal;
BankAccount(double b)
{
bal=b;
}
void contact(double r)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter Password: ");
String password=sc.next();
if(password.equals("cse556"))
{
Interest in=new Interest(r);
in.calculateInterest();
}
}
private class Interest
{
double rate;
Interest(double r)
{
rate=r;
}
void calculateInterest()
{
double inter=bal*rate/100;
bal=bal+inter;
System.out.println("Updated Balance= "+bal);
}
}
public static void main(String[] args)
{
BankAccount ba=new BankAccount(10000);
ba.contact(9.5);
}
}
Output:
Enter Password: cse556
Updated Balance= 10950.0