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

Java Notes

Uploaded by

dhritihimasus1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Java Notes

Uploaded by

dhritihimasus1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Static methods:

The static keyword in Java


is used for memory management mainly. We can apply static keyword with variables
, methods, blocks and nested classes
. The static keyword belongs to the class than an instance of the class.

The static can be:


1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.


o The static variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).


Understanding the problem without static variable

1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

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

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

Java static property is shared to all objects.

Example of static variable


1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
Test it Now

Output:
111 Karan ITS
222 Aryan ITS
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. }
18. Output:
19. 1
20. 1
21. 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);
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. }

Output:
1
2
3

2) Java static method

If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
Example of static method

1. //Java Program to demonstrate the use of a static method.


2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }

Q) 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.
3) Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
Example of static block

1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }

Q) 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. }
7. Output:
8. static block is invoked
9. Since JDK 1.7 and above, output would be:
10. Error: Main method not found in class A3, please define the main method as:
11. public static void main(String[] args)
12. or a JavaFX application class must extend javafx.application.Application

Constructors in Java

In Java
, a constructor is a block of codes similar to the method. It is called when an instance of the class
is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a
default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.


1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:


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

Java Default Constructor

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

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 of object creation.

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Output:
Bike is created

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Example of default constructor that displays the default values

1. //Let us see another example of default constructor


2. //which displays the default values
3. class Student3{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }

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

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the
same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any
number of parameters in the constructor.

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


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }

Output:
111 Karan
222 Aryan

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.

Constructor overloading in Java


is a technique of having more than one constructor with different parameter lists. They are arranged in a way that
each constructor performs a different task. They are differentiated by the compiler by the number of parameters in
the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
1. class Student5{
2. int id;
3. String name;
4. int age;
5. //creating two arg constructor
6. Student5(int i,String n){
7. id = i;
8. name = n;
9. }
10. //creating three arg constructor
11. Student5(int i,String n,int a){
12. id = i;
13. name = n;
14. age=a;
15. }
16. void display(){System.out.println(id+" "+name+" "+age);}
17.
18. public static void main(String args[]){
19. Student5 s1 = new Student5(111,"Karan");
20. Student5 s2 = new Student5(222,"Aryan",25);
21. s1.display();
22. s2.display();
23. }
24. }

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 Java Method

A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you don't have any The method is not provided by the
constructor in a class. compiler in any case.

The constructor name must be same as the class name. The method name may or may not be
same as the class name.

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from 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:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

In this example, we are going to copy the values of one object into another using Java constructor.
1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }

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.

class Student7{
1. int id;
2. String name;
3. Student7(int i,String n){
4. id = i;
5. name = n;
6. }
7. Student7(){}
8. void display(){System.out.println(id+" "+name);}
9.
10. public static void main(String args[]){
11. Student7 s1 = new Student7(111,"Karan");
12. Student7 s2 = new Student7();
13. s2.id=s1.id;
14. s2.name=s1.name;
15. s1.display();
16. s2.display();
17. }
18. }
Output:
111 Karan
111 Karan

Q) Does constructor return any value?

Yes, it is the 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 a method, etc. You can perform any operation in the constructor as
you perform in the method.

Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is
found in the java.lang.reflect package.
Constructor overloading in Java

In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept of
having more than one constructor with different parameters so that every constructor can perform a different task.

Consider the following Java program, in which we have used different constructors in the class.

Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }

Java String

In Java
, string is basically an object that represents sequence of char values. An array
of characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(),
split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters. String, StringBuffer
and StringBuilder
classes implement it. It means, we can create strings in Java by using these three classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is
created. For mutable strings, you can use StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let's first understand what String in Java is and how to create the String
object.

What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters.
The java.lang.String class is used to create a string object.
How to create a string object?

There are two ways to create String object:


1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the
pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string object with the value
"Welcome" in string constant pool that is why it will create a new object. After that it will find the string with the
value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.
Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant
pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM


will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the
string constant pool. The variable s will refer to the object in a heap (non-pool).

Java String Example

StringExample.java
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Test it Now

Output:
java
strings
example

The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console
using println() method.

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.


4 static String format(Locale l, String format, Object... args) It returns formatted string with
given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.

6 String substring(int beginIndex, int endIndex) It returns substring for given


begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string.

9 static String join(CharSequence delimiter, Iterable<? extends It returns a joined string.


CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence new) It replaces all occurrences of the


specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It


doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char


value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char


value index starting with given
index.
21 int indexOf(String substring) It returns the specified substring
index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring


index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string.


It is an overloaded method.

Java Vector

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements
in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.util package
and implements the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the
thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws the
ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-


o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections framework.

Java Vector class Declaration


1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable

Java Vector Constructors

Vector class supports four types of constructors. These are given below:

SN Constructor Description
1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial capacity and w
capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the specified initial capacity and ca
capacityIncrement) increment.

4) Vector( Collection<? extends E> c) It constructs a vector that contains the elements of a collection c.

Java Vector Methods

The following are the list of Vector class methods:

SN Method Description

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to the end of this Vector.

3) addElement() It is used to append the specified component to the end of this vector. It increases the vector
one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the specified collection.

9) copyInto() It is used to copy the components of the vector into the specified array.

10) elementAt() It is used to get the component at the specified index.

11) elements() It returns an enumeration of the components of a vector.

12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It ensures that the
can hold at least the number of components specified by the minimum capacity argument.

13) equals() It is used to compare the specified object with the vector for equality.

14) firstElement() It is used to get the first component of the vector.

15) forEach() It is used to perform the given action for each element of the Iterable until all elements hav
processed or the action throws an exception.

16) get() It is used to get an element at the specified position in the vector.
17) hashCode() It is used to get the hash code value of a vector.

18) indexOf() It is used to get the index of the first occurrence of the specified element in the vector. It retur
the vector does not contain the element.

19) insertElementAt() It is used to insert the specified object as a component in the given vector at the specified index

20) isEmpty() It is used to check if this vector has no components.

21) iterator() It is used to get an iterator over the elements in the list in proper sequence.

22) lastElement() It is used to get the last component of the vector.

23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the vector. It retur
the vector does not contain the element.

24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.

25) remove() It is used to remove the specified element from the vector. If the vector does not contain the el
it is unchanged.

26) removeAll() It is used to delete all the elements from the vector that are present in the specified collection.

27) removeAllElements() It is used to remove all elements from the vector and set the size of the vector to zero.

28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from the vector.

29) removeElementAt() It is used to delete the component at the specified index.

30) removeIf() It is used to remove all of the elements of the collection that satisfy the given predicate.

31) removeRange() It is used to delete all of the elements from the vector whose index is between fromIndex, inc
and toIndex, exclusive.

32) replaceAll() It is used to replace each element of the list with the result of applying the operator to that elem

33) retainAll() It is used to retain only that element in the vector which is contained in the specified collection

34) set() It is used to replace the element at the specified position in the vector with the specified eleme

35) setElementAt() It is used to set the component at the specified index of the vector to the specified object.

36) setSize() It is used to set the size of the given vector.

37) size() It is used to get the number of components in the given vector.

38) sort() It is used to sort the list according to the order induced by the specified Comparator.

39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the list.

40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive, and toIndex, excl
41) toArray() It is used to get an array containing all of the elements in this vector in correct order.

42) toString() It is used to get a string representation of the vector.

43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.

Java Vector Example


1. import java.util.*;
2. public class VectorExample {
3. public static void main(String args[]) {
4. //Create a vector
5. Vector<String> vec = new Vector<String>();
6. //Adding elements using add() method of List
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Adding elements using addElement() method of Vector
12. vec.addElement("Rat");
13. vec.addElement("Cat");
14. vec.addElement("Deer");
15.
16. System.out.println("Elements are: "+vec);
17. }
18. }
Test it Now

Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Java Vector Example 2


1. import java.util.*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Check size and capacity
12. System.out.println("Size is: "+vec.size());
13. System.out.println("Default capacity is: "+vec.capacity());
14. //Display Vector elements
15. System.out.println("Vector element is: "+vec);
16. vec.addElement("Rat");
17. vec.addElement("Cat");
18. vec.addElement("Deer");
19. //Again check size and capacity after two insertions
20. System.out.println("Size after addition: "+vec.size());
21. System.out.println("Capacity after addition is: "+vec.capacity());
22. //Display Vector elements again
23. System.out.println("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if(vec.contains("Tiger"))
26. {
27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
28. }
29. else
30. {
31. System.out.println("Tiger is not present in the list.");
32. }
33. //Get the first element
34. System.out.println("The first animal of the vector is = "+vec.firstElement());
35. //Get the last element
36. System.out.println("The last animal of the vector is = "+vec.lastElement());
37. }
38. }
Test it Now

Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
this keyword in Java

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.


1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usages of this keyword.
1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance
variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Test it Now

Output:
0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this
keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:
111 ankit 5000.0
112 sumit 6000.0

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in
the following program:

Program where this keyword is not required


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int r,String n,float f){
6. rollno=r;
7. name=n;
8. fee=f;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis3{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:
111 ankit 5000.0
112 sumit 6000.0

It is better approach to use meaningful names for variables. So we use same name for instance variables and parameters
in real time, and always use this keyword.

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

1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
Test it Now

Output:
hello n
hello m
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.

Calling default constructor from parameterized constructor:


1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Test it Now

Output:
hello a
10

Calling parameterized constructor from default constructor:


1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Test it Now

Output:
5
hello a
Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain
between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the
actual use of this keyword.
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now

Output:
111 ankit java 0.0
112 sumit java 6000.0

Rule: Call to this() must be the first statement in constructor.


1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this.fee=fee;
12. this(rollno,name,course);//C.T.Error
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis8{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now

Output:
Compile Time Error: Call to this must be first statement in constructor

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see
the example:
1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
Test it Now

Output:
method is invoked
Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse
one object in many methods.

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's
see the example:
1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Test it Now
Output:10

6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return type of the method must be the
class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }
Test it Now

Output:
Hello java

Proving this keyword

Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the
reference variable and this, output of both variables are same.
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now

Output:
A5@22b3ea59
A5@22b3ea59
Method Overloading in Java

If a class has multiple methods having same name but different in 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 behavior 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

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second add
method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now

Output:
22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer
arguments and second add method receives two double arguments.
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Test it Now

Output:
22
24.9

Q) Why Method Overloading is not possible by changing the return type of method only?

In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
Let's see how ambiguity may occur:
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now

Output:
Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method overloading.
But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }
Output:
main with String[]

Method Overloading and Type Promotion

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.

Example of Method Overloading with TypePromotion


1. class OverloadingCalculation1{
2. void sum(int a,long 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. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Output:40
60
Java Garbage Collection

In java, garbage means unreferenced objects.

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

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.
So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

How can an object be unreferenced?

There are many ways:


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

1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;

2) By assigning a reference to another:


1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:
1. new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to
perform cleanup processing. This method is defined in Object class as:
1. protected void finalize(){}

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

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System
and Runtime classes.
1. public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize()
method before object is garbage collected.

Simple Example of garbage collection in java


1. public class TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }

object is garbage collected


object is garbage collected
Java Object finalize() Method

Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize()
method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.

Syntax
1. protected void finalize() throws Throwable

Throw

Throwable - the Exception is raised by this method

Example 1
1. public class JavafinalizeExample1 {
2. public static void main(String[] args)
3. {
4. JavafinalizeExample1 obj = new JavafinalizeExample1();
5. System.out.println(obj.hashCode());
6. obj = null;
7. // calling garbage collector
8. System.gc();
9. System.out.println("end of garbage collection");
10.
11. }
12. @Override
13. protected void finalize()
14. {
15. System.out.println("finalize method called");
16. }
17. }
Output:
2018699554
end of garbage collection
finalize method called
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


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

The syntax of Java Inheritance


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

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of
"extends" is to increase the functionality.HTML Tutorial

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child
or subclass.
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship
between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

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

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about
interfaces later.
Note: Multiple inheritance is not supported in Java through class.

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

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.

File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:
barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below,
BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below,
Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:
meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have
the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So
whether you have same method or different, there will be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the
class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside
the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package through
child class. If you do not make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside
the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we
are going to learn the access modifiers only.

Understanding Java Access Modifiers

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

Access Modifier within class within package outside package by subclass only outside
package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier


In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.
1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

Note: A class cannot be private or protected except nested class.

2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more
restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java
1. package pack;
2. class A{
3. void msg(){System.out.println("Hello");}
4. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the
package.

3) Protected

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the
class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be
accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello

Java Access Modifiers with Method Overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

class A{
1. protected void msg(){System.out.println("Hello java");}
2. }
3.
4. public class Simple extends A{
5. void msg(){System.out.println("Hello java");}//C.T.Error
6. public static void main(String args[]){
7. Simple obj=new Simple();
8. obj.msg();
9. }
10. }

The default modifier is more restrictive than protected. That is why, there is a compile-time error.
Dynamic Method Dispatch or Runtime Polymorphism in Java

Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is
the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.
 When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the object being
referred to at the time the call occurs. Thus, this determination is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the reference variable) that
determines which version of an overridden method will be executed
 A superclass reference variable can refer to a subclass object. This is also known as upcasting. Java uses this
fact to resolve calls to overridden methods at run time.

Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects
are referred to through a superclass reference variable, different versions of the method are executed

// A Java program to illustrate Dynamic Method


// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}

Method Overriding in Java

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

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its
parent class, it is known as method overriding.

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding

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

Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of
interest.
Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in Java.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java


1. Abstract class
2. Interface

Points to Remember

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
Understanding the real scenario of Abstract class

In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and Circle classes.
Another example of Abstract class in java
Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and
even main() method.

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

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. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because
final variable once assigned a value can never be changed.

2) Java final method


If you make any method as final, you cannot override it.
Example of final method
3) Java final class

If you make any class as final, you cannot extend it.

Example of final class


static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be
initialized only in static block.
Multithreading in Java

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum
utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a
process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the
Thread class. A thread begins its life inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread object.

 Java

// Java code for thread creation by extending

// the Thread class

class MultithreadingDemo extends Thread {


public void run()

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

// Main Class

public class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

MultithreadingDemo object
= new MultithreadingDemo();

object.start();

Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we
instantiate a Thread object and call start() method on this object.

 Java

// Java code for thread creation by implementing

// the Runnable Interface

class MultithreadingDemo implements Runnable {

public void run()

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");
}

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

// Main Class

class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

Thread object

= new Thread(new MultithreadingDemo());

object.start();

Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple
inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt
methods like yield(), interrupt() etc. that are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst multiple threads.

Java I/O Tutorial

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for
input and output operations.

We can perform file handling in Java by Java I/O API.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream
of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.


1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or
socket.
InputStream

Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or
socket.

Let's understand the working of Java OutputStream and InputStream by the figure given below.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An
output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description

1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException is used to write an array of byte to the current output stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1 at the end of th
IOException

2) public int available()throws IOException returns an estimate of the number of bytes that can be read from the curren
stream.

3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy

Java Console Class

The Java Console class is be used to get input from console. It provides methods to read texts and passwords.

If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.
Let's see a simple example to read text from console.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console class declaration

Let's see the declaration for Java.io.Console class:


1. public final class Console extends Object implements Flushable

Java Console class methods

Method Description

Reader reader() It is used to retrieve the reader object associated with the console

String readLine() It is used to read a single line of text from the console.

String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single line of text from
the console.

char[] readPassword() It is used to read password that is not being displayed on the
console.
char[] readPassword(String fmt, Object... It provides a formatted prompt then reads the password that is not
args) being displayed on the console.

Console format(String fmt, Object... args) It is used to write a formatted string to the console output stream.

Console printf(String format, Object... It is used to write a string to the console output stream.
args)

PrintWriter writer() It is used to retrieve the PrintWriter object associated with the
console.

void flush() It is used to flushes the console.

How to get the object of Console

System class provides a static method console() that returns the singleton instance of Console class.
1. public static Console console(){}

Let's see the code to get the instance of Console class.


1. Console c=System.console();

Java Console Example


1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }

Output
Enter your name: Nakul Jain
Welcome Nakul Jain

Java Console Example to read password


1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }

Output
Enter password:
Password is: 123

Java FileWriter Class

Java FileWriter class is used to write character-oriented data to a file


. It is character-oriented class which is used for file handling in java
.

Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.

Java FileWriter class declaration

Let's see the declaration for Java.io.FileWriter class:


1. public class FileWriter extends OutputStreamWriter

Constructors of FileWriter class

Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string


.

FileWriter(File file) Creates a new file. It gets file name in File object
.

Methods of FileWriter class

Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.


void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Java FileWriter Example

In this example, we are writing the data in the file testout.txt using Java FileWriter class.
1. package com.javatpoint;
2. import java.io.FileWriter;
3. public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");
7. fw.write("Welcome to javaTpoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12. }

Output:
Success...

testout.txt:
Welcome to javaTpoint.
Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside
the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:


o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet
o Plugin is required at client browser to execute applet.
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Compo

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an
applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.


1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used
for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet


1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet
code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After
that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */

To execute the applet by appletviewer tool, write in command prompt:


c:\>javac First.java
c:\>appletviewer First.java

Socket overview
A socket is one endpoint of a two way communication link between two programs running on the network. The
socket mechanism provides a means of inter-process communication (IPC) by establishing named contact points
between which the communication take place.
Like ‘Pipe’ is used to create pipes and sockets is created using ‘socket’ system call. The socket provides
bidirectional FIFO Communication facility over the network. A socket connecting to the network is created at each
end of the communication. Each socket has a specific address. This address is composed of an IP address and a
port number.
Socket are generally employed in client server applications. The server creates a socket, attaches it to a network
port addresses then waits for the client to contact it. The client creates a socket and then attempts to connect to
the server socket. When the connection is established, transfer of data takes place.
Types of Sockets :
There are two types of Sockets: the datagram socket and the stream socket.
1. Datagram Socket :
This is a type of network which has connection less point for sending and receiving packets. It is similar to
mailbox. The letters (data) posted into the box are collected and delivered (transmitted) to a letterbox
(receiving socket).
2. Stream Socket
In Computer operating system, a stream socket is type of interprocess communications socket or network
socket which provides a connection-oriented, sequenced, and unique flow of data without record boundaries
with well defined mechanisms for creating and destroying connections and for detecting errors. It is similar to
phone. A connection is established between the phones (two ends) and a conversation (transfer of data) takes
place.

Function Call Description

Create() To create a socket

Bind() It’s a socket identification like a telephone number to contact

Listen() Ready to receive a connection

Connect() Ready to act as a sender


Function Call Description

Accept() Confirmation, it is like accepting to receive a call from a sender

Write() To send data

Read() To receive data

Close() To close a connection

Java Socket Programming

Java Socket programming is used for communication between the applications running on different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:


1. IP Address of Server, and
2. Port number.

Here, we are going to make one-way client and server communication. In this application, client sends a message to
the server, server reads the message and prints it. Here, two classes are being used: Socket and ServerSocket. The
Socket class is used to communicate client and server. Through this class, we can read and write message. The
ServerSocket class is used at server-side. The accept() method of ServerSocket class blocks the console until the
client is connected. After the successful connection of client, it returns the instance of Socket at server-side.
Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a
socket.

Important methods

Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish communication with the
clients.
Important methods

Method Description

1) public Socket accept() returns the socket and establish a connection between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming

Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are using 6666 port
number for the communication between the client and server. You may also choose any other port number. The
accept() method waits for the client. If clients connects with the given port number, it returns an instance of Socket.

1. ServerSocket ss=new ServerSocket(6666);


2. Socket s=ss.accept();//establishes connection and waits for the client

Creating Client:

To create the client application, we need to create the instance of Socket class. Here, we need to pass the IP address
or hostname of the Server and a port number. Here, we are using "localhost" because our server is running on same
system.

1. Socket s=new Socket("localhost",6666);

Let's see a simple of Java socket programming where client sends a text and server receives and prints it.

File: MyServer.java

1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

File: MyClient.java

1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
download this example

To execute this program open two command prompts and execute each program at each command prompt as
displayed in the below figure.

After running the client application, a message will be displayed on the server console.
Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server then server will receive and print the text. Then server will write
to the client and client will receive and print the text. The step goes on.

File: MyServer.java

1. import java.net.*;
2. import java.io.*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
7. DataInputStream din=new DataInputStream(s.getInputStream());
8. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
9. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10.
11. String str="",str2="";
12. while(!str.equals("stop")){
13. str=din.readUTF();
14. System.out.println("client says: "+str);
15. str2=br.readLine();
16. dout.writeUTF(str2);
17. dout.flush();
18. }
19. din.close();
20. s.close();
21. ss.close();
22. }}

File: MyClient.java

1. import java.net.*;
2. import java.io.*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream(s.getInputStream());
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9.
10. String str="",str2="";
11. while(!str.equals("stop")){
12. str=br.readLine();
13. dout.writeUTF(str);
14. dout.flush();
15. str2=din.readUTF();
16. System.out.println("Server says: "+str2);
17. }
18.
19. dout.close();
20. s.close();
21. }}
Java InetAddress class

Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of
any host name for example www.javatpoint.com, www.google.com, www.facebook.com, etc.

An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP
address with its corresponding host name. There are two types of addresses: Unicast and Multicast. The Unicast is an
identifier for a single interface whereas Multicast is an identifier for a set of interfaces.

Moreover, InetAddress has a cache mechanism to store successful and unsuccessful host name resolutions.

IP Address
o An IP address helps to identify a specific resource on the network using a numerical representation.
o Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge among the
destination and the source.

There are two versions of IP address:

1. IPv4

IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARAPNET in 1983. It
is a widely used IP version to differentiate devices on network using an addressing scheme. A 32-bit addressing
scheme is used to store 232 addresses that is more than 4 million addresses.

Features of IPv4:
o It is a connectionless protocol.
o It utilizes less memory and the addresses can be remembered easily with the class based addressing scheme.
o It also offers video conferencing and libraries.

2. IPv6

IPv6 is the latest version of Internet protocol. It aims at fulfilling the need of more internet addresses. It provides
solutions for the problems present in IPv4. It provides 128-bit address space that can be used to form a network of
340 undecillion unique IP addresses. IPv6 is also identified with a name IPng (Internet Protocol next generation).

Features of IPv6:
o It has a stateful and stateless both configurations.
o It provides support for quality of service (QoS).
o It has a hierarchical addressing and routing infrastructure.

TCP/IP Protocol
o TCP/IP is a communication protocol model used connect devices over a network via internet.
o TCP/IP helps in the process of addressing, transmitting, routing and receiving the data packets over the
internet.
o The two main protocols used in this communication model are:
1. TCP i.e. Transmission Control Protocol. TCP provides the way to create a communication channel
across the network. It also helps in transmission of packets at sender end as well as receiver end.
2. IP i.e. Internet Protocol. IP provides the address to the nodes connected on the internet. It uses a
gateway computer to check whether the IP address is correct and the message is forwarded correctly
or not.

Java InetAddress Class Methods

Method Description

public static InetAddress getByName(String host) throws It returns the instance of InetAddress
UnknownHostException containing LocalHost IP and name.

public static InetAddress getLocalHost() throws It returns the instance of InetAdddress


UnknownHostException containing local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.

Example of Java InetAddress Class

Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com website.

InetDemo.java
1. import java.io.*;
2. import java.net.*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=InetAddress.getByName("www.javatpoint.com");
7.
8. System.out.println("Host Name: "+ip.getHostName());
9. System.out.println("IP Address: "+ip.getHostAddress());
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
Test it Now

Output:
Host Name: www.javatpoint.com
IP Address: 172.67.196.82

Program to demonstrate methods of InetAddress class

InetDemo2.java
1. import java.net.Inet4Address;
2. import java.util.Arrays;
3. import java.net.InetAddress;
4. public class InetDemo2
5. {
6. public static void main(String[] arg) throws Exception
7. {
8. InetAddress ip = Inet4Address.getByName("www.javatpoint.com");
9. InetAddress ip1[] = InetAddress.getAllByName("www.javatpoint.com");
10. byte addr[]={72, 3, 2, 12};
11. System.out.println("ip : "+ip);
12. System.out.print("\nip1 : "+ip1);
13. InetAddress ip2 = InetAddress.getByAddress(addr);
14. System.out.print("\nip2 : "+ip2);
15. System.out.print("\nAddress : " +Arrays.toString(ip.getAddress()));
16. System.out.print("\nHost Address : " +ip.getHostAddress());
17. System.out.print("\nisAnyLocalAddress : " +ip.isAnyLocalAddress());
18. System.out.print("\nisLinkLocalAddress : " +ip.isLinkLocalAddress());
19. System.out.print("\nisLoopbackAddress : " +ip.isLoopbackAddress());
20. System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
21. System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
22. System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
23. System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
24. System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
25. System.out.print("\nisMulticastAddress : " +ip.isMulticastAddress());
26. System.out.print("\nisSiteLocalAddress : " +ip.isSiteLocalAddress());
27. System.out.print("\nhashCode : " +ip.hashCode());
28. System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
29. }
30. }
Output:

In the above Java code, the various boolean methods of InetAdress class are demonstrated.
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event
provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:


1. Register the component with the Listener
Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets
the position of the component it may be button, textfield etc.

2) Java event handling by outer class

1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }

1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }

3) Java event handling by anonymous class


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver c

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException


Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the classpath, and
then JDBC driver manager can detect and load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.


1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to
queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

Example to create the statement object

1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the
ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


1. ResultSet rs=stmt.executeQuery("select * from emp");
2. while(rs.next()){
3. System.out.println(rs.getInt(1)+" "+rs.getString(2));
4. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection int
used to close the connection.

Syntax of close() method


1. public void close()throws SQLException

Example to close connection


1. con.close();

// This code is for establishing connection with MySQL

// database and retrieving data

// from db Java Database connectivity

/*

*1. import --->java.sql

*2. load and register the driver ---> com.jdbc.

*3. create connection

*4. create a statement

*5. execute the query

*6. process the results

*7. close

*/

import java.io.*;

import java.sql.*;

class GFG {

public static void main(String[] args) throws Exception


{

String url

= "jdbc:mysql://localhost:3306/table_name"; // table details

String username = "rootgfg"; // MySQL credentials

String password = "gfg123";

String query

= "select *from students"; // query to be run

Class.forName(

"com.mysql.cj.jdbc.Driver"); // Driver name

Connection con = DriverManager.getConnection(

url, username, password);

System.out.println(

"Connection Established successfully");

Statement st = con.createStatement();

ResultSet rs

= st.executeQuery(query); // Execute query

rs.next();

String name

= rs.getString("name"); // Retrieve name from db

System.out.println(name); // Print result on console

st.close(); // close statement

con.close(); // close connection

System.out.println("Connection Closed....");

You might also like