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

1.constructors in Java

1. The document discusses constructors, default constructors, parameterized constructors, constructor overloading, garbage collection, class variables, and the static and this keywords in Java. 2. Constructors are called to initialize objects and allocate memory when an object is created. There are two types: default/no-arg constructors which have no parameters, and parameterized constructors which allow passing different values to objects. 3. The static keyword is used for memory management and applies to variables, methods, blocks and nested classes. A static variable is shared among all objects and gets memory only once at class loading.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

1.constructors in Java

1. The document discusses constructors, default constructors, parameterized constructors, constructor overloading, garbage collection, class variables, and the static and this keywords in Java. 2. Constructors are called to initialize objects and allocate memory when an object is created. There are two types: default/no-arg constructors which have no parameters, and parameterized constructors which allow passing different values to objects. 3. The static keyword is used for memory management and applies to variables, methods, blocks and nested classes. A static variable is shared among all objects and gets memory only once at class loading.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

1.

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.

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

2.Java Default Constructor


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

Syntax of default constructor:

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

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:

Bike is created

3.Java Parameterized Constructor


A constructor which has a specific number of parameters is called a 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.

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


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Output:
111 Karan
222 Aryan

4.Constructor Overloading in Java

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.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan

5.Java Garbage Collection or Cleaning up unused objects


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a
way to destroy the unused objects.

Advantage of Garbage Collection

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.

There are many ways an object be unreferenced


By nulling the reference
By assigning a reference to another
By anonymous object etc.

Java Garbage Collection Scenario


1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();

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:

protected void finalize(){}


Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have
created any object without new, you can use finalize method to perform cleanup processing (destroying
remaining objects).

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.

public static void gc(){}


Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the
finalize() method before object is garbage collected.
Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

object is garbage collected


object is garbage collecte
6.Class Variables
A variable provides us with named storage that our programs can manipulate. Java provides three types of
variables.

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;

public static void main(String args[]){


int a = 100;
VariableExample obj = new VariableExample();

System.out.println("Value of instance variable myVariable: "+obj.myVariable);


System.out.println("Value of static variable data: "+VariableExample.data);
System.out.println("Value of local variable a: "+a);
}
}
Output
Value of instance variable myVariable: 0
Value of static variable data: 30
Value of local variable a: 100

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

Understanding the problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is
created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to
the common property of all objects. If we make it static, this field will get the memory only once.
Java static property is shared to all objects.
Example of static variable

//Java Program to demonstrate the use of static variable


class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

Output:

111 Karan ITS


222 Aryan ITS

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

Usage of Java this keyword


1) this: to refer current class instance variable

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.

Solution of the above problem by this keyword

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:

111 ankit 5000


112 sumit 6000

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

dataType[] arrayRefVar; // preferred way.


or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++
language and was adopted in Java to accommodate C/C++ programmers.

Example

The following code snippets are examples of this syntax −

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.
Creating Arrays
You can create an array by using the new operator with the following syntax −

Syntax

arrayRefVar = new dataType[arraySize];


The above statement does two things −

 It creates an array using new dataType[arraySize].

 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 −

double[] myList = new double[10];


Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
10.Two dimensional Array
2D array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as
the collection of rows and columns.
However, 2D arrays are created to implement a relational database look alike data structure. It provides ease of
holding bulk of data at once which can be passed to any number of functions wherever required.
How to declare 2D Array
The syntax of declaring two dimensional array is very much similar to that of a one dimensional array, given as
follows.
1. int arr[max_rows][max_columns];

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.

How do we access data in a 2D array


Due to the fact that the elements of 2D arrays can be random accessed. Similar to one dimensional arrays, we
can access the individual cells in a 2D array by using the indices of the cells. There are two indices attached to a
particular cell, one is its row number while the other is its column number.
However, we can store the value stored in any particular cell of a 2D array to some variable x by using the
following syntax.
1. int x = a[i][j];
where i and j is the row and column number of the cell respectively.
We can assign each cell of a 2D array to 0 by using the following code:
1. for ( int i=0; i<n ;i++)
2. {
3. for (int j=0; j<n; j++)
4. {
5. a[i][j] = 0;
6. }
7. }

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

11.Java Command Line Arguments


The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one
argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sonoo

Output: Your first argument is: sonoo

Example of command-line argument that prints all the values

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

}
}

compile by > javac A.java


run by > java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
abc

12.Java Inner Classes

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.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:

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.

3) Code Optimization: It requires less code to write.

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.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

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

Programmer salary is:40000.0


Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.

14.Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.

Note: Multiple inheritance is not supported in Java through class.


When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...

15.Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class object, there will be ambiguity to call the method of A or
B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes.
So whether you have same method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

16.Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in
Java.

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.

Usage of Java Method Overriding


Method overriding is used to provide the specific implementation of a method which is already provided by its
superclass.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Java Rules for Method Overriding
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method overriding.

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Test it Now
Output:

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.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it has some
specific implementation. The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Test it Now
Output:

Bike is running safely

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 −

Animals can move


Dogs can walk and run

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

Example of final variable

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

Output:Compile Time Error

19.Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-
abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.

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.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs
to be extended and its method implemented. It cannot be instantiated.
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class


abstract class A{}
19.Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

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

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

20.Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class
and interface both can't be instantiated.But there are many differences between abstract class and interface that are given
below.

Abstract class Interface

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.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

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.

Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes

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

Following package example contains interface named animals −

/* File name : Animal.java */


package animals;

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 */

public class MammalInt implements Animal {


public void eat() {
System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Now compile the java files as shown below −


$ javac -d . Animal.java
$ javac -d . 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.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

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.

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.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
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:

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.

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

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.

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

Example of public access modifier

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

Why we need wrapper class in Java


why we need wrapper is to use them in collections API. On the other hand the wrapper objects hold much more memory
compared to primitive types. So use primitive types when you need efficiency and use wrapper class when you need
objects instead of primitive types.

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.

Lets take few examples to understand how the conversion works:

Wrapper Class Example 1: Converting a primitive type to Wrapper object


public class JavaExample{
public static void main(String args[]){
//Converting int primitive into Integer object
int num=100;
Integer obj=Integer.valueOf(num);

System.out.println(num+ " "+ obj);


}
}
Output:

100 100

24. String class


The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform
operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.

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.

Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into
lowercase letter.

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

Java String trim() method


The string trim() method eliminates white spaces before and after string.
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

Sachin
Sachin

Java String startsWith() and endsWith() method


String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true

true
true

Java String charAt() method


The string charAt() method returns a character at specified index.

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

Java String intern() method


A pool of strings, initially empty, is maintained privately by the class String.

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.

String s=new String("Sachin");


String s2=s.intern();
System.out.println(s2);//Sachin

Sachin

Java String valueOf() method


The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.

int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:

1010

Java String replace() method


The string replace() method replaces all occurrence of first sequence of character with second sequence of character.

String s1="Java is a programming language. Java is a platform. Java is an Island.";


String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"
System.out.println(replaceString);
Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

25.Java StringBuffer class


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

Important methods of StringBuffer class


Modifier and Type Method Description

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 reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

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.

You might also like