1. JDK (Java Development Kit) is a Kit that provides the environment to develop and execute(run) the
Java program. JDK is a kit(or package) that includes two things
Development Tools(to provide an environment to develop your java programs)
JRE (to execute your java program).
2. JRE (Java Runtime Environment) is an installation package that provides an environment to only
run(not develop) the java program(or application)onto your machine. JRE is only used by those who
only want to run Java programs that are end-users of your system.
3. JVM (Java Virtual Machine) Java Virtual machine (JVM) is the virtual machine that runs the Java
bytecodes. You get this bytecode by compiling the .java files into .class files. .class files contain the
bytecodes understood by the JVM.
JVM is responsible for executing the java program line by line, hence it is also known as an interpreter.
Object Oriented Programming language:
Object-oriented programming – As the name suggests uses objects in programming.Object-oriented programming
aims to implementreal-world entities like inheritance,hiding,polymorphism,etc in programming.The main aim of
OOP is to bind together the data and the functions that operate on them so that no other part of the code can
access this data except that function.
CLASS:
The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data
type, which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but
all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
A Class is a user-defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to manipulate
these variables and together these data members and member functions define the properties and
behaviour of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and member
functions can apply brakes, increase speed etc.
we can say that a Class in C++ is a blue-print representing a group of objects which shares some
common properties and behaviours
OBJECT:
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated. An Object is an identifiable entity with some
characteristics and behaviour.
Eg:consider a object called ORANGE from class FRUITS.
Here state is its color:orange,shape-spherical etc.
Behavior: its taste- sour and sweet.
Encapsulation:
In normal terms, Encapsulation is defined as wrapping up of data and information under a single unit. In
Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions
that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section handles all
the sales-related activities and keeps records of all the sales. Now there may arise a situation when for
some reason an official from the finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of the sales section. He will first have to contact
2. some other officer in the sales section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides the data. In the
above example, the data of any of the section like sales, finance or accounts are hidden from any other
section.
ABSTRACTION:
Data abstraction is one of the most essential and important featuresof object-oriented programmingin C++. Abstraction means
displaying only essential information and hiding the details. Data abstraction refers to providing only
essential information about the data to the outside world, hiding the background details or
implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of the car or applying brakes will stop the car but he does not know about how on
pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using classes. The class helps us to
group data members and member functions using available access specifiers. A Class can decide
which data member will be visible to the outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For example,
consider the pow() method present in math.h header file. Whenever we need to calculate the power of
a number, we simply call the function pow() present in the math.h header file and pass the numbers
as arguments without knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.
POLYMORPHISM:
The word polymorphism means having many forms. Polymorphism in Java is a concept by which we can
perform a single action in different ways. A person at the same time can have different characteristic. Like
a man at the same time is a father, a husband, an employee. So the same person posses different
behaviour in different situations. This is called polymorphism.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
Compile time Polymorphism (or Static polymorphism)
Polymorphism that isresolved during compiler timeisknown as static polymorphism. Methodoverloading isan exampleof compile time
polymorphism.
Method Overloading: Thisallowsusto have more than one methodhavingthe same name, if theparametersof methodsare different in
number, sequence anddata typesof parameters.
public classMain
{
void show(int x)
{
System.out.print(x);
3. }
void show(int y,int z)
{
System.out.print(y+" "+z);
}
public static void main(String[] args) {
Main m=new Main();
m.show(10,20);
}
}
O/P: 10 20
Runtime Polymorphism in Java
Dynamic polymorphism isa process in which a call to an overriddenmethodisresolved at runtime, thatswhy it iscalled runtime
polymorphism. Methodoverriding isan exampleof Runtime polymorphism.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
4. Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run() method. We are calling the
runmethod by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the
subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
Output:
running safely with 60km.
Few more overriding examples:
ABC obj = new ABC();
obj.myMethod();
// This would call the myMethod() of parent class ABC
XYZ obj = new XYZ();
obj.myMethod();
// This would call the myMethod() of child class XYZ
Java Variables
A variable is a container which holds the value n A variable is assigned with a data type. Variable is a name
of memory location. There are three types of variables in java: local, instance and static.
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
5. 2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It is
not declared as static
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class
Java static keyword
The static keyword in Java is used for memory management mainly
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.
6. 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).
Program of the counter without static variable
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at
the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will
have the value 1 in the count variable.
1. //Java Program to demonstrate the use of an instance variable
2. //which get memory each time when we create an object of the class.
3. class Counter{
4. int count=0;//will get memory each time when the instance is created
5.
6. Counter(){
7. count++;//incrementing value
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //Creating objects
13. Counter c1=new Counter();
14. Counter c2=new Counter();
15. Counter c3=new Counter();
16. }
17. }
Test it Now
Output:
1
1
1
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
1. //Java Program to illustrate the use of static variable which
2. //is shared with all objects.
3. class Counter2{
4. static int count=0;//will get memory only once and retain its value
5.
6. Counter2(){
7. count++;//incrementing the value of static variable
8. System.out.println(count);
7. 9. }
10.
11. public static void main(String args[]){
12. //creating objects
13. Counter2 c1=new Counter2();
14. Counter2 c2=new Counter2();
15. Counter2 c3=new Counter2();
16. }
17. }
Test it Now
Output:
1
2
3
Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method
that will lead the problem of extra memory allocation.
) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main
method.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now
Output:
static block is invoked
Can we overload the main method in
Java?
Yes, We can overload the main methodin java but When we execute the class JVM starts execution with public static v oid main(String[] args)
method. (the original main method), it will never call our overloadedmain method.
public class Sample{
public static void main(){
System.out.println("This is the overloaded main method");
}
public static void main(String args[]){
Sample obj = new Sample();
8. obj.main();
}
}
Output
This is the overloaded main method
ErrorsV/s Exceptions In Java:
In java, both Errors and Exceptionsare the subclasses of java.lang.Throwableclass. Error refers to an illegal operation performed by the
user which results in the abnormal working of the program. Error can not be resolved.
An Exception isan unwanted eventthat interruptsthe normal flow of the program.When an exception occursprogram execution gets
terminated.
exception handling
Exception handling ensuresthat the flow of the program doesn’t breakwhen an exception occurs. For example, if a program hasbunch of
statementsand an exception occursmid way after executing certain statementsthen the statementsafter the exceptionwill no t execute and
the program will terminateabruptly.
By handlingwe make sure that all the statementsexecute andthe flow of program doesn’t break.
Exception can be resolved.
Checked Exceptions in Java?
The exceptions thatare checked duringthe compile-time are termed as Checked exceptions in Java. The Javacompiler checks the
checked exceptions during compilation to verify that a method that isthrowing anexception contains the code to handle the
exception withthe try-catchblockor not.
And, if there isno code to handle them, then the compiler checks whetherthe method is declared using the throws keyword. And, if
the compilerfinds neitherof the two cases, then it givesa compilation error. Achecked exception extendsthe Exception class.
Examples of Java Checked Exceptions
For example, if we write a programto read datafrom a file usinga FileReaderclassand if the file doesnot exist, then there isa
FileNotFoundException.
Some checked Exceptions are
SQLException
IOException
ClassNotFoundException
InvocationTargetException
FileNotfound Exception
Code toillustrate the checked exception:
package com.techvidvan.exceptions;
import java.io.File;
import java.io.FileReader;
public class CheckedExceptions
{
public static void main(String args[])
{
File file = new File("/home/techvidvan/file.txt");
FileReader fileReader = new FileReader(file);
System.out.println("Successful");
9. }
}
Output:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at
project1/com.techvidvan.exceptions.CheckedExceptions.main(CheckedExceptions.j
ava:10)
Now, if we use the throws keyword with the main then we will not get any error:
package com.techvidvan.exceptions;
import java.io.*;
public class CheckedExceptions
{
public static void main(String args[]) throws IOException
{
File file = new File("/home/techvidvan/file.txt");
FileReader fileReader = new FileReader(file);
System.out.println("Successful");
}
}
Output:
Successful
What are Java Unchecked Exceptions?
An exception that occurs during the execution of a program is called an unchecked or a runtime
exception. The main cause of unchecked exceptions is mostly due to programming errors like
attempting to access an element with an invalid index, calling the method with illegal
arguments, etc.
In Java, the direct parent class of Unchecked Exception RuntimeException.
Unlike the checked exceptions, the compiler generally ignores the unchecked exceptions during
compilation. Unchecked exceptions are checked during the runtime. Therefore, the compiler
does not check whether the user program contains the code to handle them or not.
Examples of UncheckedExceptions in Java
For example, if a program attempts to divide a number by zero. Or, when there is an illegal
arithmetic operation, this impossible event generates a runtime exception.
Suppose, we declare an array of size 10 in a program, and try to access the 12th element of the
array, or with a negative index like -5, then we get an ArrayIndexOutOfBounds exception.
Some unchecked exceptions are
10. 1. ArithmeticException
2. NullPointerException
3. ArrayIndexOutOfBoundsException
4. NumberFormatException
import java.io.*;
Case 1: (Array)IndexoutOfBoundException: :
class GFG {
// Main Driver Function
public static void main(String[] args)
{
// Array containing 4 elements
int a[] = { 1, 2, 3, 4 };
// Try to access elements greater than
// index size of the array
System.out.println(a[5]);
}
}
Case 2: NullPointerException:
import java.io.*;
public class GFG {
// Main Driver Method
public static void main(String[] args)
{
// Instance of string a has null value
String a = null;
// Comparing null value with the string value
// throw exception and Print
System.out.println(a.equals("GFG"));
}
}
Difference between throw and throws in Java
The throw and throws is the concept of exception handling where the throw keyword throw the exception
explicitly from a method or a block of code whereas the throws keyword is used in signature of the
method.
There are many differences between throw and throws keywords. A list of differences between throw and
throws are given below:
Sr.
no.
Basis of Differences throw throws
11. 1. Definition Java throw keyword is used throw
an exception explicitly in the
code, inside the function or the
block of code.
Java throws keyword is used in
the method signature to declare
an exception which might be
thrown by the function while the
execution of the code.
2. Type of exception Using throw
keyword, we can only propagate
unchecked exception i.e., the
checked exception cannot be
propagated using throw only.
Using throws keyword, we can
declare both checked and
unchecked exceptions. However,
the throws keyword can be used
to propagate checked exceptions
only.
3. Syntax The throw keyword is followed by
an instance of Exception to be
thrown.
The throws keyword is followed
by class names of Exceptions to
be thrown.
4. Declaration throw is used within the method. throws is used with the method
signature.
5. Internal implementation We are allowed to throw only
one exception at a time i.e. we
cannot throw multiple
exceptions.
We can declare multiple
exceptions using throws keyword
that can be thrown by the
method. For example, main()
throws IOException,
SQLException.
Java throw Example
TestThrow.java
1. public class TestThrow {
2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("nNumber is negative, cannot calculate square");
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }
Output:
12. Java throws Example
TestThrows.java
1. public class TestThrows {
2. //defining a method
3. public static int divideNum(int m, int n) throws ArithmeticException {
4. int div = m / n;
5. return div;
6. }
7. //main method
8. public static void main(String[] args) {
9. TestThrows obj = new TestThrows();
10. try {
11. System.out.println(obj.divideNum(45, 0));
12. }
13. catch (ArithmeticException e){
14. System.out.println("nNumber cannot be divided by 0");
15. }
16.
17. System.out.println("Rest of the code..");
18. }
19. }
Output:
Try We specify the block of codethat might give rise to the exception in a special block witha “Try” keyword.
Catch When the exception is raisedit needs to be caught by the program. This is done using a “catch”
key word. So a catch block follows the try block that raises an exception. The keyword catchshould
alway s be used with a try.
Finally Sometimes we have an important code in our program that needs to be executed irrespective of whether
or not the exception is thrown. This code is placed in a special block starting withthe “Finally” keyword.
The Finally block follows theTry-catch block.
Throw The key word “throw” is used to throw the exception explicitly.
Throws The key word “Throws” does not throw an exception but is usedto declare exceptions. This keyword is
used to indicate that an exception might occurin the program or method.
13. Java Object finalize() Method
Finalize() is the method of Object class. This method is called just before an object is garbage collected
so as to perform clean-up activity. Clean-up activity means closing the resources associated with that
object like Database Connection, Network Connection . Remember it is not a reserved keyword. Once
the finalize method completes immediately Garbage Collector destroy that object.
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of
primitive into an object is known as autoboxing and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. Let
us see the different scenarios, where we need to use the wrapper classes.
o Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if
we convert the primitive value in an object, it will change the original value.
o Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in
objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with objects.
o Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to
Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
1. public class WrapperExample1{
2. public static void main(String args[]){
3. //Converting int into Integer
4. int a=20;
5. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
6. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since
Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives.
14. Wrapper class Example: Wrapper to Primitive
1. //Java program to convert object into primitives
2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}
Output:
3 3 3
Type Casting
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or casting down.
1. byte -> short -> char -> int -> long -> float -> double
example
2. int x = 7;
3. //automatically converts the integer type into long type
4. long y = x;
5. //automatically converts the long type into float type
6. float z = y;
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or casting up.
1. double -> float -> long -> int -> char -> short -> byte
2. double d = 166.66;
3. //converting double data type into long data type
4. long l = (long)d;
5. //converting long data type into int data type
6. int i = (int)l;
Serilaization
15. Serialization -the process of writing state of object to a file (permanent state )
The process of converting an object from normal Java supported form to file supported form/network
supporterd form is called a serialization
We can achieve serialization by 2 streams
1.fileoutputstream
2.objectoutputstream
We have an object d1
Steps to convert
1.create object output stream(oos)
Take an object (d1) and convert in to binary data
2.create file output stream(fos)
It will write the binary data in to the file
3.write object method is presented in object output stream
OOS.writeobject(d1)
16. Deserailazation -the process of reading state of object from a file.
The process of converting an object from filesupported form / network supported form into to java
supported form is called as deserialization
We can achieve deserilization by usin g 1.file input stream and
If u want to read binary data this stream is needed
2.object input stream
It will convert binary data in to object
It contains readobject
Call by value
public class Main
{
int a=10;
void b(int a)
17. {
a+=20;
}
public static void main(String[] args) {
System.out.println("Hello World");
Main m=new Main();
System.out.print("b4"+m.a);
m.b(20);
System.out.print(m.a);
}
}
What is Garbage Collection in Java?
Garbage Collection is the process of reclaiming the runtime unused memory by destroying the unused objects.
In languages like C and C++, the programmer is responsible for both the creation and destruction of objects.
Sometimes, the programmer may forget to destroy useless objects, and the memory allocated to them is not
released. The used memory of the system keeps on growing and eventually there is no memory left in the
system to allocate. Such applications suffer from "memory leaks".
After a certain point, sufficient memory is not available for creation of new objects, and the entire program
terminates abnormally due to OutOfMemoryErrors.
You can use methods like free() in C, and delete() in C++ to perform Garbage Collection. In Java, garbage
collection happens automatically during the lifetime of a program. This eliminates the need to de-allocate
memory and therefore avoids memory leaks.
There are various ways in which the references to an object can be released to make it a candidate for
Garbage Collection. Some of them are:
By making a reference null
Student student = new Student();
student = null;
By assigning a reference to another
Student studentOne = new Student();
Student studentTwo = new Student();
studentOne = studentTwo; // now the first object referred by studentOne is available for garbage collection
18. How does Garbage Collection Work in Java?
Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to
be deleted.
The garbage collection implementation lives in the JVM. Each JVM can implement its own version of garbage
collection.
Differences between a Class and an Interface:
Class Interface
The keyword usedto create a class is
“class”
The keyword usedto create an interface is
“interface”
A class can be instantiatedi.e, objects of a
class can be created.
An Interface cannot be instantiated i.e, objects
cannot be created.
Classes does not support multiple
inheritance. Interface supports multiple inheritance.
It can be inherit another class. It cannot inherit a class.
It can be inheritedby another class using
the keyword ‘extends’.
It can be inheritedby a class by using the
keyword ‘implements’and it can be inherited
by an interface usingthe keyword ‘extends’.
It can containconstructors. It cannot containconstructors.
It cannot containabstract methods. It contains abstract methods only.
Variables and methods in a class can be
declaredusing any access specifier(public,
private, default, protected)
All variables and methods in a interface are
declaredas public.
Variables in a class can be static, final or
neither. All variables are static and final.
19. Final Keyword In Java
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
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
20. 11. }
12. }
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
1. final void run(){System.out.println("running...");}
2. }
3. class Honda2 extends Bike{
4. public static void main(String args[]){
5. new Honda2().run();
6. }
7. }
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
21. Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent class
and child class have same fields.
class Animal{
1. String color="white";
2. }
3. class Dog extends Animal{
4. String color="black";
5. void printColor(){
6. System.out.println(color);//prints color of Dog class
7. System.out.println(super.color);//prints color of Animal class
8. }
9. }
10. class TestSuper1{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. d.printColor();
14. }}
Test it Now
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use
super keyword.
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
22. 1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Test it Now
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog
class, it will call the eat() method of Dog class by default because priority is given to local.
To call the parent class method, we need to use super keyword.
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
23. 9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Test it Now
Output:
animal is created
dog is created
this keyword in Java:
this is a reference variable that refers to the current object. ) 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 a nd parameters, this keyword
resolves the problem of ambiguity.
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 (imlicitly)
3. this() can be used to invoke current class constructor
class A
{
int x;
A(int x)
{
this.x=x;
System.out.print(x);
}
24. }
public class Main
{
public static void main(String[] args) {
A a1=new A(49);
}
}
o/p:49
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword
while invoking the method. Let's see the example
class A
{
void disp()
{
System.out.println("hi");
}
void show()
{
this.disp();
System.out.print("bi");
}
}
public class Main
{
25. public static void main(String[] args) {
A a1=new A();
a1.show();
o/p: hi bi
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for
constructor chaining.
class A
{
A()
{
System.out.println("hi");
}
A(int x)
{
this();
System.out.println("bi");
}
}
public class Main
{
public static void main(String[] args) {
A a1=new A(10);
}
}
O/p:hi bi
26. What is constructor chaining in Java?
In constructor chain, a constructor is called from another constructor in the same class this process is
known as constructor chaining. It occurs through inheritance. In Java, constructor chaining is a
sequence of invoking constructors upon initializing an object. It is used when we want to invoke a number
of constructors, one after another by using only an instance.
We can achieve constructor chaining in two ways:
o Within the same class: If the constructors belong to the same class, we use this
o From the base class: If the constructor belongs to different classes (parent and child classes), we
use the super keyword to call the constructor from the base class.
Rules of Constructor Chaining
o An expression that uses this keyword must be the first line of the constructor.
o Order does not matter in constructor chaining.
o There must exist at least one constructor that does not use this
Constructor Calling form another Constructor
The calling of the constructor can be done in two ways:
o By using this() keyword: It is used when we want to call the current class constructor within the
same class.
o By using super() keyword: It is used when we want to call the superclass constructor from the
base class.
ConstructorChain.java
1. public class ConstructorChain
2. {
3. //default constructor
4. ConstructorChain()
5. {
6. this("Javatpoint");
7. System.out.println("Default constructor called.");
8. }
9. //parameterized constructor
10. ConstructorChain(String str)
11. {
12. System.out.println("Parameterized constructor called");
13. }
14. //main method
15. public static void main(String args[])
16. {
27. 17. //initializes the instance of example class
18. ConstructorChain cc = new ConstructorChain();
19. }
20. }
21. Output:
22.
Calling Super Class Constructor:
Sometimes, we need to call the superclass (parent class) constructor from the child class (derived class) in such cases, we use the super() keyword in the
derived class constructor. It is optional to write super() because JVM automatically puts it. It should always write in the first line. We get a syntax error if
we try to call a superclass constructor in the child class.
class der
{
der()
{
System.out.println("default");
}
der(int x,int y)
{
this();
System.out.print("par");
}
}
public class Main extends der{
Main()
{
28. super(10,30);
}
public static void main(String[] args) {
Main m=new Main();
}
}
O/P: default par
Daemon thread :
Daemon thread isa low priority thread that runs in background to perform tasks such as garbage collection.
Properties:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collectionsconceptswith the Fundamentals
of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparati on from learning
a language to DS Algo and many more, please refer Complete Interview Preparation Course.
They can not prevent the JVM from exiting when all the user threadsfinish their execution.
JVM terminatesitself when all user threadsfinish their execution
If JVM findsrunning daemonthread, it terminatesthe thread and after that shutdown itself. JVM doesnot care whether Daemon thread
is running or not.
It is an utmost low priority thread.