unit 3
unit 3
Java constructors are special types of methods that are used to initialize an object when it is
created. It has the same name as its class name and is syntactically similar to a method. However,
constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined by the
class or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not because Java automatically provides
a default constructor that initializes all member variables to zero. However, once you define your
constructor, the default constructor is no longer used.
Rules for Creating Java Constructors
You must follow the below-given rules while creating Java constructors:
The name of the constructors must be the same as the class name.
Java constructors do not have a return type. Even do not use void as a return type.
There can be multiple constructors in the same class, this concept is known as constructor
overloading.
The access modifiers can be used with the constructors, use if you want to change the
visibility/accessibility of constructors.
Java provides a default constructor that is invoked during the time of object creation. If you
create any type of constructor, the default constructor (provided by Java) is not invoked.
Creating a Java Constructor
To create a constructor in Java, simply write the constructor's name (that is the same as
the class name) followed by the brackets and then write the constructor's body inside the
curly braces ({}).
Syntax
class ClassName {
ClassName() {
}
}
Example to create a Java Constructor
The following example creates a simple constructor that will print "Hello world".
public class Main {
// Creating a constructor
Main() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
System.out.println("The main() method.");
// Creating a class's object
// that will invoke the constructor
Main obj_x = new Main(); }
}
This program will print:
The main() method.
Hello, World!
myStudent.firstName = "Ihechikara";
myStudent.lastName = "Abba";
myStudent.age = 100;
System.out.println(myStudent.age);
//100
System.out.println(myStudent.firstName);
//Ihechikara
}
}
parameterized constructor.
programmer written constructors in a class which have one or more than one arguments
A parameterized constructor is a constructor created with arguments/parameters. Let's
break it down.
public Student(String firstName, String lastName, int age){
class ClassName {
TypeName variable1;
TypeName variable2;
ClassName(TypeName variable1, TypeName variable2) {
this.variable1 = variable1;
this.variable2 = variable2;
}
}
Example:-
class Student {
String name;
int rollNumber;
double marks;
Student(String name, int rollNumber, double marks) {
this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("John", 101, 95.5);
student.displayDetails();
}
}
Output
Name: John
Roll Number: 101
Marks: 95.5
OrderofExecution1.java
/* Parent Class */
class ParentClass
{
/* Constructor */
ParentClass()
{
System.out.println("ParentClass constructor executed.");
}
}
/* Child Class */
class ChildClass extends ParentClass
{
/* Constructor */
ChildClass()
{
System.out.println("ChildClass constructor executed.");
}
}
In the above code, after creating an instance of ChildClass the ParentClass constructor
is invoked first and then the ChildClass.
2. Order of execution of constructor in Multilevel inheritance
In multilevel inheritance, all the upper class constructors are executed when an
instance of bottom most child class is created.
OrderofExecution2.java
class College
{
/* Constructor */
College()
{
System.out.println("College constructor executed");
}
}
In the above code, an instance of Student class is created and it invokes the
constructors of College, Department and Student accordingly.
3. Calling same class constructor using this keyword
Here, inheritance is not implemented. But there can be multiple constructors of a
single class and those constructors can be accessed using this keyword.
OrderofExecution3.java
public class OrderofExecution3
{
/* Default constructor */
OrderofExecution3()
{
this("CallParam");
System.out.println("Default constructor executed.");
}
/* Parameterized constructor */
OrderofExecution3(String str)
{
System.out.println("Parameterized constructor executed.");
}
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of the class */
System.out.println("Order of constructor execution...");
OrderofExecution3 obj = new OrderofExecution3();
}
}
Output:
Order of constructor execution...
Parameterized constructor executed.
Default constructor executed.
In the above code, the parameterized constructor is called first even when the default
constructor is called while object creation. It happens because this keyword is used as
the first line of the default constructor.
/* Child Class */
class ChildClass extends ParentClass
{
int b;
ChildClass(int x, int y)
{
/* Accessing ParentClass Constructor */
super(x);
b = y;
}
/* Method to show value of a and b */
void Show()
{
System.out.println("Value of a : "+a+"\nValue of b : "+b);
}
}
○ Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.
○ Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it into objects
through the wrapper classes.
○ Synchronization: Java synchronization works with objects in Multithreading.
○ java.util package: The java.util package provides the utility classes to deal with
objects.
○ Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects
only.
The eight classes of the java.lang package are known as wrapper classes in Java. The
list of eight wrapper classes are given below:
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class
is known as autoboxing, for example, byte to Byte, char to Character, int to Integer,
long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not
need to use the intValue() method of wrapper classes to convert the wrapper type into
primitives.
Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
Output:
---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true
The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
We will discuss immutable string later. Let's first understand what String in Java is and
how to create the String object.
What is String in Java?
Generally, 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.
How to 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:
String s1="Welcome";
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.
Note: String objects are stored in a special memory area known as the "string constant
pool".
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.
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object
is not modified.
Why String objects are immutable in Java?
As Java uses the concept of String literal. Suppose there are 5 reference variables, all
refer to one object "Sachin". If one reference variable changes the value of the object, it
will be affected by all the reference variables. That is why String objects are immutable
in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the String
object is modifiable, the value might be changed and the class that is supposed to be
loaded might be different.
To avoid this kind of misinterpretation, String is immutable.
2. Thread Safe:
As the String object is immutable we don't have to take care of the synchronization that
is required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by
loading the correct class. This leads to making the application program more secure.
Consider an example of banking software. The username and password cannot be
modified by any intruder because String objects are immutable. This can make the
application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory. When we
try to declare a new String object, the JVM checks whether the value already exists in
the String pool or not. If it exists, the same value is assigned to the new object. This
feature allows Java to use the heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override the
methods of the String class. So that it can provide the same features to the new String
objects as well as to the old ones.
StringBuffer and StringBuilder
Java provides three classes to represent a sequence of characters: String, StringBuffer,
and StringBuilder. The String class is an immutable class whereas StringBuffer and
StringBuilder classes are mutable. There are many differences between StringBuffer
and StringBuilder. The StringBuilder class was introduced since JDK 1.5.
StringBuffer Example
BufferTest.java
//Java Program to demonstrate the use of StringBuffer class.
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
Output:
hellojava
StringBuilder Example
BuilderTest.java
//Java Program to demonstrate the use of StringBuilder class.
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}
Output:
hellojava
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
ConcatTest.java
//Java Program to demonstrate the performance of StringBuffer and
StringBuilder classes.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " +
(System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("Tpoint");
}
System.out.println("Time taken by StringBuilder: " +
(System.currentTimeMillis() - startTime) + "ms");
}
}
Output:
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
Immutable class?
Immutable class means once the object of the class is created its fields cannot be
modified or changed. In Java, all the wrapper classes like Boolean, Short, Integer,
Long, Float, Double, Byte, Char, and String classes are immutable classes
How to create Immutable class?
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long,
Float, Double etc. In short, all the wrapper classes and String class is immutable. We
can also create immutable class by creating final class that have final data members
as the example given below:
○ The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.
○ The class is final so we cannot create the subclass.
○ There is no setter methods i.e. we have no option to change the value of the
instance variable.
==================================================
================================================================
================================================================
================================================================
================================================================
========================================================