Java Unit-2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

UNIT – II

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.

 It is probably the most commonly used class in java library.

 In java, every string that we 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
changed.

 The Java String class implements Serializable, Comparable and


CharSequence interface that we have represented using the below image.

 The Java String class implements Serializable, Comparable and


CharSequence interface that we have represented using the below image.
 In Java, CharSequence Interface is used for representing a sequence of
characters. CharSequence interface is implemented by String, StringBuffer
and StringBuilder classes. This three classes can be used for creating
strings in java.

create a string object:


String is a sequence of characters. But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.

create a string object:


There are two ways to create String object:

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

In such case, JVM

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

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

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
.

1 char charAt(int index) It returns char value for the particular


index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.

7 boolean contains(CharSequence s) It returns true or false after matching


the sequence of char value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? It returns a joined string.


extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the


given object.
11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the


specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It doesn't


check case.

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex
and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value


index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring index
starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using


specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using


specified locale.
27 String trim() It removes beginning and ending
spaces of this string.

28 static String valueOf(int value) It converts given type into string. It is


an overloaded method.

Immutable String in Java


A String is an unavoidable type of variable while writing any application program. String references
are used to store various attributes like username, password, etc. 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.

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.

Java String compare


To compare string objects, Java provides methods and operators both. So we
can compare string in following three 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)

Example

It compares the content of the strings. It will return true if string matches, else
returns false.

public class Demo{

public static void main(String[] args) {

String s = "Hell";

String s1 = "Hello";

String s2 = "Hello";

boolean b = s1.equals(s2); //true

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{

public static void main(String[] args) {

String s1 = "Java";

String s2 = "Java";

String s3 = new String ("Java");

boolean b = (s1 == s2); //true

System.out.println(b);

b= (s1 == s3); //false

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.

The following image will explain it more clearly.


By compareTo() method

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

Syntax: int compareTo(String str)

Example:

public class HelloWorld{

public static void main(String[] args) {

String s1 = "Abhi";

String s2 = "Viraaj";

String s3 = "Abhi";

int a = s1.compareTo(s2); //return -21 because s1 < s2

System.out.println(a);

a = s1.compareTo(s3); //return 0 because s1 == s3


System.out.println(a);

a = s2.compareTo(s1); //return 21 because s2 > s1

System.out.println(a);

Output:

-21
0

21

StringBuffer class in Java


StringBuffer class is used to create a mutable string object. It means, it can be
changed after it is created. It represents growable and writable character
sequence.

It is similar to String class in Java both are used to create string, but stringbuffer
object can be changed.

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.

1. StringBuffer(): It creates an empty string buffer and reserves space for 16


characters.

2. StringBuffer(int size): It creates an empty string and takes an integer


argument to set capacity of the buffer.

3. StringBuffer(String str): It creates a stringbuffer object from the specified


string.

4. StringBuffer(charSequence []ch): It creates a stringbuffer object from the


charsequence array.
Example: Creating a StringBuffer Object

In this example, we are creating string buffer object using StrigBuffer class and
also testing its mutability.

public class Demo {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("study");

System.out.println(sb);

// modifying object

sb.append("tonight");

System.out.println(sb); // Output: studytonight

Output:
study
studytonight

Java StringBuilder class


StringBuilder is identical to StringBuffer except for one important difference that
it is not synchronized, which means it is not thread safe.

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:

public final class StringBuilder

extends Object

implements Serializable, CharSequence


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.

4. StringBuilder (CharSequence seq): It creates stringbuilder object by using


CharSequence object.

Creating a StringBuilder Class

Lets use StringBuilder class to create string object and check its mutability also

public class Demo {

public static void main(String[] args) {

StringBuilder sb = new StringBuilder("study");

System.out.println(sb);

// modifying object

sb.append("tonight.com");
System.out.println(sb);

Output:
study
studytonight.com

Difference between StringBuffer and StringBuilder class

StringBuffer class StringBuilder class

StringBuffer is synchronized. StringBuilder is not synchronized.

Because of synchronisation, StringBuffer


StringBuilder operates faster.
operation is slower than StringBuilder.

StringBuffer is thread-safe StringBuilder is not thread-safe

StringBuffer is less efficient as compare to StringBuilder is more efficient as


StringBuilder compared to StringBuffer.

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

It is more flexible as compared to


It is alternative of string class
the string class

Introduced in Java 1.0 Introduced in Java 1.5

Its performance is moderate Its performance is very high

It consumes more memory It consumes less memory

Example of StringBuffer class

public class BufferDemo{

public static void main(String[] args){

StringBufferobj=new StringBuffer("Welcome to ");

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.

In Java, we use method overloading and method overriding to achieve polymorphism.

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.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each
object uniquely.

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:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Create Object in Java


The object is a basic building block of an OOPs language. In Java, we cannot execute any program
without creating an object. There is various way to create an object in Java that we will discuss in
this section, and also learn how to create an object in Java.

Java provides five ways to create an object.

o Using new Keyword


o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization

Using new Keyword


Using the new keyword is the most popular way to create an object or instance of the class. When
we create an instance of the class by using the new keyword, it allocates memory (heap) for the
newly created object and also returns the reference of that object to that memory. The new
keyword is also used to create an array. The syntax for creating an object is:

1. ClassName object = new ClassName();

Let's create a program that uses new keyword to create an object.

CreateObjectExample1.java

1. public class CreateObjectExample1


2. {
3. void show()
4. {
5. System.out.println("Welcome to javaTpoint");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. obj.show();
13. }
14. }

Output:

Welcome to javaTpoint

Using clone() Method


The clone() method is the method of Object class. It creates a copy of an object and returns the
same copy. The JVM creates a new object when the clone() method is invoked. It copies all the
content of the previously created object into new one object. Note that it does not call any
constructor. We must implement the Cloneable interface while using the clone() method. The
method throws CloneNotSupportedException exception if the object's class does not support the
Cloneable interface. The subclasses that override the clone() method can throw an exception if an
instance cannot be cloned.

Syntax:

1. protected Object clone() throws CloneNotSupportedException

We use the following statement to create a new object.

1. ClassName newobject = (ClassName) oldobject.clone();

CreateObjectExample3.java

1. public class CreateObjectExample3 implements Cloneable


2. {
3. @Override
4. protected Object clone() throws CloneNotSupportedException
5. {
6. //invokes the clone() method of the super class
7. return super.clone();
8. }
9. String str = "New Object Created";
10. public static void main(String[] args)
11. {
12. //creating an object of the class
13. CreateObjectExample3 obj1 = new CreateObjectExample3();
14. //try catch block to catch the exception thrown by the method
15. try
16. {
17. //creating a new object of the obj1 suing the clone() method
18. CreateObjectExample3 obj2 = (CreateObjectExample3) obj1.clone();
19. System.out.println(obj2.str);
20. }
21. catch (CloneNotSupportedException e)
22. {
23. e.printStackTrace();
24. }
25. }
26. }

Output:

New Object Created

Using newInstance() Method of Class class


The newInstance() method of the Class class is also used to create an object. It calls the default
constructor to create the object. It returns a newly created instance of the class represented by the
object. It internally uses the newInstance() method of the Constructor class.

Syntax:

1. public T newInstance() throws InstantiationException, IllegalAccessException

It throws the IllegalAccessException, InstantiationException,


ExceptionInInitializerError exceptions.

We can create an object in the following ways:


1. ClassName object = ClassName.class.newInstance();

Or

1. ClassName object = (ClassName) Class.forName("fully qualified name of the class").newInstance();

In the above statement, forName() is a static method of Class class. It parses a


parameter className of type String. It returns the object for the class with the fully qualified name.
It loads the class but does not create any object. It throws ClassNotFoundException if the class
cannot be loaded and LinkageError if the linkage fails.

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

1. public class CreateObjectExample4


2. {
3. void show()
4. {
5. System.out.println("A new object created.");
6. }
7. public static void main(String[] args)
8. {
9. try
10. {
11. //creating an instance of Class class
12. Class cls = Class.forName("CreateObjectExample4");
13. //creates an instance of the class using the newInstance() method
14. CreateObjectExample4 obj = (CreateObjectExample4) cls.newInstance();
15. //invoking the show() method
16. obj.show();
17. }
18. catch (ClassNotFoundException e)
19. {
20. e.printStackTrace();
21. }
22. catch (InstantiationException e)
23. {
24. e.printStackTrace();
25. }
26. catch (IllegalAccessException e)
27. {
28. e.printStackTrace();
29. }
30. }
31. }

Output:

A new object created.

Using newInstance() Method of Constructor class


It is similar to the newInstance() method of the Class class. It is known as a reflective way to create
objects. The method is defined in the Constructor class which is the class
of java.lang.reflect package. We can also call the parameterized constructor and private constructor
by using the newInstance() method. It is widely preferred in comparison to newInstance()
method of the Class class.

Syntax:

1. public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumen


tException, InvocationTargetException

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.

We can create an object in the following way:

1. Constructor<Employee> constructor = Employee.class.getConstructor();


2. Employee emp3 = constructor.newInstance();
Let's create a program that creates an object using the newInstance() method.

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.

Serialization: The writeObject() method of the ObjectOutputStream class is used to serialize an


object. It sends the object to the output stream.

Syntax:

1. public final void writeObject(object x) throws IOException

Deserialization: The method readObject() of ObjectInputStream class is used to deserialize an


object. It references objects out of a stream.

Syntax:

1. public final Object readObject() throws IOException,ClassNotFoundException

Let's understand the serialization and deserialization through a program.

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.

Serialization of Java Object:


In the following program, we have serialized an object of Employee class by using
the writeObject() method of the ObjectOutputStream class. The state of the object is saved in
the employee.txt file.

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

Deserialization of Java Object:


In the following program, we going to deserialize an object that we have serialized in the above
program.

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

is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.

There are two types of data types in Java

: primitive and non-primitive.

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.

A local variable cannot be defined with "static" keyword.

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.

Example to understand the types of variables in java


public class A

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

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

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.

There are four types of Java access modifiers:

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.

Understanding Java Access Modifiers

Access within within outside package by subclass outside


Modifier class package only 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.

Simple example of private access modifier

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

Role of Private Constructor

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.

Example of default access modifier

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.

It provides more accessibility than the default modifer.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.

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.

Example of public access modifier

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.

It is a special type of method which is used to initialize the object.

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.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
creation.

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }

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:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

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.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
9. The maximum number is: 9
In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers

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.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define the
method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

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.

Java static keyword


The static keyword in Java

is used for memory management mainly. We can apply static keyword with variables

, methods, blocks and nested classes

. The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not unique for
each object), for example, the company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

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

Example of static variable

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
25. Output:

26. 111 Karan ITS


27. 222 Aryan ITS
28.

2) Java static method


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

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.

Example of static method

1. //Java Program to demonstrate the use of a static method.


2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }
32. Output:111 Karan BBDIT

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block

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

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 can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
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 can be used to return the current class instance from the method.

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

Factory Method Pattern


A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for
creating an object but let the subclasses decide which class to instantiate. In other words,
subclasses are responsible to create the instance of the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern


o Factory Method Pattern allows the sub-classes to choose the type of objects to create.
o It promotes the loose-coupling by eliminating the need to bind application-specific classes into the
code. That means the code interacts solely with the resultant interface or abstract class, so that it will
work with any classes that implement that interface or that extends that abstract class.

Usage of Factory Design Pattern


o When a class doesn't know what sub-classes will be required to create
o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.
ass Demo
{
Double width, height, depth;
Demo (double w, double h, double d

Calculate Electricity Bill : A Real World Example of Factory


Method
Step 1: Create a Plan abstract class.

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.

1. class DomesticPlan extends Plan{


2. //@override
3. public void getRate(){
4. rate=3.50;
5. }
6. }//end of DomesticPlan class.

1. class CommercialPlan extends Plan{


2. //@override
3. public void getRate(){
4. rate=7.50;
5. }
6. /end of CommercialPlan class.

1. class InstitutionalPlan extends Plan{


2. //@override
3. public void getRate(){
4. rate=5.50;
5. }
6. /end of InstitutionalPlan 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.

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }

1. public class RecursionExample2 {


2. static int count=0;
3. static void p(){
4. count++;
5. if(count<=5){
6. System.out.println("hello "+count);
7. p();
8. }
9. }
10. public static void main(String[] args) {
11. p();
12. }
13. }

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

10. The maximum number is: 9


11. The maximum number is: 9

You might also like