What is this in java?

advertisement
Difference between constructor and method in java
Sl. No.
1
2
3
4
5
Java Constructor
Java Method
Constructor is used to initialize the state of
an object.
Constructor must not have return type.
Constructor is invoked implicitly.
The java compiler provides a default
constructor if you don't have any constructor.
Constructor name must be same as the class
name.
Method is used to expose behavior
of an object.
Method must have return type.
Method is invoked explicitly.
Method is not provided by compiler
in any case.
Method name may or may not be
same as class name.
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
class Student
{
int roll;
String name;
void display()
{
System.out.println(roll+" "+ name);
}
}
class Test
{
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student();
s1.display();
s2.display();
}
}
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.
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
class Student
{
int roll, age;
String name;
Student(int roll, String name)
{
this.roll = roll;
this.name= name;
}
Student(int roll, String name, int age)
{
this.roll = roll;
this.age = age;
this.name= name;
}
void display()
{
System.out.println(roll +" "+age+" "+name );
}
}
class Test
{
public static void main(String args[])
{
Student s1 =new Student(25,"Tom");
Student s2 =new Student(47,"Bill",21);
s1.display();
s2.display();
}
}
Why we use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Java parameterized constructor.
A constructor that have parameters is known as parameterized constructor.
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3.
4.
5.
6.
this
this
this
this
keyword can be used to invoke current class method (implicitly)
can be passed as an argument in the method call.
can be passed as argument in the constructor call.
keyword can also be used to return the current class instance.
class Math
{
int a;
void calculateSquare(int a)
{
int result = a * a;
System.out.println(result);
}
void multiply(int a)
{
int result = this.a * a;
System.out.println(result);
}
}
class Test
{
public static void main(String args[])
{
Math m = new Math();
m.a = 5;
m. calculateSquare(8);
m. multiply(12);
}
}
Output:
60
40
In the above example, parameter (formal arguments) and instance variables are same that
is why we are using this keyword to distinguish between local variable and instance
variable.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
1. Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
2. Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Can we override static method?
No, static method cannot be overridden.
Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.
Can we override java main method?
No, because main is a static method.
Difference between method Overloading and Method
Overriding in java
Sl. No.
Method Overloading
Method Overriding
1.
Method overloading is used to increase the
Method overriding is used to provide
readability of the program.
the specific implementation of the
method that is already provided by
its super class.
2
Method overloading is performed within
Method overriding occurs in two
class
classes that have IS-A (inheritance)
relationship.
3
In case of method overloading, parameter
In case of method
must be different.
overriding, parameter must be
same.
4
5
Method overloading is the example
Method overriding is the example
of compile time polymorphism.
of run time polymorphism.
In java, method overloading can't be
Return type must be same or
performed by changing return type of the
covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
Interfaces
A Java interface is used to specify what is to be done but not how it is to be done.
A Java interface consists of only final static variables and abstract methods. No
implementation is provided for the methods. We may declare the vehicle interface in the
following way:
public interface Vehicle {
// body
}
The interface may contain both variables and methods. Variables are implicitly final, static
and public. And the methods are implicitly abstract and public. Use of specifiers that
overwrite these default specifiers is not allowed. For example, both methods and variables
may not be declared with the public or protected specifiers. The reason behind this is the
same as discussed above with reference to the interface.
The following example shows the interface Vehicle with three abstract methods and a final
variable code.
public interface Vehicle {
int CODE = 347; // implicitly public and final
void start(); // method is implicitly public and abstract
public void stop(); // method is implicitly abstract
public abstract void changeSpeed(int newSpeed);
}
The variables declared in an interface should be initialised with default values as final
variables require that they be initialised at the time of declaration itself. A class which
implements this interface should provide the definition for all of the abstract methods. Given
below is an example.
public class Aeroplane implements Vehicle {
int speed;
public void start() {
System.out.println(" Taking off");
}
public void stop() {
System.out.println(" Taking landing");
}
public void changeSpeed(int s) {
speed = s;
}
}
The variable names used in the parameter list of the method name in this class and those
defined in the interface need not match as was the case always. We have used the variable
name s instead of newSpeed.
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample hello
Output: Your first argument is: hello
Example of command-line argument that prints all the
values
In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.
class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A hello world 1 3 abc
Output: hello
world
1
3
abc
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is why we
use exception handling. Let's take a scenario:
1. statement
2. statement
3. statement
4. statement
5. statement
6. statement
7. statement
8. statement
9. statement
10. statement
1;
2;
3;
4;
5;//exception occurs
6;
7;
8;
9;
10;
Suppose there is 10 statements in your program and there occurs an exception at
statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we
perform exception handling, rest of the exception will be executed. That is why we use
exception handling in java.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked
exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;
//
ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length()); // NullPointerException
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); // NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; // ArrayIndexOutOfBoundsException
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1.
2.
3.
4.
5.
try
catch
finally
throw
throws
Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
Java try block must be followed by either catch or finally block.
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Problem without exception handling
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1
{
public static void main(String args[])
{
int data=50/0; //may throw exception
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of
the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Solution by exception handling
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2
{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement
is printed.
Internal working of java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:



Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Java catch multiple exceptions
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
catch(Exception e)
{
System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}
Output: task1 completed
rest of the code...
Java finally block
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
1. throw exception;
Let's see the example of throw IOException.
1. throw new IOException("sorry device error);
java throw keyword example
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
{
throw new ArithmeticException("not valid");
}
else
{
System.out.println("welcome to vote");
}
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
What is JIT compiler?
Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation.Here the term “compiler” refers to a translator from
the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
What is difference between object oriented programming
language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance.
Examples of object based programming languages are JavaScript, VBScript etc.
What is constructor?
Constructor is just like a method that is used to initialize the state of an object. It is invoked
at the time of object creation.
What is the purpose of default constructor?
The default constructor provides the default values to the objects. The java compiler creates
a default constructor only if there is no constructor in the class.
Does constructor return any value?
yes, that is current instance (You cannot use return type yet it returns a value).
Is constructor inherited?
No, constructor is not inherited.
Can you make a constructor final?
No, constructor can't be final.
What is static variable?


static variable is used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of students etc.
static variable gets memory only once in class area at the time of class loading.
What is static method?



A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Why main method is static?
because object is not required to call static method if It were non-static method,jvm creats
object first then call main() method that will lead to the problem of extra memory
allocation.
What is static block?


Is used to initialize the static data member.
It is excuted before main method at the time of classloading.
Can we execute a program without main() method?
Yes, one of the way is static block.
What if the static modifier is removed from the signature of the
main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
What is this in java?
It is a keyword that that refers to the current object.
What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour of
another object of another class. It represents IS-A relationship. It is used for Code
Resusability and Method Overriding.
Which class is the superclass for every class.
Object class.
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java in case of class.
What is object cloning?
The object cloning is used to create the exact copy of an object.
What is method overriding:
If a subclass provides a specific implementation of a method that is already provided by its
parent class, it is known as Method Overriding. It is used for runtime polymorphism and to
provide the specific implementation of the method.
Can we override static method?
No, you can't override the static method because they are the part of class not object.
Why we cannot override static method?
It is because the static method is the part of class and it is bound with class whereas
instance method is bound with object and static gets memory in class area and instance
gets memory in heap.
What is final variable?
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
What is final method?
Final methods can't be overriden.
What is final class?
Final class can't be inherited.
What is blank final variable?
A final variable, not initalized at the time of declaration, is known as blank final variable.
What is Runtime Polymorphism?
Runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super
class. The determination of the method to be called is based on the object being referred to
by the reference variable.
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
1. static binding (also known as early binding).
2. dynamic binding (also known as late binding).
Understanding Type
Let's understand the type of instance.
1) variables have a type
Each variable has a type, it may be primitive and non-primitive.
int data=30;
Here data variable is a type of int.
2) References have a type
class Dog
{
public static void main(String args[])
{
Dog d1;//Here d1 is a type of Dog
}
}
3) Objects have a type
An object is an instance of particular java class, but it is also an instance of its superclass.
class Animal{}
class Dog extends Animal
{
public static void main(String args[])
{
Dog d1=new Dog();
}
}
Here d1 is an instance of Dog class, but it is also an instance of Animal.
Static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
class Dog
{
private void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal
{
void eat()
{
System.out.println("animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog();
a.eat();
}
}
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the
instance of Dog is also an instance of Animal. So compiler doesn't know its type, only its
base type.
Download