on Leave a Comment

OSI Model: Session Layer and its Functions

Session layer is also known as port layer. This layer provides a mechanism for managing conversation between communicating devices. Session layer set up a connection between communicating devices and if the connection is not used for  a long time, then the connection is closed or re-open. Connection may be either half duplex or full duplex. Session layer establishes, maintains and synchronizes the interaction among communication devices. Session layer is network dialog controller.

Functions of Session Layer

Dialog Control: Session layer allows communication between two processes. The communication may be in either half duplex mode or full duplex mode.

Synchronization: Session layer allows process to add synchronization points or check points. For example, if a communication device is sending a file of 600 pages, so it is recommendation to add checkpoints after each 60 pages to ensure that each 60 page is received or acknowledged independently. In a case, if a crash happens at page no 520, then there is no need to send previous 500 pages. 

Interaction Management: It allows presentation layer entities to interact each other and control its functions.

Token Management: Session layer provides tokens that can be exchanged between communicating parties and only the side having token can perform critical task.
 
on Leave a Comment

Java Program to Convert Octal Number to Decimal Number

This java program converts octal value to decimal value. First user enters any octal number and octal value is converted into decimal value and finally decimal equivalent is displayed on the screen.

Octal Number: The octal number system is the base-8 number system, and uses the digits 0 to 7.

Java Program to Convert Octal Number to Decimal Number

import java.util.Scanner;

public class OctToDec
{
    public static void main(String args[])
    {
        int octal, decimal=0, i=0;
        Scanner scan = new Scanner(System.in);
  
        System.out.print("Enter any Octal Number : ");
        octal = scan.nextInt();
  
        for( ; octal != 0; i++, octal = octal/10)
        {
            decimal = decimal + (octal%10) * (int) Math.pow(8, i);
        }
  
        System.out.print("Decimal Equivalent is " + decimal);
    }
}

Output:

Enter any Octal Number : 246
Decimal Equivalent is 166

on 2 comments

Hybrid Inheritance in Java with Example

We know that a class can inherits functionality of other class called inheritance. Hybrid inheritance is a type of inheritance. Hybrid inheritance is combination of both single inheritance and multiple inheritance. In java, we cannot implement multiple inheritance using classes. For example, java compiler shows error, if we write class A extends B, C.

We can achieve hybrid inheritance through interfaces. Because multiple inheritance can be achieve by interfaces.

Hybrid Inheritance in Java
Hybrid Inheritance in Java

Example of Hybrid Inheritance in Java

In this program, interface B & C extends interface A and class HybridInheritance implements interface B, C.

interface A {
    public void methodA();
}
interface B extends A {
    public void methodB();
}
interface C extends A {
    public void methodC();
}
class HybridInheritance implements B, C {
    public void methodA() {
        System.out.println("Calling methodA");
    
    }
    public void methodB() {
        System.out.println("Calling methodB");
    }
    public void methodC() {
        System.out.println("Calling methodC");
    }
    public static void main(String args[]) {
        HybridInheritance obj = new HybridInheritance();
        obj.methodA();
        obj.methodB();
        obj.methodC();
    }
}

Output:

Calling methodA
Calling methodB
Calling methodC


on Leave a Comment

Abstract Class and Methods in Java

In java, abstract class is declared with abstract keyword. An abstract class can contain both concrete (normal) method and abstract method. Abstract class is a way to achieve abstraction; however it does not provide 100% abstraction. 

Abstraction: It refers to hiding the background details and explanation of data and represents only essential information or functionality to the user.

Syntax of Abstract Class

abstract class class_name { }

Abstract Method

A method which is declared with abstract keyword and declared without any body is called abstract method. A class containing any abstract method then the class is declared as abstract class. Abstract method must be defined by its subclass; otherwise we must declare subclass as abstract class. If we do not defining abstract method in its subclass and do not declaring subclass as abstract, then we will get compile time error. Abstract method can never be final and static. 

Syntax of Abstract Method

abstract return_type function_name(); //no implementation

Example of Abstract Class with Non-Abstract Method

abstract class Example
{
	void show()
	{
		System.out.println("Abstract class with non-abstract method");
	}
}
class AbstractClass extends Example
{
	public static void main(String[] args) {
		AbstractClass obj = new AbstractClass();
		obj.show();
	}
}

Output:

Abstract class with non-abstract method

Example of Abstract Class with Abstract Method

abstract class Example
{
	abstract void show();
}
class AbstractClass extends Example
{
	void show()
	{
		System.out.println("Abstract class with abstract method");
	}
	public static void main(String[] args) {
		AbstractClass obj = new AbstractClass();
		obj.show();
	}
}

Output:

Abstract class with abstract method

Example of Abstract Class with Constructor

We can create object of an abstract class, so we can also define constructor in abstract class.

abstract class Example
{
	Example()
	{
		System.out.println("Abstract class Constructor");
	}
}
class AbstractClass extends Example
{
	public static void main(String[] args) {
		Example obj = new AbstractClass();		
	}
}

Output:

Abstract class Constructor

Usage of Abstract Class and Abstract Method

We know that a class containing any abstract method then the class is declared as abstract class. And an abstract method must be defined in its subclass. So, if we want overriding compulsory, then we can use abstract methods. 

Some Points about Abstract Class

We cannot instantiate abstract class directly.

Abstract class can contain both abstract method and non-abstract method.

Abstract class can have constructors and data members.

We cannot declare abstract constructor and abstract static method.

Abstract method must be defined in its subclass.

Abstract method can never be static and final.





on Leave a Comment

Interface in Java With Examples

In java, full abstraction can be achieved by interface. An interface is like a class, but it is very different from class. Like class, interface also contains variables and methods. But interface defines only final fields and abstract methods. In class, by default all members are of package level access modifier or default modifier. But in interface, all members are of public access modifier ad we can't change it. In interface, all variables are public, static and final and all methods are public and abstract.

Uses of Java Interface

It is used to achieve full abstraction.
To support the functionality of multiple inheritance.
It is also used to achieve loose coupling.

Syntax of Java Interface

interface InterfaceName
{
 //Variables Declaration
 //Methods Declaration
}

Example:

interface Example
{
    int a = 10;
    void show();
}

In interface, methods are declared without any body.

Example of Interface in Java

interface Example
{
 void setName(String n);
 void setAge(int x);
 /*
  Compiler will convert it as
  public abstract void setName(String n);
  public abstract void setAge(int x);
    */
}
class Student
{
 String name;
 int age;
 int rollno;
 void setName(String n)
 {
  name = n;
 }
 void setAge(int x)
 {
  age = x;
 }
 void setRollno(int r)
 {
  rollno = r;
 }
    void showDetails()
    {
     System.out.println("Name: "+name);
     System.out.println("Age: "+age);
     System.out.println("Roll no: "+rollno);
    }
}
class Testing
{
 public static void main(String[] args) {
  Student s = new Student();
  s.setName("John");
  s.setAge(17);
  s.setRollno(28);
                s.showDetails();
 }
}

Output:

Name: John
Age: 17
Roll no: 28

Interface and Inheritance

We know that a class cannot extents more than one class, but it can implements one or more interfaces. Like a class extends other class, an interface extends other interface.


Example 1:

interface I1
{
 public void display1();
}
interface I2
{
 public void display2();
}

class Testing implements I1,I2
{
 public void display1()
 {
  System.out.println("Interface I1");
 }
 public void display2()
 {
  System.out.println("Interface I2");
 }
 public static void main(String[] args) {
  Testing t = new Testing();
  t.display1();
  t.display2();
 }
}

Output:

Interface I1
Interface I2

Example 2:

interface I1
{
 public void display1();
}
interface I2 extends I1
{
 public void display2();
}

class Testing implements I2
{
 public void display1()
 {
  System.out.println("Interface I1");
 }
 public void display2()
 {
  System.out.println("Interface I2");
 }
 public static void main(String[] args) {
  Testing t = new Testing();
  t.display1();
  t.display2();
 }
}

Output:

Interface I1
Interface I2

Why we cannot create instance of an interface?

We know that variables are by default static in an interface. And static variables do not belongs to object. This is the reason why there is no constructor in interface. We already know that when an object creates constructor automatically calls. So interface does not have constructor and instance variable, this is the reason why we cannot create instance of an interface.






on Leave a Comment

OSI Model: Transport Layer and its Function

The transport layer is responsible for delivery of entire message from source to destination. We know that the network layer ensures the delivery of individual packets, but its treats every packet individually and does not recognize the relationship between packets. The transport layer ensures that whole message transmits in an order way, ensures error control. Transport layer provides reliability through error control and flow control at source to destination level.

Examples of transport layer protocols are TCP/IP and UDP.

Functions of Transport Layer

Service Point Addressing: There are many programs running on a computer at the same time. Transport layer is responsible for process to process delivery of entire message. For process to process delivery of transmission, transport layer header includes service point address also known as port address. As network layer gets packets to the correct computer, transport layer gets message to the correct process on a computer.

Segmentation and Reassembling: Transport layer divides the message into segments and each segment contains a sequence number. The segment number enables transport layer to reassemble the message. When message is reassembled correctly upon arrival at the destination, this layer identifies and replaces packets which were lost in transmission.

Connection Control: The transport layer can be of two types, either connectionless or connection-oriented. In connectionless transport layer, each segment is considered as independent packets and delivers it to transport layer at destination machine. In connection-oriented transport layer, a connection is established with transport layer at destination machine before delivering packets. The connection is terminated when all data are transferred.

Flow Control: Flow control in this layer is performed process to process.

Error Control: Transport layer is also responsible error control. Error control is performed process to process. The sending transport layer ensures that message arrives at destination machine without any error.

on Leave a Comment

Java Program to Count Number of Digits in Integer

This java program counts number of digits in an integer. First, user has to enter any positive integer. If user enter negative integer, then converts it into positive integer and if user enters 0, then convert it into 1. 

Steps to count number of digits in integer:

1. Check if number is greater than 0.
2. Then, divide number by 10.
3. Increments the count variable by 1.
4. Again, go to step 1, if condition in step 1 is true, then executes further steps, otherwise exit the loop.

Java Program to Count Number of Digits in Integer

import java.util.Scanner;
class CountDigits { public static void main(String[] args) { int num, count = 0, temp; Scanner scan = new Scanner(System.in); System.out.print("Enter a Positive Integer : "); num = scan.nextInt(); temp = num; //Check if entered number is less than zero if(num<0) { num=num * -1; } //Check if number is equals to zero else if(num==0) { num=1; } for(; num>0; num = num/10, count++) { } System.out.println("Number of Digits in "+temp+" is "+count); } }

Output:

Enter a Positive Integer : 6321
Number of Digits in 6321 is 4

on Leave a Comment

Inheritance in Java

Inheritance is a process by which one class acquires properties (data members and methods) of another class. It is very essential feature of object oriented programming. Most important aspect of inheritance is reusability. We have to only unique features in derived class, other common features is extended from the base class. 

Derived Class: The class that inherits the properties (data members and methods) of base class.

Base Class: The class whose properties (data members and methods) are extended by derived class.

Uses of Java Inheritance

- Code Reusability
- Method overriding (runtime polymorphism)
- Save time for writing same code over and over.

Syntax of Java Inheritance

class Derivedclass-name extends Baseclass-name  
{  
   //data members and methods
}

The “extends” keyword is used for inheritance in java. The “extends” means increase the features.

Java Inheritance Example

In this example, Student class extends Person class. Person class has two data members and one parametrized constructor. Student class inherits the properties of person class. All students have a name, age and roll no. For storing name and age of students, data members of person class are used. And age of student is stored in data member of student class. In the Student class constructor, we call the Person class constructor using super keyword.

class Person
{
 String name; 
 int age;
 Person(String n, int a)
 {
  name = n;
  age = a;
 }
}
class Student extends Person
{
 int rollno;
 Student(String n, int a, int r)
 {
  super(n, a);
  rollno = r;
 }
 void showDetails()
 {
  System.out.println("Name : "+super.name);
  System.out.println("Age : "+super.age);
  System.out.println("Roll no : "+rollno);
 }
}
class Inheritance
{
 public static void main(String[] args) {
  Student s = new Student("John", 18, 30);
  s.showDetails();
 }
}

Output:

Name : John
Age : 18
Roll no : 30

Types of Inheritance in Java

Following are the types of inheritance supported by java.

Single Inheritance
Single Inheritance in Java
Single Inheritance
In single inheritance, there is only one base class and derived. This type of inheritance is very simple and easy to understand.

Multilevel Inheritance
Multilevel Inheritance in Java
Multilevel Inheritance
In multilevel inheritance, derived inherits the properties of base class and further another class inherits properties of that derived class and so on. For example, class B inherits properties of class A and class C inherits properties of class B.

Hierarchical Inheritance
Hierarchical Inheritance in Java
Hierarchical Inheritance
In hierarchical inheritance, multiple derived classes inherits the properties of single base class. For example, class B and class C inherits properties of class A.

Multiple Inheritance
Multiple Inheritance in Java
Multiple Inheritance
Multiple inheritance cannot be achieved by class, it is only achieved by interfaces. In multiple inheritance, an interface inherits the properties of two or more two interfaces. For example, interface C inherits properties of interface A and B
Hybrid Inheritance

It is combination of more than one type of inheritance. For example, a combination of single and hierarchical inheritance. 



on Leave a Comment

OSI Model: Network Layer and its Function

Network layer is the layer 3 of OSI reference model. Network layer is responsible to deliver packets from source to destination across multiple networks (links). We have already learnt about data link layer that it delivers the packets between computers in same network. But, when we have to transfer packets across multiple networks, then network layer comes in need.

At the sender side, network layer breaks larger packets into small packets and at the receiver side, network layer assembles packets for higher layers. 

Functions of Network Layer

1. Network layer handles logical addressing. Logical address is IP address used for the purpose of routing.

2. Transfers packets from source to destination hosts.

3. In a network of networks, devices routes the packets to its destination. Network layer helps in routing, connecting devices such as routers work at this layer.

4. It provides routing algorithms.

on Leave a Comment

OSI Model: Data Link Layer

The data link layer is layer 2 of OSI reference model. The data link layer is responsible for node to node delivery of frames. This layer receives packets from network layer, converts packets to frames and gives it to physical layer. It delivers frames between nodes on the same network. Data link layer analyse the bit pattern of data and ensures that received data is error free. If the bit pattern of received data is different, then it tries to correct data or ask to retransfer data.

There may be situation when different devices try to transfer data through same medium in LAN. This causes frame collision. Data link layer specifies how to recover frames or reduce frame collision.

The data link layer contains two sublayers:

1. Logical Link Control (LLC)
2. Media Access Control (MAC)

Functions of Data Link Layer

Framing: The data link layer converts the bit stream received from network layer to the manageable data units called frames.

Physical Addressing: To distribute frames to different devices on the network, physical address is necessary. For this purpose, data link layer adds a header to the frame to define physical address of sender and receiver. If the receiver is outside the sender network, then the receiver address is the address of the device that connects the network to the next one. 

Flow Control: If the data rate at receiver side is less than the sender side data rate, then there is a chance of data loss. For this, data link layer imposes a flow control mechanism to avoid traffic at receiver side.

Error Control: The data link layer adds trailer at the end of the frame to control error. It also uses mechanism to recognize duplicate frames. 

Access Control: If two or more devices try to transfer data through the same link on the network, it causes frame collision. To avoid this, data link layer protocols determines which device has control over the link at a given time.



on Leave a Comment

OSI Model: Physical Layer and its Function

In OSI modelphysical layer is first and lowest layer. Physical layer coordinates all the functions that are required to carry bit stream over a transmission media. The transmission media may be either guided or unguided media. The physical layer deals with the mechanical and electrical specification of transmission media. 

The physical layer defines functions and procedures to transmit data over transmission media.

Functions of Physical Layer

Representation of Bits: Data in physical layer consists of bit stream. To transmit data, bits must be encoded into signals either electrical or optical. Physical layer defines the type of encoding, how 0s and 1s are changed into signals.

Data rate: Physical layer defines data rate mean numbers of bits sent per second.

Synchronization of Bits: The data rate may be different on sender side and receiver side. But, for transmission sender and receiver must be synchronized at bit level. The sender and receiver clocks must be synchronized.

Physical Characteristics of Interfaces and Medium: The physical layer defines the type of transmission medium and characteristics of interface between the devices and transmission medium.

Line Configuration: The physical layer defines connection of devices to the media. In point-to-point configuration, two devices are connected through a dedicated link. In multipoint configuration, multiple devices connected through a link.

Topologies: Physical layer defines how devices make a network using topologies: Mesh, Star, Ring, Bus or Hybrid.

Transmission Mode: Physical also Layer defines the direction of transmission between two devices: Simplex, Half Duplex or Full Duplex.

on Leave a Comment

Java Character Class

We have ever seen characters of primitive char data type. But java also provides a wrapper class called Character class. The Character class wraps a char value in an object. We can create objects of Character class using new keyword. The Character class contains a single field whose type is char. We can manipulate characters using many static methods provides by Character class.

Creating an Object of Character Class

Character ch = new Character('A');

The Character class has only one constructor that contains only one argument of char value.

The java compiler has a feature called autoboxing or unboxing, under this feature, if we pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character class object.

Escape Sequences

Any character preceded by a backslash \ character is escape sequence. Escape sequence character has special meaning to the compiler.

This table shows the Java escape sequences:

Escape Sequence Description
\tInserts a tab in the text at this point.
\bInserts a backspace in the text at this point.
\nInserts a newline in the text at this point.
\rInserts a carriage return in the text at this point.
\fInserts a form feed in the text at this point.
\'Inserts a single quote character in the text at this point.
\"Inserts a double quote character in the text at this point.
\\Inserts a backslash character in the text at this point.

We can use escapes sequences in print statement. When java compiler encounters escape sequences in print statement, the compiler interprets it accordingly.

Example of Escape Sequences

class EscapeSequence
{
 public static void main(String[] args) {
  System.out.print("\tWelcome to \"Pc Technical Pro\"");
 }
}

Output:

        Welcome to "Pc Technical Pro"

Character Class Methods

1. isLetter(char ch)

The isLetter(char ch) methods returns Boolean value. This method returns true if specified char value is letter, otherwise it returns false. We can also pass ASCII value of char value to this method, as typecasting is implicitly performed by compiler. 

Example:

class CharacterMethods
{
 public static void main(String[] args) {
  System.out.println(Character.isLetter('B'));
  System.out.println(Character.isLetter('6'));
 }
}

Output:

true
false

2. isDigit(char ch)

The isDigit(char ch) methods returns Boolean value. This method returns true if specified char value is digit, otherwise it returns false. We can also pass ASCII value of char value to this method.

Example:

class CharacterMethods
{
 public static void main(String[] args) {
  System.out.println(Character.isDigit('B'));
  System.out.println(Character.isDigit('6'));
 }
}

Output:

false
true


3. isWhitespace(char ch)

This method determines that specified char value is whitespace or not. The whitespace includes space, tab, or new line.

Example:

class CharacterMethods
{
 public static void main(String[] args) {
  System.out.println(Character.isWhitespace('B'));
  System.out.println(Character.isWhitespace('6'));
  System.out.println(Character.isWhitespace(' '));
  System.out.println(Character.isWhitespace('\n'));
  System.out.println(Character.isWhitespace('\t'));
 }
}

Output:

false
false
true
true
true

4. isUpperCase(char ch)

This method determines whether the specified char value is uppercase or not.

Example:

class CharacterMethods
{
 public static void main(String[] args) {
  System.out.println(Character.isUpperCase('a'));
  System.out.println(Character.isUpperCase('B'));
  System.out.println(Character.isUpperCase('6'));
 }
}

Output:

false
true
false

5. isLowerCase(char ch)

This method determines whether the specified char value(ch) is lowercase or not.

Example:

class CharacterMethods
{
 public static void main(String[] args) {
  System.out.println(Character.isLowerCase('a'));
  System.out.println(Character.isLowerCase('B'));
  System.out.println(Character.isLowerCase('6'));
 }
}

Output:

true
false
false

on Leave a Comment

Java Program to Check Leap Year or Not

This java program checks whether a year is leap year or not. Leap year is a year comes after every four year containing 366 days including 29 February as an intercalary day.

A year is a leap year if:

1. Year is divided by 4 but not by 100.
2. Century year (1600, 2000 etc) is divided by 400 and 100.

Java Program to Check Leap Year or Not

import java.util.Scanner;

public class CheckLeapYear
{
    public static void main(String args[])
    {
       int year;
       Scanner read = new Scanner(System.in);
    
       System.out.print("Enter Year : ");
       year = read.nextInt();
    
       if((year%400==0)||(year%100!=0 && year%4==0))
        System.out.println(year+" is a Leap Year.");
       else
        System.out.println(year+" is not a Leap Year.");
    }
}

Output 1:

Enter Year : 2016
2016 is a Leap Year.

Output 2:

Enter Year : 1998
1998 is not a Leap Year.

on Leave a Comment

Java Program to Swap Two Numbers

In this article, we will read about how to swap two numbers in java. We can swap two number using third variable or without using third variable. In this article, we will both methods.

Java Program to Swap Two Numbers

This java program swaps two numbers using third variable.

import java.util.Scanner;
class Swapping
{
 public static void main(String[] args) {
  int n1, n2, temp;
  Scanner read = new Scanner(System.in);

  System.out.print("Enter first number : ");
  n1 = read.nextInt();

  System.out.print("Enter second number : ");
  n2 = read.nextInt();
        
                /*Swapping two numbers using third variable*/
  temp = n1;
  n1 = n2;
  n2 = temp;
        
                System.out.println("\nAfter Swapping\n");
                System.out.println("First number : "+n1);
                System.out.println("Second number : "+n2);
 }
}

Output:

Enter first number : 5
Enter second number : 6

After Swapping

First number : 6
Second number : 5

Java Program to Swap Two Numbers without Using Third Variable

This java program swaps two numbers without using third variable.

import java.util.Scanner;
class Swapping
{
 public static void main(String[] args) {
  int n1, n2;
  Scanner read = new Scanner(System.in);

  System.out.print("Enter first number : ");
  n1 = read.nextInt();

  System.out.print("Enter second number : ");
  n2 = read.nextInt();
        
                /*Swapping two numbers without using third variable*/
                n1 = n1 - n2;
                n2 = n1 + n2;
                n1 = n2 - n1;
        
                System.out.println("\nAfter Swapping\n");
                System.out.println("First number : "+n1);
                System.out.println("Second number : "+n2);
 }
}

Output:

Enter first number : 10
Enter second number : 20

After Swapping

First number : 20
Second number : 10




on Leave a Comment

Java Program to Convert Decimal to Octal

This java program converts decimal value to its equivalent octal value. First enter a decimal number and converts this number into its equivalent octal value. And finally display that octal value.

Java Program to Convert Decimal to Octal

import java.util.Scanner;
public class DecToOct
{
 public static void main(String[] args) {
 int decimal;
        Scanner scan = new Scanner(System.in);
  
        System.out.print("Enter a Decimal Number : ");
        decimal = scan.nextInt();
  
 int q, i=1, j;
        q = decimal;
          
 int octal[] = new int[100];
        while(q != 0)
        {
            octal[i++] = q%8;
            q = q/8;
        }
  
        System.out.print("Octal Equivalent of " + decimal + " is : ");
        for(j=i-1; j>0; j--)
        {
            System.out.print(octal[j]);
        }
 }
}

Output:

Enter any Decimal Number : 66
Octal Equivalent of 66 is : 102


.
on Leave a Comment

Java Program to Calculate Simple and Compound Interest

This java program calculates simple and compound interest. First, user enters the amount, number of years and rate of interest, then calculates simple interest and compound interest. 

Java Program to Calculate Simple and Compound Interest

 import java.util .*;

 class SiCi
{
 public static void main(String[] args) {
 double p, rate, t, si, ci;
        System.out.print("Enter The Amount : ");
        Scanner read = new Scanner(System. in);
     p = read.nextDouble();

     System. out. print("Enter The No. of Years : ");
    t = read.nextDouble();

     System. out. print("Enter The Rate of Interest (ROI) : ");
     rate = read.nextDouble();

     /*Calculating Simple Interest and Compound Interest*/
     si = (p * t * rate)/100;
     ci = p*Math.pow(1.0+rate/100.0,t)-p;

     /*Displaying Simple Interest and Compound Interest*/
     System.out.println("Simple Interest = "+si);
     System.out. println("Compound Interest = "+ci);
 }
}

Output:

Enter The Amount : 1000
Enter The No. of Years : 2
Enter The Rate of Interest (ROI) : 15
Simple Interest = 300.0
Compound Interest = 322.4999999999998


on Leave a Comment

This Keyword in Java With Examples

The java this keyword is used to refer the current object. There are many uses of java this keyword.

Uses of java this keyword

this keyword can be used to refer instances of current object.

this keyword can be used to refer methods of current object.

this keyword can be used to refer constructors of current object.

this keyword can be passed as  argument to method of current object.

this keyword can be passed as argument to constructor of current object.

this keyword can be used to return current object.

this keyword can be used to refer instances of current object

If the local variables and instance variables are same, this is ambiguity for JVM, To solve this ambiguity, java this keyword is used.

Example:

class Area
{
 float l;
 float b;
 Area(float l, float b)
 {
  this.l = l;
  this.b = b;
 }
 void show()
 {
  System.out.println("Length = "+l+"\nBreadth = "+b);
 }
}
class ThisKeyword
{
 public static void main(String[] args) {
  Area obj = new Area(10, 8);
  obj.show();
 }
}

Output:

Length = 10.0
Breadth = 8.0

this keyword can be used to refer methods of current object

We can also invoke methods using this keyword. But we can also call methods by name. If we don't use this keyword for invoking methods, then compiler automatically adds this keyword.

Example:

class Area
{
 float l;
 float b;
 Area(float l, float b)
 {
  this.l = l;
  this.b = b;
 }
 void show()
 {
  System.out.println("Length = "+l+"\nBreadth = "+b);
  System.out.println("\nArea = "+this.calculate());
 }
    float calculate()
 {
  return this.l*this.b;
 }
}
class ThisKeyword
{
 public static void main(String[] args) {
  Area obj = new Area(10, 8);
  obj.show();
 }
}

Output:

Length = 10.0
Breadth = 8.0

Area = 80.0

this keyword can be used to refer constructors of current object

We can also refer constructors of class using this keyword. Java this can be used to invoke both parameterized and non-parameterized constructor.

Example:

class Area
{
 float l;
 float b;
 Area()
 {
  System.out.println("Calculates area of rectangle");
 }
 Area(float l, float b)
 {
  this();
  this.l = l;
  this.b = b;
 }
 void show()
 {
  System.out.println("Length = "+l+"\nBreadth = "+b);
  System.out.println("\nArea = "+this.calculate());
 }
    float calculate()
 {
  return this.l*this.b;
 }
}
class ThisKeyword
{
 public static void main(String[] args) {
  Area obj = new Area(10, 8);
  obj.show();
 }
}

Output:

Calculates area of rectangle
Length = 10.0
Breadth = 8.0

Area = 80.0

this keyword can be passed as  argument to method of current object

We can pass this keyword as argument to method of current object.

Example:

class Area
{
 float l;
 float b;
 Area(float l, float b)
 {
  this.l = l;
  this.b = b;
  show(this);
 }
 void show(Area ob)
 {
  System.out.println("Length = "+l+"\nBreadth = "+b);
 }
}
class ThisKeyword
{
 public static void main(String[] args) {
  Area obj = new Area(10, 8);
 }
}

Output:

Length = 10.0
Breadth = 8.0

this keyword can be passed as argument to constructor of current object

We can pass this keyword as argument to constructor of current object.

Example:

class Area
{
 float l;
 float b;
 Area()
 {
  ThisKeyword t = new ThisKeyword(this);
 }
}
class ThisKeyword
{
 ThisKeyword(Area o)
 {
  System.out.println("Constructor is invoked");
 }
 public static void main(String[] args) {
  Area obj = new Area();
 }
}

Output:

Constructor is invoked

this keyword can be used to return current object

We can return an object using this keyword.

Example:

class Area
{
 float l;
 float b;
 Area call()
 {
   return this;
 }
 void show()
 {
  System.out.println("Length = "+l+"\nBreadth = "+b);
 }
 Area(float l, float b)
 {
  this.l = l;
  this.b = b;
 }
}
class ThisKeyword
{
 ThisKeyword(Area o)
 {
  System.out.println("Constructor is invoked");
 }
 public static void main(String[] args) {
  new Area(4, 5).call().show();
 }
}

Output:

Length = 4.0
Breadth = 5.0