JAVA UNIT-2 Notes
JAVA UNIT-2 Notes
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
static String format(String returns formatted string
3 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.
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;
int age;
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();
System.out.println(p.hashCode()); // 705927765
}
}
Initializing the instance variables:
It is the duty of the programmer to initialize the instance depending on his
requirements. There are various ways to do this.
First way is to initialize the instance variables of Person class in other class, i.e.,
Demo class. For this purpose, the Demo class can be rewritten like this:
class Demo
{
public static void main(String args[])
{
Person p = new Person();
p.name="Raju";
p.age=22;
System.out.println(p.hashCode()); // 705927765
}
}
Second way is to initialize the instance variables of Person class in the Same class.
For this purpose, the Person class can be rewritten like this:
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
double volume()
{
return width * height * depth;
}
}
public class Test
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mybox3 = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mybox3.volume();
System.out.println(" Volume of mybox3 is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mybox3 is 343.0
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collec
tion
3) By annonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in Object
class as: protected void finalize(){}
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Program:
public class TestGarbage1
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
Methods in Java:
A method represents a group of statements that performs a task. Here 'task' represents
a calculation or processing of data or generating a report etc.
A Method has two types:
Method Header
Method Body
Method Header: It contains method name, method parameters and method return
data type.
returntype methodName(parameters)
Method Body: Method body consists of group of statements which contains logic to
perform the task.
{
Statements;
}
If a method returns some value, then a return statement should be written within the
body of method, as:
return somevalue;
There are two types of methods in java:
a) Instance methods
b) Static methods
a) Instance Methods:
Instance methods are the methods which act on the instance variables of the
class. To call the instance methods, we should use the form:
objectname. methodname ();
Example-1: Write a program to perform addition of two numbers using instance
method without return statement.
class Addition
{
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 a1=new Addition();
a1.add(27,35);
}
}
Output:
Addition is 62
Example-2: Write a program to perform addition of two numbers using instance
method with return statement.
class Addition
{
double add(double a,double b)
{
double c=a+b;
return c;
}
}
class MethodDemo
{
public static void main(String args[])
{
Addition a1=new Addition();
double c=a1.add(27,35);
System.out.println("Addition is "+c);
}
}
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
{
}
}
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.
{
return num*fact(num-1);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter number: ");
long num=sc.nextInt();
long f=Factorial.fact(num);
System.out.println("Factorial is "+f);
}
}
Arrays:
Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
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 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