You are on page 1of 52

1. What is OOPS?

OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a
collection of objects. Each object is nothing but an instance of a class.
2. Write basic concepts of OOPS?
Following are the concepts of OOPS and are as follows:.
1. Abstraction.
2. Encapsulation.
3. Inheritance.
4. Polymorphism.
3. What is a class?
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the
details of an object.
4. What is an object?
Object is termed as an instance of a class, and it has its own state, behavior and identity.
5. What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That hidden data can
be restricted to the members of that class.
Levels are Public,Protected, Private, Internal and Protected Internal.
6. What is Polymorphism?
Polymorphism is nothing butassigning behavior or value in a subclass to something that was already
declared in the main class. Simply, polymorphism takes more than one form.
7. What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another class.
Ifinheritance applied on one class is called Single Inheritance, and if it depends on multiple classes, then it
is called multiple Inheritance.
8. What are manipulators?
Manipulators are the functions which can be used in conjunction with the insertion (<<) and extraction (>>)
operators on an object. Examples are endl and setw.
9. Define a constructor?

Constructor is a method used to initialize the state of an object, and it gets invoked at the time of object
creation. Rules forconstructor are:.

Constructor Name should be same asclass name.

Constructor must have no return type.

10. Define Destructor?


Destructor is a method which is automatically called when the object ismade ofscope or destroyed.
Destructor name is also same asclass name but with the tilde symbol before the name.
11. What is Inline function?
Inline function is a technique used by the compilers and instructs to insert complete body of the function
wherever that function is used in the program source code.
12. What is avirtual function?
Virtual function is a member function ofclass and its functionality can be overridden in its derived class.
This function can be implemented by using a keyword called virtual, and it can be given during function
declaration.
Virtual function can be achieved in C++, and it can be achieved in C Languageby using function pointers
or pointers to function.
13. What isfriend function?
Friend function is a friend of a class that is allowed to access to Public, private or protected data in that
same class. If the function is defined outside the class cannot access such information.
Friend can be declared anywhere in the class declaration, and it cannot be affected by access control
keywords like private, public or protected.
14. What is function overloading?
Function overloading is defined as a normal function, but it has the ability to perform different tasks. It
allowscreation of several methods with the same name which differ from each other by type of input and
output of the function.
Example
void add(int& a, int& b);
void add(double& a, double& b);
void add(struct bob& a, struct bob& b);
15. What is operator overloading?

Operator overloading is a function where different operators are applied and depends on the arguments.
Operator,-,* can be used to pass through the function , and it has their own precedence to execute.
Example:

C#

1 class complex {
2 double real,
3 imag; public: complex(double r, double i) : real(r),
4 imag(i) {} complex operator+(complex a, complex b);
5 complex operator*(complex a, complex b);
6 complex& operator=(complex a, complex b);
7}

a=1.2, b=6
16. What is an abstract class?
An abstract class is a class which cannot be instantiated. Creation of an object is not possible with
abstract class , but it can be inherited. An abstract class can contain only Abstract method. Java allows
only abstract method in abstract class while for other language it allows non-abstract method as well.
17. What is a ternary operator?
Ternary operator is said to be an operator which takes three arguments. Arguments and results are of
different data types , and it is depends on the function. Ternary operator is also called asconditional
operator.
18. What is the use of finalize method?
Finalize method helps to perform cleanup operations on the resources which are not currently used.
Finalize method is protected , and it is accessible only through this class or by a derived class.
19. What are different types of arguments?
A parameter is a variable used during the declaration of the function or subroutine and arguments are
passed to the function , and it should match with the parameter defined. There are two types of
Arguments.

Call by Value Value passed will get modified only inside the function , and it returns the same value

whatever it is passed it into the function.

Call by Reference Value passed will get modified in both inside and outside the functions and it returns the

same or different value.

20. What is super keyword?


Super keyword is used to invoke overridden method which overrides one of its superclass methods. This
keyword allows to access overridden methods and also to access hidden members of the superclass.
It also forwards a call from a constructor to a constructor in the superclass.
21. What is method overriding?
Method overriding is a feature that allows sub class to provide implementation of a method that is already
defined in the main class. This will overrides the implementation in the superclass by providing the same
method name, same parameter and same return type.
22. What is an interface?
An interface is a collection of abstract method. If the class implements an inheritance, and then thereby
inherits all the abstract methods of an interface.
23. What is exception handling?
Exception is an event that occurs during the execution of a program. Exceptions can be of any type Run
time exception, Error exceptions. Those exceptions are handled properly through exception handling
mechanism like try, catch and throw keywords.
24. What are tokens?
Token is recognized by a compiler and it cannot be broken down into component elements. Keywords,
identifiers, constants, string literals and operators are examples of tokens.
Even punctuation characters are also considered as tokens Brackets, Commas, Braces and
Parentheses.
25. Difference between overloading and overriding?
Overloading is static binding whereas Overriding is dynamic binding. Overloading is nothing but the same
method with different arguments , and it may or may not return the same value in the same class itself.
Overriding is the same method names with same arguments and return types associates with the class
and its child class.

26. Difference between class and an object?


An object is an instance of a class. Objects hold any information , but classes dont have any information.
Definition of properties and functions can be done at class and can be used by the object.
Class can have sub-classes, and an object doesnt have sub-objects.
27. What is an abstraction?
Abstraction is a good feature of OOPS , and it shows only the necessary details to the client of an object.
Means, it shows only necessary details for an object, not the inner details of an object. Example When
you want to switch On television, it not necessary to show all the functions of TV. Whatever is required to
switch on TV will be showed by using abstract class.
28. What are access modifiers?
Access modifiers determine the scope of the method or variables that can be accessed from other various
objects or classes. There are 5 types of access modifiers , and they are as follows:.

Private.

Protected.

Public.

Friend.

Protected Friend.

29. What is sealed modifiers?


Sealed modifiers are the access modifiers where it cannot be inherited by the methods. Sealed modifiers
can also be applied to properties, events and methods. This modifier cannot be applied to static members.

30. How can we call the base method without creating an instance?
Yes, it is possible to call the base method without creating an instance. And that method should be,.
Static method.
Doing inheritance from that class.-Use Base Keyword from derived class.
31. What is the difference between new and override?
The new modifier instructs the compiler to use the new implementation instead of the base class function.
Whereas, Override modifier helps to override the base class function.
32. What are the various types of constructors?

There are three various types of constructors , and they are as follows:.
Default Constructor With no parameters.
Parametric Constructor With Parameters. Create a new instance of a class and also passing
arguments simultaneously.
Copy Constructor Which creates a new object as a copy of an existing object.
33. What is early and late binding?
Early binding refers to assignment of values to variables during design time whereas late binding refers to
assignment of values to variables during run time.
34. What is this pointer?
THIS pointer refers to the current object of a class. THIS keyword is used as a pointer which differentiates
between the current object with the global object. Basically, it refers to the current object.
35. What is the difference betweenstructure and a class?
Structure default access type is public , but class access type is private. A structure is used for grouping
data whereas class can be used for grouping data and methods. Structures are exclusively used for
dataand it doesnt require strict validation , but classes are used to encapsulates and inherit data which
requires strict validation.
36. What is the default access modifier in a class?
The default access modifier of a class is Private by default.
37. What is pure virtual function?
A pure virtual function is a function which can be overridden in the derived classbut cannot be defined. A
virtual function can be declared as Pure by using the operator =0.
Example -.

C#

1 Virtual void function1() // Virtual, Not pure


2
3 Virtual void function2() = 0 //Pure virtual

38. What are all the operators that cannot be overloaded?


Following are the operators that cannot be overloaded -.
1. Scope Resolution (:: )
2. Member Selection (.)
3. Member selection through a pointer to function (.*)
39. What is dynamic or run time polymorphism?
Dynamic or Run time polymorphism is also known as method overriding in which call to an overridden
function is resolved during run time, not at the compile time. It means having two or more methods with
the same name,same signature but with different implementation.
40. Do we require parameter for constructors?
No, we do not require parameter for constructors.
41. What is a copy constructor?
This is a special constructor for creating a new object as a copy of an existing object. There will be always
only on copy constructor that can be either defined by the user or the system.
42. What does the keyword virtual represented in the method definition?
It means, we can override the method.
43. Whether static method can use non static members?
False.
44. What arebase class, sub class and super class?
Base class is the most generalized class , and it is said to be a root class.
Sub class is a class that inherits from one or more base classes.
Super class is the parent class from which another class inherits.
45. What is static and dynamic binding?
Binding is nothing but the association of a name with the class. Static binding is a binding in which name
can be associated with the class during compilation time , and it is also called as early Binding.

Dynamic binding is a binding in which name can be associated with the class during execution time , and
it is also called as Late Binding.
46. How many instances can be created for an abstract class?
Zero instances will be created for an abstract class.
47. Which keyword can be used for overloading?
Operator keyword is used for overloading.
48. What is the default access specifier in a class definition?
Private access specifier is used in a class definition.
49. Which OOPS concept is used as reuse mechanism?
Inheritance is the OOPS concept that can be used as reuse mechanism.
50. Which OOPS concept exposes only necessary information to the calling functions?
Data Hiding / Abstraction

1. What is OOPS?
Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions"
and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data,
processes it, and produces output data.
2. basic Concepts of OOPs?
Abstraction.
Encapsulation.
Inheritance.
Polymorphism.
3. What is a class?
A set or category of things having some property or attribute in common and differentiated from others by kind, type,
or quality.
4. What is an object?
Objects are created from Classes, in C#, is an instance of a class that is created dynamically. Object is also a keyword
that is an alias for the predefined type System.
5. What is Encapsulation?
Encapsulation is the packing of data and functions into a single component. The features of encapsulation are
supported using classes in most object-oriented programming languages, although other alternatives also exist.
It allows selective hiding of properties and methods in an object by building an impenetrable wall to protect the code
from accidental corruption.
Also Read: Top 50 Common Job Interview Questions and answers
6. What is Polymorphism?
In programming languages and type theory, polymorphism is the provision of a single interface to entities of different

types.
A polymorphic type is a type whose operations can also be applied to values of some other type, or types.
7. What is Inheritance?
inheritance is when an object or class is based on another object or class, using the same implementation (inheriting
from a class) specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior).
It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and
interfaces.
8. What is Constructor?
A is special method of the class that will be automatically invoked when an instance of the class is created is called as
constructor.
Constructors are mainly used to initialize private fields of the class while creating an instance for the class.
When you are not creating a constructor in the class, then compiler will automatically create a default constructor in
the class that initializes all numeric fields in the class to zero and all string and object fields to null.
Syntax.
[Access Modifier] ClassName([Parameters])
{
}
9. Types of Constructors
Basically constructors are 5 types those are
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor
10. Define Destructor?
A destructor is a method which is automatically invoked when the object is destroyed.
Its main purpose is to free the resources (memory allocations, open files or sockets, database connections, resource
locks, etc.)
Also Read: Android Interview Ques & Ans for Fresher
11. What is Inline function?
In the C and C++ programming languages, an inline function is one qualified with the keyword inline; this serves two
purposes.
Firstly, it serves as a compiler directive, which suggests (but does not require) that the compiler substitute the body
of the function inline by performing inline expansion,
The second purpose of inline is to change linkage behavior; the details of this are complicated.
12. What is operator overloading?
In programming, operator overloadingless commonly known as operator ad hoc polymorphismis a specific case of
polymorphism, where different operators have different implementations depending on their arguments. Operator
overloading is generally defined by the language, the programmer, or both.
13. Different between method overriding and method overloading?
In Overriding methods it will create two or more methods with same name and same parameter in different classes.
while Overloading it will create more then one method with same name but different parameter in same class.
14. What is this keywords?
Every instance method in every object in Java receives a reference named this when the method is invoked. The
reference named this is a reference to the object on which the method was invoked. It can be used for any purpose
for which such a reference is needed.
15. What is super keyword?
The super keyword is a reference variable that is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super
reference variable.
Also Read: Top 20 JSP Interview Questions and Answers
16. What is an abstract class?An abstract class is a class that is declared abstractit may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
17. What is final keywords?
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be: variable, method, 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.
More question coming soon.. we are updating our list of ques and answer... :)
keep wait and watch for few days.

1. What is the difference between a constructor and a method?


A constructor is a member function of a class that is used to create objects of that class. It has the same name as
the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is
invoked using the dot operator.
2. What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that
their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
3. Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared
resources.
Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the
process of using or updating same shared variable. This usually leads to significant errors.
4. What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not
be instantiated (ie. you may not call its constructor), abstract class may contain static data.
Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be
declared abstract even if it has no abstract methods. This prevents it from being instantiated.
5. What is the difference between an Interface and an Abstract class?
An abstract class can have instance methods that implement a default behavior. An Interface can only declare
constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
An interface has all public members and no implementation. An abstract class is a class which may have the usual
flavors of class members (private, protected, etc.), but has some abstract methods.
6. Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is
more advantageous, 'cause when you are going for multiple inheritance, the only interface can help.

7. What is an Iterator?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This
interface allows you to walk through a collection of objects, operating on each object in turn.
Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained;
generally it is not advisable to modify the collection itself while traversing an Iterator.
8. State the significance of public, private, protected, default modifiers both singly and in combination and
state the effect of package relationships on declared items qualified by these modifiers.
public: Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the

variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that
owns the protected feature. This access is provided even to subclasses that reside in a different package from the
class that owns the protected feature.
What you get by default ie, without any access modifier (ie, public private or protected). It means that it is visible to
all within a particular package.
9. What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means
that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding
is done based on the type of the object, and static methods are attached to a class, not an object.
A static method in a superclass can be shadowed by another static method in a subclass, as long as the original
method was not declared final. However, you can't override a static method with a nonstatic method. In other words,
you can't change a static method into an instance method in a subclass.
10. What is final class?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its
class is inherited. You can't change value of a final variable (is a constant).
11. What if the main() method is declared as private?
The program compiles properly but at runtime it will give "main() method not public." message.
12. What if the static modifier is removed from the signature of the main() method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
13. What if I write static public void instead of public static void?
Program compiles and runs properly.
14. What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".
15. What is the first argument of the String array in main() method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is
the program name.
16. If I do not provide any arguments on the command line, then the String array of main() method will be empty
or null?
It is empty. But not null.
17. How can one prove that the array is not null but empty using one line of code?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown
a NullPointerException on attempting to print args.length.
18. What environment variables do I need to set on my machine in order to be able to run Java programs?

CLASSPATH and PATH are the two variables.

19. Can an application have multiple classes having main() method?


Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main
method only in the class whose name you have mentioned.
Hence there is not conflict amongst the multiple classes having main() method.
20. Can I have multiple main() methods in the same class?
No the program fails to compile. The compiler says that the main() method is already defined in the class.
21. Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
22. Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And
the JVM will internally load the class only once no matter how many times you import the same class.
23. What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its
subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception
will be thrown.
Example: IOException thrown by java.io.FileInputStream's read() method
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are
unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch
the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception
could be thrown.
Example: StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must
be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
24. What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass,
the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not
the method definition from superclass. Methods may be overridden to be more public, not more private.
25. Are the imports checked for validity at compile time? Example: will the code containing an import such as
java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will
not compile. It will throw an error saying, can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

26. Does importing a package imports the subpackages as well? Example: Does importing com.MyTest.* also
import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the
package MyTest only. It will not import any class in any of it's subpackage.
27. What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means
declaration + initialization.

Example: String s; is just a declaration while String s = new String ("abcd"); Or String s =
"abcd"; are both definitions.
28. What is the default value of an object reference declared as an instance variable?
The default value will be null unless we define it explicitly.
29. Can a top level class be private or protected?
No. A top level class cannot be private or protected. It can have either "public" or no modifier. If it does not have a
modifier it is supposed to have a default access.
If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here".
This means that a top level class can not be private. Same is the case with protected.
30. What type of parameter passing does Java support?
In Java the arguments are always passed by value.
31. Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.
32. Objects are passed by value or by reference?
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the
original reference and parameter copy both refer to the same object.
33. What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
34. How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the
instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a
file.
35. Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any
methods.
36. How can I customize the seralization process? i.e. how can one have a control over the serialization
process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface.
This interface contains two methods namely readExternal and writeExternal.
You should implement these methods and write the logic for customizing the serialization process.

Some Theory : Java OOPs Concepts


1. Object Oriented Programming

2. Advantage of OOPs over Procedure-oriented programming language


3. Difference between Objcet-oriented and Objcet-based programming language.
In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides
many concepts such asinheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming paradigm where
everything is represented as an object, is known as truly object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair,


table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies the software development and maintenance by providing some concepts:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike
etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convense
the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we
don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.

Advantage of OOPs over Procedure-oriented programming language


1)OOPs makes development and maintenance easier where as in Procedure-oriented programming
language it is not easy to manage if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can be
accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide the solution
of real word problem if we are using the Object-Oriented Programming language.

What is difference between object-oriented programming language and object-based


programming language?
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and
VBScript are examples of object based programming languages.

Do You Know ?

Can we overload main method ?


Constructor returns a value but, what ?
Can we create a program without main method ?
What are the 6 ways to use this keyword ?
Why multiple inheritance is not supported in java ?
Why use aggregation ?
Can we override the static method ?
What is covariant return type ?
What are the three usage of super keyword?

Why use instance initializer block?


What is the usage of blank final variable ?
What is marker or tagged interface ?
What is runtime polymorphism or dynamic method dispatch ?
What is the difference between static and dynamic binding ?
How downcasting is possible in java ?
What is the purpose of private constructor?
What is object cloning ?

What we will learn in OOPs Concepts ?

Advantage of OOPs
Naming Convention
Object and class
Method overloading
Constructor
static keyword
this keyword with 6 usage
Inheritance
Aggregation
Method Overriding
Covariant Return Type
super keyword
Instance Initializer block
final keyword
Abstract class
Interface
Runtime Polymorphism
Static and Dynamic Binding
Downcasting with instanceof operator
Package
Access Modifiers
Encapsulation
Object Cloning

Java Tutorial
1. Java - What, Where and Why?
2. What is Java
3. Where Java is used
4. Java Applications
Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely used robust technology. Let's
start learning of java from basic questions like what is java tutorial, core java, where it is used, what type
of applications are created in java and why use java.

What is Java

Java is a programming language and a platform.


Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has its own runtime environment (JRE) and API, it is called platform.

Java Example
Let's have a quick look at java programming example. A detailed description of hello java example is given
in next page.
1. class Simple{
2.
public static void main(String args[]){
3.
System.out.println("Hello Java");
4.
}
5. }
Test it Now

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some of
them are as follows:
1.
2.
3.
4.
5.
6.
7.
8.

Desktop Applications such as acrobat reader, media player, antivirus etc.


Web Applications such as irctc.co.in, javatpoint.com etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games etc.

Types of Java Applications


There are mainly 4 type of applications that can be created using java programming:

1) Standalone Application

It is also known as desktop application or window-based application. An application that we need to install
on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating
standalone applications.

2) Web Application
An application that runs on the server side and creates dynamic page, is called web application. Currently,
servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.

3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage of high
level security, load balancing and clustering. In java, EJB is used for creating enterprise applications.

4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for creating mobile
applications.

Features of Java
1. Features of Java
1. Simple
2. Object-Oriented
3. Platform Independent
4. secured
5. Robust
6. Architecture Neutral
7. Portable
8. High Performance
9. Distributed
10. Multi-threaded
There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance

11. Multithreaded
12. Distributed

Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading
etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1.
2.
3.
4.
5.
6.

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types of
platforms software-based and hardware-based. Java provides software-based platform. The Java
platform differs from most other platforms in the sense that it's a software-based platform that runs on
top of other hardware-based platforms.It has two components:
1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple


platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code is compiled by the compiler and
converted into bytecode.This bytecode is a platform independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

Secured
Java is secured because:

No explicit pointer
Programs run inside virtual machine sandbox.

Classloader- adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access right to
objects.
Security Manager- determines what resources a class can access such as reading and writing
to the local disk.

These security are provided by java language. Some security can also be provided by application
developer through SSL,JAAS,cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that
avoids security problem. There is automatic garbage collection in java. There is exception handling and
type checking mechanism in java. All these points makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat
slower than a compiled language (e.g., C++)

Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares
the same memory. Threads are important for multi-media, Web applications etc.

C++ vs Java
There are many differences and similarities between C++ programming language and Java. A list of top
differences between C++ and Java are given below:

Comparison Index
Platform-

C++

Java

C++ is platform-dependent.

Java is platform-independent.

C++ is mainly used for system

Java

programming.

programming. It is widely used in window,

independent
Mainly used for

is

mainly

web-based,

used

enterprise

for

application

and

mobile

applications.
Goto

C++ supports goto statement.

Java doesn't support goto statement.

Multiple

C++

Java doesn't support multiple inheritance

inheritance

inheritance.

supports

multiple

through class. It can be achieved by


interfaces in java.

Operator

C++

supports

Overloading

overloading.

operator

Java doesn't support operator overloading.

Pointers

C++ supports pointers. You can

Java supports pointer internally. But you

write pointer program in C++.

can't write the pointer program in java. It


means java has restricted pointer support in
java.

Compiler

and

C++ uses compiler only.

Java uses compiler and interpreter both.

Call by Value and

C++ supports both call by value

Java supports call by value only. There is no

Call by reference

and call by reference.

call by reference in java.

Structure

C++ supports structures and

Java doesn't support structures and unions.

Interpreter

and

Union

unions.

Thread Support

C++

doesn't

have

built-in

Java has built-in thread support.

support for threads. It relies on


third-party libraries for thread
support.
Documentation

C++

doesn't

support

comment

documentation comment.

Java

supports

documentation

comment

(/** ... */) to create documentation for java


source code.

Virtual Keyword

C++ supports virtual keyword

Java has no virtual keyword. We can

so that we can decide whether

override all non-static methods by default.

or not override a function.

In other words, non-static methods are


virtual by default.

unsigned right shift

C++

doesn't

>>>

operator.

support

>>>

Java supports unsigned right shift >>>


operator that fills zero at the top for the
negative numbers. For positive numbers, it
works same like >> operator.

Inheritance Tree

C++ creates a new inheritance

Java uses single inheritance tree always

tree always.

because all classes are the child of Object


class in java. Object class is the root of
inheritance tree in java.

Simple Program of Java


1. Software Requirements
2. Creating Hello Java Example

3. Resolving javac is not recognized problem


In this page, we will learn how to write the simple program of java. We can write a simple hello java program
easily after installing the JDK.
To create a simple java program, you need to create a class that contains main method. Let's understand
the requirement first.

Requirement for Hello Java Example


For executing any java program, you need to
install the JDK if you don't have installed it, download the JDK and install it.
set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
create the java program
compile and run the java program

Creating hello java example


Let's create the hello java program:
1. class Simple{
2.
public static void main(String args[]){
3.
System.out.println("Hello Java");
4.
}
5. }
Test it Now
save this file as Simple.java

To compile:

javac Simple.java

To execute:

java Simple

Output:Hello Java

Understanding first java program


Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

class keyword is used to declare a class in java.


public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method. The
main method is executed by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.

void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used print statement. We will learn about the internal working of
System.out.println statement later.

To write the simple program, open notepad by start menu -> All Programs -> Accessories ->
notepad and write simple program as displayed below:

As displayed in the above diagram, write the simple program of java in notepad and saved it as
Simple.java. To compile and run this program, you need to open command prompt by start menu ->
All Programs -> Accessories -> command prompt.

To compile and run the above program, go to your current directory first; my current directory is c:\new
. Write here:
To compile:

javac Simple.java

To execute:

java Simple

How many ways can we write a java program


There are many ways to write a java program. The modifications that can be done in a java program are
given below:
1) By changing sequence of the modifiers, method prototype is not changed.
Let's see the simple code of main method.

1. static public void main(String args[])


2) subscript notation in java array can be used after type, before variable or after variable.
Let's see the different codes to write the main method.
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
3) You can provide var-args support to main method by passing 3 ellipses (dots)
Let's see the simple code of using var-args in main method. We will learn about var-args later in Java New
Features chapter.
1. public static void main(String... args)
4) Having semicolon at the end of class in java is optional.
Let's see the simple code.
1.
2.
3.
4.
5.

class A{
static public void main(String... args){
System.out.println("hello java4");
}
};

Valid java main method signature


1.
2.
3.
4.
5.
6.
7.
8.

public static void main(String[] args)


public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] args)

Invalid java main method signature


1.
2.
3.
4.

public void main(String[] args)


static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)

Resolving an error "javac is not recognized as an internal or external command" ?

If there occurs a problem like displayed in the below figure, you need to set path. Since DOS doesn't know
javac or java, we need to set path. Path is not required in such a case if you save your program inside the
jdk/bin folder. But its good approach to set path. Click here for How to set path in java.

Next TopicInternal details of Hello Java Program

Variable and Datatype in Java


1. Variable
2. Types of Variable
3. Data Types in Java
In this page, we will learn about the variable and java data types. Variable is a name of memory location.
There are three types of variables: local, instance and static. There are two types of datatypes in java,
primitive and non-primitive.

Variable

Variable is name of reserved area allocated in memory.

1. int data=50;//Here data is variable

Types of Variable
There

are three types of variables in java


local variable
instance variable
static variable

Local Variable
A variable that is declared inside the method is called local variable.

Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not
declared as static.

Static variable

A variable that is declared as static is called static variable. It cannot be local.


We will have detailed learning of these variables in next chapters.

Example to understand the types of variables


1.
2.
3.
4.
5.
6.
7.

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

Data Types in Java


In java, there are two types of data types
primitive data types
non-primitive data types

Data Type

Default Value

Default size

boolean

false

1 bit

char

'\u0000'

2 byte

byte

1 byte

short

2 byte

int

4 byte

long

0L

8 byte

float

0.0f

4 byte

double

0.0d

8 byte

Why char uses 2 byte in java and what is \u0000 ?


because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of unicode
system.To get detail about Unicode see below.

Object and Class in Java


1. Object in Java
2. Class in Java
3. Instace Variable in Java
4. Method in Java
5. Example of Object and class that maintains the records of student
6. Annonymous Object
In this page, we will learn about java objects and classes. In object-oriented programming technique, we
design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.

Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It
can be physical or logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:

state: represents data (value) of an object.


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

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to
write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
A class in java can contain:

data member
method
constructor
block
class and interface

Syntax to declare a class:


1. class <class_name>{
2.
data member;
3.
method;
4. }

Simple Example of Object and Class


In this example, we have created a Student class that have two data members id and name. We are creating
the object of the Student class by new keyword and printing the objects value.
1. class Student1{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6.
Student1 s1=new Student1();//creating an object of Student
7.
System.out.println(s1.id);
8.
System.out.println(s1.name);
9. }
10. }
Test it Now
Output:0 null

Instance variable in Java


A variable that is created inside the class but outside the method, is known as instance variable.Instance
variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is
created.That is why, it is known as instance variable.

Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.

Advantage of Method

Code Reusability
Code Optimization

new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records of students


In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects
by invoking the displayInformation method.
1. class Student2{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6.
rollno=r;
7.
name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student2 s1=new Student2();
14. Student2 s2=new Student2();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
23. }
Test it Now
111 Karan
222 Aryan

As you see in the above figure, object gets the memory in Heap area and reference variable refers to
the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer
to the objects allocated in memory.

Another Example of Object and Class


There is given another example that maintains the records of Rectangle class. Its exaplanation is same
as in the above Student class example.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6.
length=l;
7.
width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }

22. }
Output:55
45

What are the different ways to create an object in Java?


There

are
By
By
By
By

many ways to create an object in java. They are:


new keyword
newInstance() method
clone() method
factory method etc.

We will learn, these ways to create the object later.

Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4.
int fact=1;
5.
for(int i=1;i<=n;i++){
6.
fact=fact*i;
7.
}
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.
1. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Let's see the example:
1. class Rectangle{
2. int length;
3. int width;
4.

5. void insert(int l,int w){


6.
length=l;
7.
width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
14.
15. r1.insert(11,5);
16. r2.insert(3,15);
17.
18. r1.calculateArea();
19. r2.calculateArea();
20. }
21. }
Output:55
45

Method Overloading in Java


1. Different ways to overload the method
2. By changing the no. of arguments
3. By changing the datatype
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behaviour of the method because
its name differs. So, we perform method overloading to figure out the program quickly.

Advantage of method overloading?


Method overloading increases the readability of the program.

Different ways to overload the method


There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

In java, Methood Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no. of arguments


In this example, we have created two overloaded methods, first sum method performs addition of two
numbers and second sum method performs addition of three numbers.
1. class Calculation{
2.
void sum(int a,int b){System.out.println(a+b);}
3.
void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5.
public static void main(String args[]){
6.
Calculation obj=new Calculation();
7.
obj.sum(10,10,10);
8.
obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:30
40

2)Example of Method Overloading by changing data type of argument


In this example, we have created two overloaded methods that differs in data type. The first sum method
receives two integer arguments and second sum method receives two double arguments.
1. class Calculation2{
2.
void sum(int a,int b){System.out.println(a+b);}
3.
void sum(double a,double b){System.out.println(a+b);}
4.
5.
public static void main(String args[]){
6.
Calculation2 obj=new Calculation2();
7.
obj.sum(10.5,10.5);
8.
obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:21.0
40

Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may
occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
1. class Calculation3{
2.
int sum(int a,int b){System.out.println(a+b);}
3.
double sum(int a,int b){System.out.println(a+b);}
4.
5.
public static void main(String args[]){
6.
Calculation3 obj=new Calculation3();
7.
int result=obj.sum(20,20); //Compile Time Error
8.
9.
}
10. }
Test it Now
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

Can we overload main() method?


Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Let's see the simple example:

1. class Overloading1{
2.
public static void main(int a){
3.
System.out.println(a);
4.
}
5.
6.
public static void main(String args[]){
7.
System.out.println("main() method invoked");
8.
main(10);
9.
}
10. }
Test it Now
Output:main() method invoked
10

Method Overloading and TypePromotion


One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept
by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float
or double and so on.

Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time
1.
2.
3.
4.
5.
6.

of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values


1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now

Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.
1. class Student4{
2.
int id;
3.
String name;
4.
5.
Student4(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
void display(){System.out.println(id+" "+name);}
10.
11.
public static void main(String args[]){
12.
Student4 s1 = new Student4(111,"Karan");
13.
Student4 s2 = new Student4(222,"Aryan");
14.
s1.display();
15.
s2.display();
16. }
17. }
Test it Now
Output:
111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists.The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type.

Example of Constructor Overloading


1. class Student5{
2.
int id;
3.
String name;
4.
int age;
5.
Student5(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
Student5(int i,String n,int a){
10.
id = i;
11.
name = n;
12.
age=a;
13.
}
14.
void display(){System.out.println(id+" "+name+" "+age);}
15.
16.
public static void main(String args[]){
17.
Student5 s1 = new Student5(111,"Karan");
18.
Student5 s2 = new Student5(222,"Aryan",25);
19.
s1.display();
20.
s2.display();
21. }
22. }
Test it Now
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor
Constructor is used to initialize the state of an object.

Java Method

Method is used to expose behav


object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you don't have any

Method is not provided by compiler

constructor.
Constructor name must be same as the class name.

Method name may or may not be sa


name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in java. They are:

By constructor
By assigning the values of one object into another
By clone() method of Object class

Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value
4. Copying the values of one object into another
5. Does constructor perform other task instead initialization
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
1.
2.
3.
4.
5.
6.

time of object creation.


class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values


1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
1. class Student4{
2.
int id;
3.
String name;
4.
5.
Student4(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
void display(){System.out.println(id+" "+name);}
10.
11.
public static void main(String args[]){
12.
Student4 s1 = new Student4(111,"Karan");
13.
Student4 s2 = new Student4(222,"Aryan");
14.
s1.display();
15.
s2.display();
16. }
17. }
Test it Now
Output:
111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists.The compiler differentiates these constructors by taking into account
the number of parameters in the list and their type.

Example of Constructor Overloading


1. class Student5{
2.
int id;
3.
String name;
4.
int age;
5.
Student5(int i,String n){
6.
id = i;
7.
name = n;
8.
}
9.
Student5(int i,String n,int a){

10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22. }

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

Test it Now
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor
Constructor is used to initialize the state of an object.

Java Method

Method is used to expose be


object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you don't have any

Method is not provided by compi

constructor.
Constructor name must be same as the class name.

Method name may or may not be


name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

By constructor
By assigning the values of one object into another
By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21. }

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}

Test it Now
Output:
111 Karan
111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another object. In
this case, there is no need to create the constructor.
1. class Student7{
2.
int id;
3.
String name;
4.
Student7(int i,String n){
5.
id = i;
6.
name = n;
7.
}
8.
Student7(){}
9.
void display(){System.out.println(id+" "+name);}
10.
11.
public static void main(String args[]){
12.
Student7 s1 = new Student7(111,"Karan");

13.
14.
15.
16.
17.
18.
19. }

Student7 s2 = new Student7();


s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}

Test it Now
Output:
111 Karan
111 Karan

Q) Does constructor return any value?


Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the
constructor as you perform in the method.

You might also like