Java Notes
Java Notes
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.
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.
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.
Output:
1
2
3
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
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. }
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.
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.
1. <class_name>(){}
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
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.
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the
same values also.
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.
Output:
111 Karan
222 Aryan
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Output:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
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 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.
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
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
Yes, it is the current class instance (You cannot use return type yet it returns a value).
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.
Yes.
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.
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.
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?
1) String Literal
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
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.
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
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.
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.
SN Method Description
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.
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.
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.
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
21) iterator() It is used to get an iterator over the elements in the list in proper sequence.
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.
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.
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.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.
Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
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.
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.
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.
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:
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.
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.
Output:
hello a
10
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
Output:
Compile Time Error: Call to this must be first statement in constructor
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.
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
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:
Output:
Hello java
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.
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
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?
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[]
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.
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.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
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.
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
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.
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.
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:
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...
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...
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...
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
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 many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we
are going to learn the access modifiers only.
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
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. }
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.
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.
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.
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
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
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();
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.
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).
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.
Points to Remember
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.
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.
If you make any variable as final, you cannot change the value of final variable(It will be constant).
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.
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
try {
System.out.println(
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
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
try {
System.out.println(
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
class Multithread {
Thread object
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 (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.
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.
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");
OutputStream vs InputStream
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.
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.
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.
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
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);
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.
System class provides a static method console() that returns the singleton instance of Console class.
1. public static Console console(){}
Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Output
Enter password:
Password is: 123
Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.
Constructor Description
FileWriter(File file) Creates a new file. It gets file name in File object
.
Method Description
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
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
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
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>
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. */
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.
Java Socket programming is used for communication between the applications running on different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.
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.
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.
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.
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.
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.
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.
Method Description
public static InetAddress getByName(String host) throws It returns the instance of InetAddress
UnknownHostException containing LocalHost IP and name.
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
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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){}
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
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.
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. }
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. Statement stmt=con.createStatement();
/*
*7. close
*/
import java.io.*;
import java.sql.*;
class GFG {
String url
String query
Class.forName(
System.out.println(
Statement st = con.createStatement();
ResultSet rs
rs.next();
String name
System.out.println("Connection Closed....");