Java Unit-2
Java Unit-2
Java Unit-2
syllabus :
Strings: Creating Strings, String Class Methods, String Comparison, Immutability of Strings Introduction to OOPs:
Problems in Procedure Oriented Approach, Features of ObjectOriented Programming System (OOPS) Classes and
Objects: Object Creation, Initializing the Instance Variables, Access Specifiers, Constructors Methods in Java:Method
Header or Method Prototype, Method Body, Understanding Methods, Static Methods, Static Block, The keyword
„this‟, Instance Methods, Passing Primitive Data Types to Methods, Passing Objects to Methods, Passing Arrays to
Methods, Recursion, Factory Methods Inheritance: Inheritance, The keyword „super‟, The Protected Specifier, Types
of Inheritance
Strings:
String is an object that represents sequence of characters. In Java, String is
represented by String class which is located into java.lang package.
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
changed.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with
the value "Welcome" in string constant pool that is why it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create a new object but will return
the reference to the same instance.
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in
the string constant pool. The variable s will refer to the object in a heap (non-pool).
Output:
11. java
12. strings
13. example
The above code, converts a char array into a String object. And displays the String objects s1,
s2, and s3 on console using println() method.
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of char
values.
No Method Description
.
4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring index
starting with given index.
Once String object is created its data or state can't be changed but a new String object is created.
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
8. Output:
9. Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".But if we explicitly assign it to the reference variable, it will refer
to "Sachin Tendulkar" object.
For example:
Testimmutablestring1.java
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.
2. Using == operator
3. By CompareTo() method
equals() method compares two strings for equality. Its general syntax is,
Example
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";
System.out.println(b);
b = s.equals(s1) ; //false
System.out.println(b);
}
}
true
false
Using == operator
The double equal (==) operator compares two object references to check whether
they refer to same instance. This also, will return true on successful match else
returns false.
public class Demo{
String s1 = "Java";
String s2 = "Java";
System.out.println(b);
System.out.println(b);
Explanation
We are creating a new object using new operator, and thus it gets created in a
non-pool memory area of the heap. s1 is pointing to the String in string pool
while s3 is pointing to the String in heap and hence, when we compare s1 and
s3, the answer is false.
String compareTo() method compares values and returns an integer value which
tells if the string compared is less than, equal to or greater than the other string.
It compares the String based on natural ordering i.e alphabetically. Its general
Example:
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
System.out.println(a);
System.out.println(a);
Output:
-21
0
21
It is similar to String class in Java both are used to create string, but stringbuffer
object can be changed.
In this example, we are creating string buffer object using StrigBuffer class and
also testing its mutability.
System.out.println(sb);
// modifying object
sb.append("tonight");
Output:
study
studytonight
StringBuilder also used for creating string object that is mutable and non
synchronized. The StringBuilder class provides no guarantee of synchronization.
StringBuffer and StringBuilder both are mutable but if synchronization is not
required then it is recommend to use StringBuilder class.
This class is located into java.lang package and signature of the class is as:
extends Object
Lets use StringBuilder class to create string object and check its mutability also
System.out.println(sb);
// modifying object
sb.append("tonight.com");
System.out.println(sb);
Output:
study
studytonight.com
Its storage area is in the heap Its storage area is the stack
It is mutable It is mutable
Methods are synchronized Methods are not synchronized
obj.append("studytonight.com");
System.out.println(obj);
Output:
Welcome to studytonight.com
Features of ObjectOriented Programming System (OOPS
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or
code. The only necessary thing is the type of message accepted and the type of response returned
by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we
don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
Object:
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the
banking system.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to
write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
CreateObjectExample1.java
Output:
Welcome to javaTpoint
Syntax:
CreateObjectExample3.java
Output:
Syntax:
Or
To create the object, we use the newInstance() method of the Class class. It works only when we
know the name of the class and the class has a public default constructor.
In the following program, we have creates a new object using the newInstance() method.
CreateObjectExample4.java
Output:
Syntax:
The method parses an array of Objects as an argument. The values of primitive types wrapped in a
wrapper Object of the appropriate type. It returns a new object created by calling the constructor. It
throws IllegalAccessException, IllegalArgumentException, InstantiationException,
InvocationTargetException, ExceptionInInitializerError Exceptions.
CreateObjectExample5.java
1. import java.lang.reflect.*;
2. public class CreateObjectExample5
3. {
4. private String str;
5. CreateObjectExample5()
6. {
7. }
8. public void setName(String str)
9. {
10. this.str = str;
11. }
12. public static void main(String[] args)
13. {
14. try
15. {
16. Constructor<CreateObjectExample5> constructor = CreateObjectExample5.class.getDeclaredConstr
uctor();
17. CreateObjectExample5 r = constructor.newInstance();
18. r.setName("JavaTpoint");
19. System.out.println(r.str);
20. }
21. catch (Exception e)
22. {
23. e.printStackTrace();
24. }
25. }
26. }
Output:
JavaTpoint
Using Deserialization
In Java, serialization is the process of converting an object into a sequence of byte-stream. The
reverse process (byte-stream to object) of serialization is called deserialization. The JVM creates a
new object when we serialize or deserialize an object. It does not use constructor to create an
object. While using deserialization, the Serializable interface (marker interface) must be
implemented in the class.
Syntax:
Syntax:
Employee.java
1. import java.io.Serializable;
2. public class Employee implements Serializable
3. {
4. int empid;
5. String empname;
6. public Empoyee(int empid, String empname)
7. {
8. this.empid = empid;
9. this.empname = empname;
10. }
11. }
We have created a class named Employee whose object is to be serialized and deserialized.
SerializationExample.java
1. import java.io.*;
2. class SerializationExample
3. {
4. public static void main(String args[])
5. {
6. Try
7. {
8. //Creating the object
9. Employee emp = new Employee(198054,"Andrew");
10. //Creates a stream and writes the object
11. FileOutputStream fout=new FileOutputStream("employee.txt");
12. ObjectOutputStream out=new ObjectOutputStream(employeeout);
13. out.writeObject(emp);
14. out.flush();
15. //closes the output stream
16. out.close();
17. System.out.println("Successfully Created");
18. }
19. catch(Exception e)
20. {
21. System.out.println(e);
22. }
23. }
24. }
Output:
Successfully Created
DeserializationExample.java
1. import java.io.*;
2. class DeserializationExample
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. //Creating a stream to read the object
9. ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.txt"));
10. Employee e=(Employee)in.readObject();
11. //prints the data of the serialized object
12. System.out.println(e.empid+" "+e.empname);
13. //closing the input stream
14. in.close();
15. }
16. catch(Exception e)
17. {
18. System.out.println(e);
19. }
20. }
21. }
Output:
198054 Andrew
In the above five methods, we have noticed that the new keyword and
both newInstance() methods use the constructor to create objects, while the rest two methods do
not use the constructor.
Java Variables
A variable is a container which holds the value while the Java program
Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.
Types of Variables
There are three types of variables in Java
:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as
It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory allocation
for static variables happens only once when the class is loaded in the memory.
1. {
2. static int m=100;//static variable
3. void method()
4. {
5. int n=90;//local variable
6. }
7. public static void main(String args[])
8. {
9. int data=50;//instance variable
10. }
11. }//end of class
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a
compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
1. /save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor
if your class doesn't have any.
1. <class_name>(){}
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It provides the reusability of code. We can also easily
modify code using methods. In this section, we will learn what is a method in Java, types of
methods, method declaration, and how to call a method in Java.
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a method
once and use it many times. We do not require to write code again and again. It also provides
the easy modification and readability of code, just by adding or removing a chunk of code. The
method is executed only when we call or invoke it.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which
it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must be
in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same class, it is
known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point. Some
pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Demo.java
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define the
method.
We have defined the above method named findevenodd(). It has a parameter num of type int. The
method does not return any value that's why we have used void. The method body contains the
steps to check the number is even or odd. If the number is even, it prints the number is even, else
prints the number is odd.
is used for memory management mainly. We can apply static keyword with variables
. The static keyword belongs to the class than an instance of the class.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
Example:
In this example, we have three instance variables and a constructor that have
three parameters with same name as instance variables. Now, we will use this
to assign values of parameters to instance variables.
class Demo
{
Double width, height, depth;
Demo (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
}
}
Cl
1. import java.io.*;
2. abstract class Plan{
3. protected double rate;
4. abstract void getRate();
5.
6. public void calculateBill(int units){
7. System.out.println(units*rate);
8. }
9. }//end of Plan class.
Step 2: Create the concrete classes that extends Plan abstract class.
Step 3: Create a GetPlanFactory to generate object of concrete classes based on given information..
1. class GetPlanFactory{
2.
3. //use getPlan method to get object of type Plan
4. public Plan getPlan(String planType){
5. if(planType == null){
6. return null;
7. }
8. if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
9. return new DomesticPlan();
10. }
11. else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){
12. return new CommercialPlan();
13. }
14. else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
15. return new InstitutionalPlan();
16. }
17. return null;
18. }
19. }//end of GetPlanFactory class.
Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete classes by passing an
information such as type of plan DOMESTICPLAN or COMMERCIALPLAN or INSTITUTIONALPLAN.
1. import java.io.*;
2. class GenerateBill{
3. public static void main(String args[])throws IOException{
4. GetPlanFactory planFactory = new GetPlanFactory();
5.
6. System.out.print("Enter the name of plan for which the bill will be generated: ");
7. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
8.
9. String planName=br.readLine();
10. System.out.print("Enter the number of units for bill will be calculated: ");
11. int units=Integer.parseInt(br.readLine());
12.
13. Plan p = planFactory.getPlan(planName);
14. //call getRate() method and calculateBill()method of DomesticPaln.
15.
16. System.out.print("Bill amount for "+planName+" of "+units+" units is: ");
17. p.getRate();
18. p.calculateBill(units);
19. }
20. }//end of GenerateBill class.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called recursive method.
Syntax:
1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
}
}