0% found this document useful (0 votes)
2 views

unit 3

Java constructors are special methods for initializing objects, sharing the same name as the class and lacking a return type. There are two main types of constructors: default constructors, which are automatically provided by Java, and parameterized constructors, which are defined by the programmer. Additionally, Java supports constructor overloading and the use of 'this' and 'super' keywords to manage constructor execution in inheritance scenarios.

Uploaded by

nishthagavande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 3

Java constructors are special methods for initializing objects, sharing the same name as the class and lacking a return type. There are two main types of constructors: default constructors, which are automatically provided by Java, and parameterized constructors, which are defined by the programmer. Additionally, Java supports constructor overloading and the use of 'this' and 'super' keywords to manage constructor execution in inheritance scenarios.

Uploaded by

nishthagavande
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Java Constructors

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

Following is the syntax of a constructor −

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!

Types of Java Constructors


There are three different types of constructors in Java, we have listed them as follows:
1. Default Constructor
2. Parameterized Constructor

What is a default constructor?


A default constructor is a constructor created by the compiler if we do not define any
constructor(s) for a class. Here is an example:
public class Student {
String firstName;
String lastName;
int age;

public static void main(String args[]) {


Student myStudent = new Student();

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

Order of Execution of Constructors in Java Inheritance


Constructors in Java
A constructor in Java is similar to a method with a few differences. Constructor has the
same name as the class name. A constructor doesn't have a return type.
A Java program will automatically create a constructor if it is not already defined in the
program. It is executed when an instance of the class is created.
A constructor cannot be static, abstract, final or synchronized. It cannot be overridden.
Java has two types of constructors:
1. Default constructor
2. Parameterized constructor
What is the order of execution of constructor in Java inheritance?
While implementing inheritance in a Java program, every class has its own constructor.
Therefore the execution of the constructors starts after the object initialization. It follows a
certain sequence according to the class hierarchy. There can be different orders of
execution depending on the type of inheritance.
Different ways of the order of constructor execution in Java
1. Order of execution of constructor in Single inheritance
In single level inheritance, the constructor of the base class is executed first.

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

public class OrderofExecution1


{
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of ChildClass */
System.out.println("Order of constructor execution...");
new ChildClass();
}
}
Output:
Order of constructor execution...
ParentClass constructor executed.
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");
}
}

class Department extends College


{
/* Constructor */
Department()
{
System.out.println("Department constructor executed");
}
}

class Student extends Department


{
/* Constructor */
Student()
{
System.out.println("Student constructor executed");
}
}
public class OrderofExecution2
{
/* Driver Code */
public static void main(String ar[])
{
/* Create instance of Student class */
System.out.println("Order of constructor execution in Multilevel
inheritance...");
new Student();
}
}
Output:
Order of constructor execution in Multilevel inheritance...
College constructor executed
Department constructor executed
Student 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.

4. Calling superclass constructor using super keyword


A child class constructor or method can access the base class constructor or method
using the super keyword.
OrderofExecution4.java
/* Parent Class */
class ParentClass
{
int a;
ParentClass(int x)
{
a = x;
}
}

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

public class OrderofExecution4


{
/* Driver Code */
public static void main(String ar[])
{
System.out.println("Order of constructor execution...");
ChildClass d = new ChildClass(79, 89);
d.Show();
}
}
Output :Order of constructor execution…
Value of a : 79
Value of b : 89
In the above code, the ChildClass calls the ParentClass constructor using a super
keyword that determines the order of execution of constructors.
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive data types into
object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and
objects into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects
many times like in Collections, Serialization, Synchronization, etc. Let us see the
different scenarios, where we need to use the wrapper classes.

○ 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:

Primitive Type Wrapper class

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

System.out.println(a+" "+i+" "+j);


}}
Output:
20 20 20

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

System.out.println(a+" "+i+" "+j);


}}
Output:
333

Java Wrapper classes Example


//Java Program to convert all primitives into its corresponding
//wrapper objects and vice-versa
public class WrapperExample3{
public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

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

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=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

Custom Wrapper class in Java


Java Wrapper classes wrap the primitive data types, that is why it is known as
wrapper classes. We can also create a class which wraps a primitive data type. So, we
can create a custom wrapper class in Java.
//Creating the custom wrapper class
class Javatpoint{
private int i;
Javatpoint(){}
Javatpoint(int i){
this.i=i;
}
public int getValue(){
return i;
}
public void setValue(int i){
this.i=i;
}
@Override
public String toString() {
return Integer.toString(i);
}
}
//Testing the custom wrapper class
public class TestJavatpoint{
public static void main(String[] args){
Javatpoint j=new Javatpoint(10);
System.out.println(j);
}}
Output:
10
Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence
interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create strings in
Java by using these three classes.

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

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
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
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Test it Now
Output:
java
strings
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 It returns a formatted


format, Object... args) string.

4 static String format(Locale It returns formatted string


l, String format, Object... with given locale.
args)

5 String substring(int It returns substring for


beginIndex) given begin index.

6 String substring(int It returns substring for


beginIndex, int endIndex) given begin index and end
index.

7 boolean It returns true or false after


contains(CharSequence s) matching the sequence of
char value.

8 static String It returns a joined string.


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

10 boolean equals(Object It checks the equality of


another) 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, It replaces all occurrences


char new) of the specified char value.

14 String It replaces all occurrences


replace(CharSequence old, of the specified
CharSequence new) CharSequence.

15 static String It compares another string.


equalsIgnoreCase(String It doesn't check case.
another)

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


matching regex.

17 String[] split(String regex, It returns a split string


int limit) 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 It returns the specified char


fromIndex) value index starting with
given index.

21 int indexOf(String It returns the specified


substring) substring index.

22 int indexOf(String It returns the specified


substring, int fromIndex) substring index starting
with given index.

23 String toLowerCase() It returns a string in


lowercase.

24 String toLowerCase(Locale It returns a string in


l) lowercase using specified
locale.

25 String toUpperCase() It returns a string in


uppercase.

26 String toUpperCase(Locale It returns a string in


l) uppercase using specified
locale.

27 String trim() It removes beginning and


ending spaces of this string.

28 static String valueOf(int It converts a given type into


value) a 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.
Let's try to understand the concept of immutability by the example given below:
Testimmutablestring.java
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:
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
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Test it Now
Output:
Sachin Tendulkar

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.

Sr no String Buffer StringBuilder

1. StringBuffer is synchronized i.e. StringBuilder is non-synchronized


thread safe. It means two threads i.e. not thread safe. It means two
can't call the methods of StringBuffer threads can call the methods of
simultaneously. StringBuilder simultaneously.

1. StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

1. StringBuffer was introduced in Java StringBuilder was introduced in


1.0 Java 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:

Example to create Immutable class


In this example, we have created a final class named Employee. It have one final
datamember, a parameterized constructor and getter method.
ImmutableDemo.java
public final class Employee
{
final String pancardNumber;
public Employee(String pancardNumber)
{
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
public class ImmutableDemo
{
public static void main(String ar[])
{
Employee e = new Employee("ABC123");
String s1 = e.getPancardNumber();
System.out.println("Pancard Number: " + s1);
}
}
Output:
Pancard Number: ABC123

The above class is immutable because:

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

==================================================
================================================================
================================================================
================================================================
================================================================
========================================================

You might also like