1.constructors in Java
1.constructors in Java
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.
<class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object
creation.
Output:
Bike is created
The parameterized constructor is used to provide different values to distinct objects. However, you can provide
the same values also.
Output:
111 Karan
222 Aryan
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their types.
It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used to
perform cleanup processing. This method is defined in Object class as:
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in
System and Runtime classes.
Class variables − Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block. There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
Instance variables − Instance variables are declared in a class, but outside a method. When space is allocated
for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that
must be referenced by more than one method, constructor or block, or essential parts of an object's state that
must be present throughout the class.
Local variables − Local variables are declared in methods, constructors, or blocks. Local variables are created
when the method, constructor or block is entered and the variable will be destroyed once it exits the method,
constructor, or block.
Example
public class VariableExample{
int myVariable;
static int data = 30;
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.
Output:
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance
variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Test it Now
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Test it Now
Output:
9.Array
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such
as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the
variable can reference. Here is the syntax for declaring an array variable −
Syntax
Example
Syntax
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in
one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0
to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its
reference to myList −
Above image shows the two dimensional array, the elements are organized in the form of rows and columns.
First element of the first row is represented by a[0][0] where the number shown in the first index is the number
of that row while the number shown in the second index is the number of the column.
Initializing 2D Arrays
We know that, when we declare and initialize one dimensional array in C programming simultaneously, we
don't need to specify the size of the array. However this will not work with 2D arrays. We will have to define at
least the second dimension of the array.
The syntax to declare and initialize the 2D array is given as follows.
1. int arr[2][2] = {0,1,2,3};
The number of elements that can be present in a 2D array will always be equal to (number of rows * number of
columns).
Example : Storing User's data into a 2D array and printing it.
import java.util.Scanner;
publicclass TwoDArray {
publicstaticvoid main(String[] args) {
int[][] arr = newint[3][3];
Scanner sc = new Scanner(System.in);
for (inti =0;i<3;i++)
{
for(intj=0;j<3;j++)
{
System.out.print("Enter Element");
arr[i][j]=sc.nextInt();
System.out.println();
}
}
System.out.println("Printing Elements...");
for(inti=0;i<3;i++)
{
System.out.println();
for(intj=0;j<3;j++)
{
System.out.print(arr[i][j]+"\t");
}
}
}
}
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have
traversed the array using for loop.
class A{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Output: sonoo
jaiswal
1
3
abc
We use inner classes to logically group classes and interfaces in one place so that it can be more readable and
maintainable.
Additionally, it can access all the members of outer class including private data members and methods.
1) Nested classes represent a special type of relationship that is it can access all the members (data members and
methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes
and interfaces in one place only.
13.Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called
child or subclass.
Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship
between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output
In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.
In other words, If a subclass provides the specific implementation of the method that has been declared by one
of its parent class, it is known as method overriding.
Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use
method overriding.
17.Super keyword
super variable refers immediate parent class instance.
super variable can invoke immediate parent class method.
super() acts as immediate parent class constructor and should be first line in child class constructor.
When invoking a superclass version of an overridden method the super keyword is used.
Example
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
Output
This will produce the following result −
18.Final Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only..
Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you
type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the
implements keyword (instead of extends). The body of the interface method is provided by the "implement" class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8, it
abstract methods. can have default and static methods also.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
21.Package
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of
classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing
access protection and namespace management.
java.io − classes for input , output functions are bundled in this package
Creating a Package
While creating a package, you should choose a name for the package and include a package statement along with that name
at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to
include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each source
file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current
default package.
To compile the Java programs with package statements, you have to use -d option as shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed
in that folder.
Example
Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower
case letters to avoid any conflicts with the names of classes and interfaces.
interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */
Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as
shown below.
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
The import Keyword
If a class wants to use another class in the same package, the package name need not be used. Classes in the same
package find each other without any special syntax.
Example
Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the
Employee class without using the payroll prefix, as demonstrated by the following Boss class.
package payroll;
public class Boss {
public void payEmployee(Employee e) {
e.mailCheck();
}
}
What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following
techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example −
payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example −
import payroll.*;
The class itself can be imported using the import keyword. For example −
import payroll.Employee;
22.Access Modifiers in Java
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
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.
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.
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.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are
going to learn the access modifiers only.
ccess Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data member and private method. We
are accessing these private members from outside the class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It
cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than
protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package,
since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.
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.
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.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
23.Wrapper class in Java
In the OOPs concepts guide, we learned that object oriented programming is all about objects. The eight primitive data
types byte, short, int, long, float, double, char and boolean are not objects, Wrapper classes are used for converting
primitive data types into objects, like int to Integer etc. Lets take a simple example to understand why we need wrapper
class in java.
For example: While working with collections in Java, we use generics for type safety like this: ArrayList<Integer> instead
of this ArrayList<int>. The Integer is a wrapper class of int primitive type. We use wrapper class in this case because
generics needs objects not primitives. There are several other reasons you would prefer a wrapper class instead of
primitive type
Primitive Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
The primitive data types are not objects so they do not belong to any class. While storing in data structures which support
only objects, it is required to convert the primitive type to object first which we can do by using wrapper classes.
100 100
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web
based or mobile application.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Test it Now
SACHIN
sachin
Sachin
Sachin
Sachin
true
true
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
S
h
Java String length() method
The string length() method returns length of the string.
String s="Sachin";
System.out.println(s.length());//6
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the
equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a
reference to this String object is returned.
Sachin
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:
1010
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
public append(String s) is used to append the specified string with this string. The append()
synchronized method is overloaded like append(char), append(boolean),
StringBuffer append(int), append(float), append(double) etc.
public insert(int offset, String s) is used to insert the specified string with this string at the specified
synchronized position. The insert() method is overloaded like insert(int, char),
StringBuffer insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
public replace(int startIndex, int is used to replace the string from specified startIndex and endIndex.
synchronized endIndex, String str)
StringBuffer
public delete(int startIndex, int is used to delete the string from specified startIndex and endIndex.
synchronized endIndex)
StringBuffer
public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of
characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, is used to return the substring from the specified beginIndex and
int endIndex) endIndex.