Naming Convention
Naming Convention
Naming Convention
A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc.), but it is not mandatory to follow that is why it is known as convention not rule.
Advantage:
By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does.
class name Interface name method name variable name package name constants name
should begin with uppercase letter and be a noun e.g.String,System,Thread etc. should begin with uppercase letter and be an adjective (whereever possible). e.g. Runnable,ActionListener etc. should begin with lowercase letter and be a verb. e.g. main(),print(),println(),actionPerformed() etc. should begin with lowercase letter e.g. firstName,orderNumber etc. should be in lowercase letter. e.g. java,lang,sql,util etc. should be in uppercase letter. e.g. RED,YELLOW,MAX_PRIORITY etc.
9. Annonymous Object 10. Creating multiple objects by one type In this page, we will learn about the objects and classes. In object-oriented programming, we design a program using objects and classes. Object is the physical entity whereas class is the logical entity. A class works as a template from which we create the objects.
Object
A real world entity that have state and behaviour is known as an object. For example: chair, table, pen etc. An object have three characterstics: state:represents the data of an object. behaviour:represents the behaviour of an object. identity:Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user, but is used internally by the JVM to identify each object uniquely. For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behaviour. Object is an instance of a class.Class is a template or blueprint from which objects are created.So object is the instance(result) of a class.
Class
A class is a group of objects that have common property. It is a template or blueprint from which objects are created. A class in java can contain: data member method constructor block
Syntax of class:
class <class_name>{ data member; method; }
int id;//data member (also instance variable) String name;//data member(also instance variable) public static void main(String args[]){ Student s1=new Student();//creating an object of Student System.out.println(s1.id+" "+s1.name); } } Output:0 null
Instance variable
A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.
Method
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
rollno=r; name=n; } void displayInformation(){System.out.println(rollno+" "+name);}//method public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } } Output:111 Karan 222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
There is given another example that maintains the records of Rectangle class. Its exaplanation is same as in the above Student class example. class Rectangle{ int length; int width; void insert(int l,int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} public static void main(String args[]){ Rectangle r1=new Rectangle(); Rectangle r2=new Rectangle(); r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } } Output:55 45
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object. If you have to use an object only once, annonymous object is a good approach.
class Calculation{ void fact(int int fact=1; for(int i=1;i<=n;i++){ fact=fact*i; } System.out.println("factorial is "+fact); } public static void main(String args[]){ new Calculation().fact(5);//calling method with annonymous object } } Output:55 45 n){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects Let's see the example:
class Rectangle{ int length; int width; void insert(int l,int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} public static void main(String args[]){ Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
Note: In java, Methood Overloading is not possible by changing return type of the method.
public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(10.5,10.5); obj.sum(20,20); } } Output:21.0 40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur: because there was problem:
class Calculation{ int sum(int a,int b){System.out.println(a+b);} double sum(int a,int b){System.out.println(a+b);} public static void main(String args[]){ Calculation obj=new Calculation(); int result=obj.sum(20,20); //Compile Time Error } } int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
class Simple{ public static void main(int a){ System.out.println(a); } public static void main(String args[]){ System.out.println("main() method invoked"); main(10); } } Output:main() method invoked 10
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.
class Calculation{ void sum(int a,long b){System.out.println(a+b);} void sum(int a,int b,int c){System.out.println(a+b+c);} public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(20,20);//now second int literal will be promoted to long obj.sum(20,20,20); } } Output:40 60
similar number of arguments, there will be ambiguity. //Program of method overloading with TypePromotion in case ambiguity class Calculation{ void sum(int a,long b){System.out.println("a method invoked");} void sum(long a,int b){System.out.println("b method invoked");} public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(20,20);//now ambiguity } } Output:Compile Time Error
Constructor
1. Types of constructors 1. Default Constructor 2. Parameterized Constructor 2. Constructor Overloading 3. Does constructor return any value 4. Copying the values of one object into another 5. Does constructor perform other task instead initialization Constructor is a special type of method that is used to initialize the state of an object. Constructor is invoked at the time of object creation. It constructs the values i.e. data for the object that is why it is known as constructor. Constructor is just like the instance method but it does not have any explicit return type.
Types of constructors
There are two types of constructors: 1. default constructor (no-arg constructor) 2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.
<class_name>(){}
Parameterized constructor
A constructor that have parameter is known as parameterized constructor.
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
//Program of constructor overloading class Student{ int id; String name; int age; Student(int i,String n){ id = i; name = n; } Student(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan",25); s1.display(); s2.display(); } } Output:111 Karan 0 222 Aryan 25
Constructor
Constructor is used to initialize the state of an object. Constructor must not have return type. Constructor is invoked implicitly. The java compiler provides a default constructor if you don't have any constructor. Constructor name must be same as the class name.
Method
Method is used to expose behaviour of an object. Method must have return type. Method is invoked explicitly. Method is not provided by compiler in any case. Method name may or may not be same as class name.
Copying the values of one object to another like copy constructor in C++
There are By By By many ways to copy the values of one object into another. They are: constructor assigning the values of one object into another clone() method of Object class
In this example, we are going to copy the values of one object into another using constructor. //Program of Copying the values of one object to another class Student{ int id; String name; Student(int i,String n){ id = i; name = n; } Student(Student s){ id = s.id; name =s.name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(s1); s1.display(); s2.display(); } } Output:111 Karan 111 Karan
static keyword
1. Static variable 2. Program of counter without static variable 3. Program of counter with static variable 4. Static method 5. Restrictions for static method 6. Why main method is static ? 7. Static block 8. Can we execute a program without main method ?
The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods and blocks. The static keyword belongs to the class than instance of the class. The static can be: 1. variable (also known as class variable) 2. method (also known as class method) 3. block
1) static variable
If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. The static variable gets memory only once in class area at the time of class loading.
Student(int r,String n){ rollno = r; name = n; } void display (){System.out.println(rollno+" "+name+" "+college);} public static void main(String args[]){ Student s1 = new Student (111,"Karan"); Student s2 = new Student (222,"Aryan"); s1.display(); s2.display(); } } Output:111 Karan ITS 222 Aryan ITS
class Counter{ int count=0;//will get memory when instance is created Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); }}
Output:1 1 1
class Counter{ static int count=0;//will get memory only once and retain its value Counter(){ count++; System.out.println(count); }
public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); }}
Output:1 2 3
2) static method
If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.
public static void main(String args[]){ Student.change(); Student s1 = new Student (111,"Karan"); Student s2 = new Student (222,"Aryan"); Student s3 = new Student (333,"Sonoo"); s1.display(); s2.display(); s3.display(); } } Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT
//Program of accessing non-static data member directly from static method main class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } } Output:Compile Time Error
3)static block:
Is used to initialize the static data member. It is excuted before main method at the time of classloading.
this keyword
1. this keyword 2. Usage of this keyword 1. to refer the current class instance variable 2. to invoke the current class constructor 3. to invoke the current class method 4. to pass as an argument in the method call 5. to pass as an argument in the constructor call 6. to return the current class instance 3. Proving this keyword There can be a lot of usage of this keyword. In java, this is a reference variable that refers to the current object.
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.
class student{ int id; String name; student(int id,String name){ id = id; name = name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ student s1 = new student(111,"Karan"); student s2 = new student(321,"Aryan"); s1.display(); s2.display(); } } Output:0 null 0 null
In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable.
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
Student e1 = new Student(111,"karan"); Student e2 = new Student(222,"Aryan"); e1.display(); e2.display(); } } Output: default constructor is invoked default constructor is invoked 111 Karan 222 Aryan
class Student{ int id; String name; Student (){System.out.println("default constructor is invoked");} Student(int id,String name){ id = id; name = name; this ();//must be the first statement } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student e1 = new Student(111,"karan"); Student e2 = new Student(222,"Aryan"); e1.display(); e2.display(); } } Output:Compile Time Error
3)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example class S{ void m(){ System.out.println("method is invoked"); } void n(){ this.m();//no need because compiler does it for you. } void p(){ n();//complier will add this to invoke n() method as this.n() } public static void main(String args[]){
Output:10
Example of this keyword that you return as a statement from the method
class A{ A getA(){ return this; } void msg(){System.out.println("Hello java");} } class Test{ public static void main(String args[]){ new A().getA().msg(); } } Output:Hello java
Syntax of Inheritance
class Subclass-name extends Superclass-name { //methods and fields } The keyword extends indicates that you are making a new class that derives from an existing class. In the terminology of Java, a class that is inherited is called a superclass. The new class is called a subclass.
Example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
class Employee{ int salary=40000; } class Programmer extends Employee{ int bonus=10000; Public Static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Output:Programmer salary is:40000 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:
Note:Multiple inheritance is not supported in java in case of class. When a class extends two classes i.e. known as multiple inheritance.For Example:
class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were Public Static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } }
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship. Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.
class Employee{ int id; String name; Address address;//Address is a class ... }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
class Operation{ int square(int n){ return n*n; } } class Circle{ Operation op;//aggregation double pi=3.14; double area(int radius){ op=new Operation(); int rsquare=op.square(radius);//code reusability (i.e. delegates the method call). return pi*rsquare; }
public static void main(String args[]){ Circle c=new Circle(); double result=c.area(5); System.out.println(result); } }
Output:78.5
Address.java
public class Address { String city,state,country; public Address(String city, String state, String country) { super(); this.city = city; this.state = state; this.country = country; } }
Emp.java
public class Emp { int id; String name; Address address; public Emp(int id, String name,Address address) { this.id = id; this.name = name; this.address=address; } void display(){ System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country); } public static void main(String[] args) { Address address1=new Address("gzb","UP","india"); Address address2=new Address("gno","UP","india"); Emp e=new Emp(111,"varun",address1); Emp e2=new Emp(112,"arun",address2); e.display(); e2.display(); } }
Rules for Method Overriding: 1. method must have same name as in the parent class 2. method must have same parameter as in the parent class.
//Problem without method overriding class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike extends Vehicle{ public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } } Output:Vehicle is running Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.
Method Overloading
1) Method overloading is used to increase the readability of the program. 2) method overlaoding is performed within a class. 3) In case of method overloading parameter must be different.
Method Overriding
Method overriding is used to provide the specific implementation of the method that is already provided by its super class. Method overriding occurs in two classes that have IS-A relationship. In case of method overriding parameter must be same.
Access Modifiers
1. private access modifier 2. Role of private constructor 3. default access modifier 4. protected access modifier 5. public access modifier
6. Applying access modifer with method overriding There are two types of modifiers access modifier and non-access modifier. The access modifiers specifies accessibility (scope) of a datamember, method, constructor or class. There are 4 types of access modifiers: 1. private 2. default 3. protected 4. public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.
1) private
The private access modifier is accessible only within class.
void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A();//Compile Time Error } }
2) default
If you don't use any modifier, it is treated as default modifier bydefault. The default modifier is accessible only within package.
3) protected
The protected access modifier is accessible within package and outside the package by only through inheritance. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modiers.
//save by A.java package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Output:Hello
class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");}//C.T.Error public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } The default modifier is more restrictive than protected. That is why there is compile time error.
2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.
void msg(){System.out.println("parent");} } class Child extends Parent{ void msg()throws ArithmeticException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new Child(); p.msg(); } } Output:child
import java.io.*; class Parent{ void msg()throws ArithmeticException{System.out.println("parent");} } class Child extends Parent{ void msg()throws Exception{System.out.println("child");} public static void main(String args[]){ Parent p=new Child(); try{ p.msg(); }catch(Exception e){} } } Output:Compile Time Error
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.
As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.
super keyword:
super is a reference variable that is used to refer immediate parent class object.
class Vehicle{ int speed=50; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(speed);//will print speed of Bike } public static void main(String args[]){ Bike b=new Bike(); b.display(); } } Output:100 In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish
between parent class instance variable and current class instance variable. Solution by super keyword //example of super keyword class Vehicle{ int speed=50; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(super.speed);//will print speed of Vehicle now } public static void main(String args[]){ Bike b=new Bike(); b.display(); } } Output:50
class Vehicle{ Vehicle(){System.out.println("Vehicle is created");} } class Bike extends Vehicle{ Bike(){ super();//will invoke parent class constructor System.out.println("Bike is created"); }
public static void main(String args[]){ Bike b=new Bike(); } } Output:Vehicle is created Bike is created Note:super() is added in each class construtor automatically by compiler.
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the consructor.
Another example of super keyword where super() is provided by the compiler implicitely.
class Vehicle{ Vehicle(){System.out.println("Vehicle is created");} } class Bike extends Vehicle{ int speed; Bike(int speed){ this.speed=speed; System.out.println(speed); } public static void main(String args[]){
class Person{ void message(){System.out.println("welcome");} } class Student extends Person{ void message(){System.out.println("welcome to java");} void dislay(){ message();//will invoke current class message() method super.message();//will invoke parent class message() method } public static void main(String args[]){ Student s=new Student(); s.display(); } }
Output:welcome to java welcome In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.
class Person{ void message(){System.out.println("welcome");} } class Student extends Person{ void dislay(){ message();//will invoke parent class message() method } public static void main(String args[]){ Student s=new Student(); s.display(); } }
Output:welcome
Que) What is the use of instance initializer block while we can directly assign a value in instance data member? For example:
//Program of instance initializer block class Bike{ int speed; Bike(){System.out.println("constructor is invoked");} {System.out.println("instance initializer block invoked");} public static void main(String args[]){ Bike b1=new Bike(); Bike b2=new Bike(); } } Output:instance initializer block invoked constructor is invoked instance initializer block invoked constructor is invoked In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the costructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in every constructor.
A(){ System.out.println("parent class constructor invoked"); } } class B extends A{ B(){ super(); System.out.println("child class constructor invoked"); } {System.out.println("instance initializer block is invoked");} public static void main(String args[]){ B b=new B(); } }
Output:parent class constructor invoked instance initializer block is invoked child class constructor invoked
//Another example of instance initializer block that is invoked after super() class A{ A(){ System.out.println("parent class constructor invoked"); } } class B extends A{ B(){ super();
System.out.println("child class constructor invoked"); } B(int a){ super(); System.out.println("child class constructor invoked "+a); } {System.out.println("instance initializer block is invoked");} public static void main(String args[]){ B b1=new B(); B b2=new B(10); } }
Output:parent class constructor invoked instance initializer block is invoked child class constructor invoked parent class constructor invoked instance initializer block is invoked child class constructor invoked 10
final keyword:
1. Final variable 2. Final method 3. Final class 4. Is final method inherited ? 5. Blank final variable 6. Static blank final variable 7. Final parameter 8. Can you declare a final constructor
<<prev
next>>
The final keyword in java is used to restrict the user. The 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, that have no value it is called blank 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)final variable:
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike obj=new obj.run(); } } Output:Compile Time Error Bike();
2)final method
If you make any method as final, you cannot override it.
void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output:Compile Time Error
3)final class:
If you make any class as final, you cannot extend it.
final class Bike{} class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } }
public Static void main(String args[]){ Bike b=new Bike(); b.cube(5); } } Output:Compile Time Error
Abstraction
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Another way, it shows only important things to the user and hides the internal details. Abstraction lets you focus on what the object does instead of how it does it.
Abstract class
A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract class Bike{ abstract void run(); } class Honda extends Bike{ void run(){System.out.println("running safely..");} public static void main(String args[]){ Bike obj = new Honda(); obj.run(); } } Output:running safely..
abstract class Shape{ abstract void draw(); } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle extends Shape{
void draw(){System.out.println("drawing circle");} } class Test{ public static void main(String args[]){ Shape s=new Circle(); //In real scenario, Object is provided through factory method s.draw(); } } Output:drawing circle
//example of abstract class that have method body abstract class Bike{ abstract void run(); void changeGear(){System.out.println("gear changed");} } class Honda extends Bike{ void run(){System.out.println("running safely..");} public static void main(String args[]){ Bike obj = new Honda(); obj.run(); obj.changeGear(); } } Output:running safely.. gear changed //example of abstract class having constructor, field and method abstract class Bike { int limit=30;
Bike(){System.out.println("constructor is invoked");} void getDetails(){System.out.println("it has two wheels");} abstract void run(); } class Honda extends Bike{ void run(){System.out.println("running safely..");} public static void main(String args[]){ Bike obj = new Honda(); obj.run(); obj.getDetails(); System.out.println(obj.limit); } } Output:constructor is invoked running safely.. it has two wheels 30
Rule: If there is any abstract method in a class, that class must be abstract.
Rule: If you are extending any abstact class that have abstract method, you must either provide the implementation of the method or make this class abstract.
Note: If you are beginner to java, learn interface first and skip this example.
void d(); } abstract class B implements A{ public void c(){System.out.println("I am C");} } class M extends B{ public void a(){System.out.println("I am a");} public void b(){System.out.println("I am b");} public void d(){System.out.println("I am d");} } class Test{ public static void main(String args[]){ A a=new M(); a.a(); a.b(); a.c(); a.d(); }} Output:I I I I am am am am a b c d
Interface
1. Interface 2. Example of Interface 3. Multiple inheritance by Interface 4. Why multiple inheritance is supported in Interface while it is not supported in case of
It is used to achieve fully abstraction. By interface, we can support the functionality of multiple inheritance. It can be used to achieve loose coupling.
The java compiler converts methods of interface as public and abstract, data members as public,final and static bydefault.
} class A implements printable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A obj = new A(); obj.print(); } }
Output:Hello
interface printable{ void print(); } interface Showable{ void show(); } class A implements printable,Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ A obj = new A(); obj.print();
obj.show(); } }
Output:Hello Welcome
Que) Multiple inheritance is not supported in case of class but it is supported in case of interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class. But it is supported in case of interface because there is no ambiguity as implmentation is provided by the implementation class. For example:
interface Printable{ void print(); } interface Showable{ void print(); } class A implements Printable,Showable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A obj = new A(); obj.print(); } }
Output:Hello As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class A, so there is no ambiguity.
Note: A class implements interface but One interface extends another interface .
interface Printable{ void print(); } interface Showable extends Printable{ void show(); } class A implements Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} public static void main(String args[]){ A obj = new A(); obj.print(); obj.show(); } }
Output:Hello Welcome
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
Runtime Polymorphism
1. Runtime Polymorphism 2. Upcasting 3. Example of Runtime Polymorphism 4. Runtime Polymorphism with data members Runtime polymorphism or dynamic method dispatch is a process in which a call to an
overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.For example:
A a=new B();//upcasting
class Bike{ void run(){System.out.println("running");} } class Splender extends Bike{ void run(){System.out.println("running safely with 60km");} public static void main(String args[]){ Bike b = new Splender();//upcasting
class Bike{ int speedlimit=90; } class Honda extends Bike{ int speedlimit=150; public static void main(String args[]){ Bike obj=new Honda(); System.out.println(obj.speedlimit);//90 } } Output: 90
About type:
class Dog{ public static void main(String args[]){ Dog d1;//Here d1 is a type of Dog } }
static binding:
When type of the object is determined at compiled time(by the compiler), it is known as static binding. If there is any private,final or static method in a class,it is static binding.
class Dog{ private void eat(){System.out.println("dog is eating...");} public static void main(String args[]){
Dynamic binding:
When type of the object is determined at run-time, it is known as dynamic binding.
class Animal{ void eat(){System.out.println("animal is eating...");} } class Dog extends Animal{ void eat(){System.out.println("dog is eating...");} public static void main(String args[]){ Animal a=new Dog(); a.eat(); } } Output:dog is eating... In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
instanceof operator
1. The instanceof operator 2. Example of instanceof operator 3. Applying the instanceof operator with a variable the have null value 4. Downcasting with instanceof operator 5. Downcasting without instanceof operator The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).
The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false.
class Simple{ public static void main(String args[]){ Simple s=new Simple(); System.out.println(s instanceof Simple);//true } } Output:true An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of Dog can be reffered by either Dog or Animal class.
class Animal{} class Dog extends Animal{//Dog inherits Animal public static void main(String args[]){ Dog d=new Dog(); System.out.println(d instanceof Animal);//true } } Output:true
Let's see the example given below where we apply instanceof operator with the variable that have null value.
class Dog{ public static void main(String args[]){ Dog d=null; System.out.println(d instanceof Dog);//false } } Output:false
Dog d=new Animal();//Compilation error If we perform downcasting by typecasting, ClassCastException is thrown at runtime.
class Animal { } class Dog extends Animal { static void method(Animal a) { if(a instanceof Dog){ Dog d=(Dog)a;//downcasting System.out.println("ok downcasting performed"); }
} public static void main (String [] args) { Animal a=new Dog(); Dog.method(a); } } Output:ok downcasting performed
class Animal { } class Dog extends Animal { static void method(Animal a) { Dog d=(Dog)a;//downcasting System.out.println("ok downcasting performed"); } public static void main (String [] args) { Animal a=new Dog(); Dog.method(a); } } Output:ok downcasting performed Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast it, it is fine. But what will happen if we write:
Animal a=new Animal(); Dog.method(a); //Now ClassCastException but not in case of instanceof operator
interface Printable{} class A implements Printable{ public void a(){System.out.println("my a method");} } class B implements Printable{ public void b(){System.out.println("my a method");} } class Call{ void invoke(Printable p){//upcasting if(p instanceof A){ A a=(A)p;//Downcasting a.a(); } if(p instanceof B){ B b=(B)p;//Downcasting b.b(); } } }//end of Call class class Test{ public static void main(String args[]){ Printable p=new B(); Call c=new Call(); c.invoke(p); } }
Package
1. Package 2. Example of package 3. Accessing package 1. By import packagename.*
2. By import packagename.classname 3. By fully qualified name 4. Subpackage 5. Sending class file to another directory 6. -classpath switch 7. 4 ways to load the class file or jar file 8. How to put two public class in a package 9. Static Import 10. Package class A package is a group of similar types of classs, interfaces and sub-packages. Package can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. In this page, we will have the detailed learning of creating user-defined packages.
Advantage of Package
Package is used to categorize the classes and interfaces so that they can be easily maintained. Package provids access protection. Package removes naming collision.
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages. The import keyword is used to make the classes and interface of another package accessible to the current package.
If you import package.classname then only declared class of this package will be accessible but not subpackages.
package pack; public class A{ public void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.A; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } } Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
Output:Hello
Note: Sequence of the program must be package then import then class.
Subpackage
Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.
Example of Subpackage
package com.javatpoint.core; class Simple{ public static void main(String args[]){ System.out.println("Hello subpackage"); } } To Compile: javac -d . Simple.java To Run: java com.javatpoint.core.Simple Output:Hello subpackage
Note: If you import a package, all the classes and interface of that package will be imported excluding the classes and interfaces of the subpackages. Hence, you need to import the subpackage as well.
//save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides. e:\sources> set classpath=c:\classes;.; e:\sources> java mypack.Simple
Rule: There can be only one public class in a java source file and it must be saved by the public class name.
//save as C.java otherwise Compilte Time Error class A{} class B{} public class C{}
Static Import:
The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.
import static java.lang.System.*; class StaticImportExample{ public static void main(String args[]){ out.println("Hello");//Now no need of System.out out.println("Java"); } }
Output:Hello Java
Package class
The package class provides methods to get information about the specification and implementation of a package. It provides methods such as getName(), getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.
class PackageInfo{ public static void main(String args[]){ Package p=Package.getPackage("java.lang"); System.out.println("package name: "+p.getName());
System.out.println("Specification Title: "+p.getSpecificationTitle()); System.out.println("Specification Vendor: "+p.getSpecificationVendor()); System.out.println("Specification Version: "+p.getSpecificationVersion()); System.out.println("Implementaion Title: "+p.getImplementationTitle()); System.out.println("Implementation Vendor: "+p.getImplementationVendor()); System.out.println("Implementation Version: "+p.getImplementationVersion()); System.out.println("Is sealed: "+p.isSealed());
} }
Output:package name: java.lang Specification Title: Java Plateform API Specification Specification Vendor: Sun Microsystems, Inc. Specification Version: 1.6 Implemenation Title: Java Runtime Environment Implemenation Vendor: Sun Microsystems, Inc. Implemenation Version: 1.6.0_30 IS sealed: false
Access Modifiers
1. private access modifier 2. Role of private constructor 3. default access modifier 4. protected access modifier 5. public access modifier 6. Applying access modifer with method overriding There are two types of modifiers access modifier and non-access modifier. The access modifiers specifies accessibility (scope) of a datamember, method, constructor or class. There are 4 types of access modifiers: 1. private 2. default 3. protected 4. public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.
1) private
2) default
If you don't use any modifier, it is treated as default modifier bydefault. The default modifier is accessible only within package.
3) protected
The protected access modifier is accessible within package and outside the package by only through inheritance. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
package pack; public class A{ protected void msg(){System.out.println("Hello");} } //save by B.java package mypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } } Output:Hello
4) public
The public access modifier is accessible everywhere. It has the widest scope among all other modiers.
obj.msg(); } } Output:Hello
class A{ protected void msg(){System.out.println("Hello java");} } public class Simple extends A{ void msg(){System.out.println("Hello java");}//C.T.Error public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } } The default modifier is more restrictive than protected. That is why there is compile time error.
Encapsulation
Encapsulation is a process of wrapping code and data together into a single unit. It is a way to achieve data hiding.
Simple example:
//save as Student.java package mypack; public class student{ private string name; public String getName(){ return name; } public void setName(String name){
this.name=name } } package mypack; class Test public static void main(){ Student s=new Student(); s.setname("vijay"); System.out.println(s.getName()); } }
class Student implements Cloneable{ int rollno; String name; Student(int rollno,String name){ this.rollno=rollno; this.name=name; }
public Object clone()throws CloneNotSupportedException{ return super.clone(); } public static void main(String args[]){ try{ Student s1=new Student(101,"amit"); Student s2=(Student)s1.clone(); System.out.println(s1.rollno+" "+s1.name); System.out.println(s2.rollno+" "+s2.name); }catch(CloneNotSupportedException c){} } } Output:101 amit 101 amit
Object class
The Object class is the super class of all the classes in java. The Object is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting. The Object class provides some common behaviours to all the objects such as object can be compared, object can be cloned, object can be notified etc.
5. public String toString() returns the string representation of this object. 6. public final void notify() wakes up single thread, waiting on this object's monitor. 7. public final void notifyAll() wakes up all the threads, waiting on this object's monitor. 8. public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified miliseconds, until another thread notifies (invokes notify() or notifyAll() method). 9. public final void wait(long timeout,int nanos)throws InterruptedExceptioncauses the current thread to wait for the specified miliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). 10. public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). 11. protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected. We will have the detailed learning of these methods in next chapters.
Array in Java
Normally, array is a collection of similar type of elements that have contigious memory location. In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed elements in an array. Array is index based, first element of the array is stored at 0 index.
Advantage of Array
Code Optimization: It makes the code optimized, we can retrive or sort the data easily. Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array. Single Dimensional Array Multidimensional Array
class B{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
Output:10 20 70 40 50
We can declare, instantiate and initialize the java array together by:
class B{ public static void main(String args[]){ int a[]={33,3,4,5};//declaration, instantiation and initialization //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
Output:33 3 4 5
We can pass the array in the method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
class B{ static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5}; min(a);//passing array in the method }}
Output:3
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
class B{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i
Output:1 2 3 2 4 5 4 4 5
In java, array is an object. For array object, an proxy class is created whose name can be obtained by getClass().getName() method on the object.
class B{ public static void main(String args[]){ int arr[]={4,4,5}; Class c=arr.getClass(); String name=c.getName(); System.out.println(name); } }}
Output:[I
Copying an array
public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length )
class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }
Output:caffein
class Operation{ int data=50; void change(int data){ data=data+100;//changes will be in the local variable only }
public static void main(String args[]){ Operation op=new Operation(); System.out.println("before change "+op.data); op.change(500); System.out.println("after change "+op.data); } }
class Operation2{ int data=50; void change(Operation op){ op.data=op.data+100;//changes will be in the instance variable }
public static void main(String args[]){ Operation2 op=new Operation2(); System.out.println("before change "+op.data); op.change(op);//passing object System.out.println("after change "+op.data); } }
Output:before change 50
strictfp keyword
The strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic.
package com.abc; /** This class is a user-defined class that contains one methods cube.*/ public class M{ /** The cube method prints cube of the given number */ public static void } cube(int n){System.out.println(n*n*n);}
To create the document API, you need to use the javadoc tool followed by java file name. There is no need to compile the javafile. On the command prompt, you need to write:
javadoc M.java to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get the information about the classes.
class A{ public static void main(String args[]){ System.out.println("first argument is: "+args[0]); } }
compile by > javac A.java run by > java A sonoo jaiswal 1 3 abc
String Handling
1. String Handling 2. How to create string objects? 1. String literal
2. new keyword 3. Why Java uses the concept of String literal? String Handling provides a lot of concepts that can be performed on a string such as concatinating string, comparing string, substring etc. In java, string is basically an immutable object. We will discuss about immutable string later. Let's first understand what is string and how we can create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.
Do You Know ?
Why String objects are immutable ? How to create an immutable class ? What is string constant pool ? What code is written by the compiler if you concat any string by + (string concatenation operator) ? What is the difference between StringBuffer and StringBuilder class ?
1) String literal:
String literal is created by double quote.For Example: String s="Hello"; 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 returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example: String s1="Welcome"; String s2="Welcome";//no new object will be created
In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new object whether will return the reference to the same instance. Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
2) By new keyword:
String s=new String("Welcome");//creates two objects and one reference variable In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).
Immutable String:
In java, strings are immutable (unmodifiable) objects.For example class Simple{ public static void main(String args[]){ String s="Sachin"; s.concat(" Tendulkar");//concat() method appends the string at the end System.out.println(s);//will print Sachin because strings are immutable objects } }
Output:Sachin
As you can see in the above figure that two objects will be created but no reference variable refers to "Sachin Tendulkar".But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example: class Simple{ public static void main(String args[]){ String s="Sachin"; s=s.concat(" Tendulkar"); System.out.println(s); } }
Output:Sachin Tendulkar
String comparison:
There 1. 2. 3. are By By By three ways to compare String objects: equals() method = = operator compareTo() method
1) By equals() method:
equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods: public boolean equals(Object another){} compares this string to the specified object. public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.
//Example of equals(Object) method class Simple{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//false } }
//Example of equalsIgnoreCase(String) method class Simple{ public static void main(String args[]){ String s1="Sachin"; String s2="SACHIN"; System.out.println(s1.equals(s2));//false System.out.println(s1.equalsIgnoreCase(s3));//true } }
Output:false true
2) By == operator:
The = = operator compares references not values. //Example of == operator class Simple{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); System.out.println(s1==s2);//true (because both refer to same instance) System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool) } }
Output:true false
3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. Suppose s1 and s2 are two string variables.If: s1 == s2 :0 s1 > s2 :positive value s1 < s2 :negative value
//Example of compareTo() method: class Simple{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3="Ratan"; System.out.println(s1.compareTo(s2));//0 System.out.println(s1.compareTo(s3));//1(because s1>s3) System.out.println(s3.compareTo(s1));//-1(because s3 < s1 ) } }
Output:0 1 -1
String Concatenation:
There are two ways to concat string objects: 1. By + (string concatenation) operator 2. By concat() method
String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString(); String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation operator can concat not only string but primitive values also.For Example:
class Simple{ public static void main(String args[]){ String s=50+30+"Sachin"+40+40; System.out.println(s);//80Sachin4040 } }
Output:80Sachin4040 Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string. Syntax:public String concat(String another){} //Example of concat(String) method class Simple{ public static void main(String args[]){ String s1="Sachin ";
Output:Sachin Tendulkar
Substring:
You can get substring from the given String object by one of the two methods: 1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive). 2. public String substring(int startIndex,int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
In case of string: startIndex:starts from index 0(inclusive). endIndex:starts from index 1(exclusive).
Example:
//Example of substring() method class Simple{ public static void main(String args[]){ String s="Sachin Tendulkar"; System.out.println(s.substring(6));//Tendulkar System.out.println(s.substring(0,6));//Sachin } }
Output:Sachin Tendulkar
First seven methods have already been discussed.Now Let's take the example of other methods:
//Example of toUpperCase() and toLowerCase() method class Simple{ public static void main(String args[]){ String s="Sachin"; System.out.println(s.toUpperCase());//SACHIN System.out.println(s.toLowerCase());//sachin System.out.println(s);//Sachin(no change in original) } }
trim() method:
//Example of trim() method class Simple{ public static void main(String args[]){ String s=" Sachin "; Sachin
System.out.println(s);// } }
System.out.println(s.trim());//Sachin
Output:
Sachin Sachin
Output:true true
charAt() method:
//Example of charAt() method class Simple{ public static void main(String args[]){ String s="Sachin"; System.out.println(s.charAt(0));//S System.out.println(s.charAt(3));//h } }
Output:S h
length() method:
//Example of length() method class Simple{ public static void main(String args[]){ String s="Sachin"; System.out.println(s.length());//6 } }
Output:6
intern() method:
A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. //Example of length() method class Simple{ public static void main(String args[]){ String s=new String("Sachin"); String s2=s.intern(); System.out.println(s2);//Sachin } }
Output:Sachin
StringBuffer class:
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as String except it is mutable i.e. it can be changed.
Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an order.
class A{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.append("Java");//now original string is changed
class A{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } }
class A{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo } }
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class A{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.delete(1,3); System.out.println(sb);//prints Hlo } }
class A{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } }
StringBuffer sb=new StringBuffer(); System.out.println(sb.capacity());//default 16 sb.append("Hello"); System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language"); System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 } }
class A{ public static void main(String args[]){ StringBuffer sb=new StringBuffer(); System.out.println(sb.capacity());//default 16 sb.append("Hello"); System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language"); System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 sb.ensureCapacity(10);//now no change System.out.println(sb.capacity());//now 34 sb.ensureCapacity(50);//now (34*2)+2 System.out.println(sb.capacity());//now 70 } }
StringBuilder class:
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK1.5.
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } }
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } }
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.replace(1,3,"Java"); System.out.println(sb);//prints HJavalo }
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.delete(1,3); System.out.println(sb);//prints Hlo } }
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder("Hello"); sb.reverse(); System.out.println(sb);//prints olleH } }
from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder(); System.out.println(sb.capacity());//default 16 sb.append("Hello"); System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language"); System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 } }
class A{ public static void main(String args[]){ StringBuilder sb=new StringBuilder(); System.out.println(sb.capacity());//default 16 sb.append("Hello"); System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language"); System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 sb.ensureCapacity(10);//now no change System.out.println(sb.capacity());//now 34 sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70 } }
public final class Employee{ final String pancardNumber; public Employee(String pancardNumber){ this.pancardNumber=pancardNumber; } public String getPancardNumber(){ return pancardNumber; } }
The above class is immutable because: The instance variable of the class is final i.e. we cannot change the value of it after creating an object. The class is final so we cannot create the subclass. There is no setter methods i.e. we have no option to change the value of the instance variable. These points makes this class as immutable.
object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
this.rollno=rollno; this.name=name; this.city=city; } public String toString(){//overriding the toString() method return rollno+" "+name+" "+city; } public static void main(String args[]){ Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad"); System.out.println(s1);//compiler writes here s1.toString() System.out.println(s2);//compiler writes here s2.toString() } }
Exception
Dictionary Meaning:Exception is an abnormal condition. In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.
statement 1; statement 2; statement 3; statement 4; statement 5; statement 6; statement 7; statement 8; statement 9; statement 10; Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be excecuted i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling.
Do You Know ?
What is the difference between checked and unchecked exceptions ? What happens behind the code int data=50/0; ? Why use multiple catch block ? Is there any possibility when finally block is not executed ? What is exception propagation ? What is the difference between throw and throws keyword ? What are the 4 rules for using exception handling with method overriding ?
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions: 1. Checked Exception 2. Unchecked Exception 3. Error
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3)Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
int a=50/0;//ArithmeticException
have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
try block
Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.
catch block
Catch block is used to handle the Exception. It must be used after the try block.
class Simple{ public static void main(String args[]){ int data=50/0; System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:/ by zero As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is not printed. Let's see what happens behind the scene:
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: Prints out exception description. Prints the stack trace (Hierarchy of methods where the exception occurred). Causes the program to terminate. But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
int data=50/0; }catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code... Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.
Rule:At a time only one Exception is occured and at a time only one catch block is executed. Rule:All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .
class Excep4{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){System.out.println("common task completed");} catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} System.out.println("rest of the code..."); } }
Output:Compile-time error
Syntax:
.... try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e)
{ } } catch(Exception e) { } ....
Example:
Example of nested try block class Excep6{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println("other statement); }catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } }
finally block
The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc.
Note:Before terminating the program, JVM executes finally block(if any). Note:finally must be followed by try or catch block.
case 1
Program in case exception does not occur class Simple{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Output:5 finally block is always executed rest of the code...
case 2
Program in case exception occured but not handled class Simple{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Output:finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero
case 3
Program in case exception occured and handled
class Simple{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:/ by zero finally block is always executed rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block. Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
throw keyword
The throw keyword is used to explictily throw an exception. We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:not valid
Exception propagation:
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.
In the above example exception occurs in m() method where it is not handled,so it is propagated to previous n() method where it is not handled, again it is propagated to p() method where exception is handled. Exception can be handled in any method in call stack either in main() method,p() method,n() method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
class Simple{ void m(){ throw new java.io.IOException("device error");//checked exception } void n(){ m(); } void p(){ try{ n();
}catch(Exception e){System.out.println("exception handeled");} } public static void main(String args[]){ Simple obj=new Simple(); obj.p(); System.out.println("normal flow"); } } Output:Compile Time Error
throws keyword
The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained. Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
Example which describes that checked exceptions can be propagated by throws keyword.
In this example, we are going to see that checked exception also propagates if method declares an exception (i.e. specifies throws keyword with the exception class).
import java.io.IOException; class Simple{ void m()throws IOException{ throw new IOException("device error");//checked exception } void n()throws IOException{ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled");} } public static void main(String args[]){ Simple obj=new Simple(); obj.p(); System.out.println("normal flow..."); } } Output:exception handled normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases: 1. Case1:You caught the exception i.e. handle the exception using try/catch. 2. Case2:You declare the exception i.e. specifying throws with the method.
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
Example of handling the exception if exception occurs in the method which declares an exception
import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } }
class Test{ public static void main(String args[]){ try{ M m=new M(); m.method(); }catch(Exception e){System.out.println("exception handled");} System.out.println("normal flow..."); } } Output:exception handled normal flow...
A) Program of declaring the exception if exception does not occur in the method which declares an exception
import java.io.*;
class Test{ public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } } Output:device operation performed normal flow...
B)Example of declaring the exception if exception occurs in the method which declares an exception
import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } }
class Test{ public static void main(String args[])throws IOException{//declare exception M m=new M(); m.method(); System.out.println("normal flow..."); } }
Output:Runtime Exception
throws is used to declare an exception. checked exception can be propagated with throws. throws is followed by class. throws is used with the method signature. You can declare multiple exception e.g. public void method()throws IOException,SQLException.
import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class Child extends Parent{ void msg()throws IOException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new Child(); p.msg(); } } Output:Compile Time Error
2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.
import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class Child extends Parent{ void msg()throws ArithmeticException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new Child(); p.msg(); } } Output:child
1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
import java.io.*; class Parent{ void msg()throws ArithmeticException{System.out.println("parent");} } class Child extends Parent{ void msg()throws Exception{System.out.println("child");} public static void main(String args[]){ Parent p=new Child(); try{ p.msg(); }catch(Exception e){} } } Output:Compile Time Error
import java.io.*; class Parent{ void msg()throws Exception{System.out.println("parent");} } class Child extends Parent{ void msg()throws Exception{System.out.println("child");} public static void main(String args[]){ Parent p=new Child();
import java.io.*; class Parent{ void msg()throws Exception{System.out.println("parent");} } class Child extends Parent{ void msg()throws ArithmeticException{System.out.println("child");} public static void main(String args[]){ Parent p=new Child(); try{ p.msg(); }catch(Exception e){} } } Output:child
import java.io.*; class Parent{ void msg()throws Exception{System.out.println("parent");} } class Child extends Parent{
void msg(){System.out.println("child");} public static void main(String args[]){ Parent p=new Child(); try{ p.msg(); }catch(Exception e){} } } Output:child
Custom Exception :
If you are creating your own Exception that is known as custom exception or userdefined exception. //Example of custom exception class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class Excep13{ static void validate(int age)throws InvalidAgeException{ if(age Output:Exception occured: InvalidAgeException:not valid rest of the code...
Do You Know ?
What is the internal code generated by the compiler for member inner class ? What are the two ways to create annonymous inner class ? Can we access the non-final local variable inside the local inner class ? How to access the static nested class ? Can we define an interface within the class ? Can we define a class within the interface ?
Que) What is the difference between nested class and inner class?
Inner class is a part of nested class. Non-static nested classes are known as nested classes.
In this example, we are invoking the method of member inner class from the display method of Outer class.
class Outer{ private int data=30; class Inner{ void msg(){System.out.println("data is "+data);} } void display(){ Inner in=new Inner(); in.msg(); } public static void main(String args[]){ Outer obj=new Outer(); obj.display(); } } Output:data is 30
//Program of member inner class that is invoked outside a class class Outer{ private int data=30; class Inner{ void msg(){System.out.println("data is"+data);} } } class Test{ public static void main(String args[]){ Outer obj=new Outer(); Outer.Inner in=obj.new Inner(); in.msg(); } } Output:data is 30
<<prev
next>>
Person p=new Person(){ void eat(){System.out.println("nice fruits");} }; } } 1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method. 2. An object of Annonymous class is created that is reffered by p reference variable of Person type. As you know well that Parent class reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class
import java.io.PrintStream; static class Emp$1 extends Person { Emp$1(){} void eat() { System.out.println("nice fruits"); } }
What does the compiler for annonymous inner class created by interface
It performs two main tasks behind this code:
} } 1. A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method. 2. An object of Annonymous class is created that is reffered by p reference variable of Eatable type. As you know well that Parent class reference variable can refer the object of Child class.
The internal code generated by the compiler for annonymous inner class created by interface
import java.io.PrintStream; static class Emp$1 implements Eatable { Emp$1(){} void eat(){System.out.println("nice fruits");} }
class Simple{ private int data=30;//instance variable void display(){ class Local{ void msg(){System.out.println(data);} } Local l=new Local(); l.msg(); } public static void main(String args[]){ Simple obj=new Simple(); obj.display(); }
} Output:30
import java.io.PrintStream; class Simple$1Local { final Simple this$0; Simple$1Local() { super(); this$0 = Simple.this; } void msg() { System.out.println(Simple.access$000(Simple.this)); } }
class Simple{ private int data=30;//instance variable void display(){ int value=50;//local variable must be final class Local{ void msg(){System.out.println(value);}//C.T.Error } Local l=new Local(); l.msg(); } public static void main(String args[]){ Simple obj=new Simple(); obj.display(); } } Output:Compile Time Error
class Simple{ private int data=30;//instance variable void display(){ final int value=50;//local variable must be final class Local{ void msg(){System.out.println(data+" "+value);}//ok } Local l=new Local(); l.msg(); } public static void main(String args[]){ Simple obj=new Simple(); obj.display(); } } Output:30 50
A static class that is created inside a class is known as static nested class. It cannot access the non-static members. It can access static data members of outer class including private. static nested class cannot access non-static (instance) data member or method.
class Outer{ static int data=30; static class Inner{ void msg(){System.out.println("data is "+data);} } public static void main(String args[]){ Outer.Inner obj=new Outer.Inner(); obj.msg(); } }
Output:data is 30 In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object.
import java.io.PrintStream; static class Outer$Inner { Outer$Inner(){} void msg(){ System.out.println((new StringBuilder()).append("data is ")
.append(Outer.data).toString()); } }
class Outer{ static int data=30; static class Inner{ static void msg(){System.out.println("data is "+data);} } public static void main(String args[]){ Outer.Inner.msg();//no need to create the instance of static nested class } }
Output:data is 30
Nested Interface
An interface which is declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly.
interface Showable{ void show(); interface Message{ void msg(); } } class Test implements Showable.Message{ public void msg(){System.out.println("Hello nested interface");} public static void main(String args[]){ Showable.Message message=new Test();//upcasting here message.msg(); } }
Internal code generated by the java compiler for nested interface Message
The java compiler internally creates public and static interface as displayed below:.
class A{ interface Message{ void msg(); } } class Test implements A.Message{ public void msg(){System.out.println("Hello nested interface");} public static void main(String args[]){ A.Message message=new Test();//upcasting here message.msg(); } }