0% found this document useful (0 votes)
3 views55 pages

03-Java Basic

The document outlines the five phases of a Java program: Edit, Compile, Load, Verify, and Execute, detailing the process from writing code to executing it on a machine. It also introduces Java basics, including the structure of a simple 'Hello World' program, the concept of classes and objects, and methods for initializing objects. Additionally, it provides examples of creating and using classes, along with various ways to create objects in Java.

Uploaded by

psudeep445
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views55 pages

03-Java Basic

The document outlines the five phases of a Java program: Edit, Compile, Load, Verify, and Execute, detailing the process from writing code to executing it on a machine. It also introduces Java basics, including the structure of a simple 'Hello World' program, the concept of classes and objects, and methods for initializing objects. Additionally, it provides examples of creating and using classes, along with various ways to create objects in Java.

Uploaded by

psudeep445
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

References

1. [Link]
2. [Link]

Java Basics

5 Phases of the Java Program There are five phases needed to run the Java
program.

In this section, we will discuss those 5 phases of the Java program in detail.

These steps are to create and execute the Java application using a Java
development environment.

These phases are discussed in the context of JDK 6.0 from Sun Microscystems Inc.

JDK is the Java Development Kit and JDK6 is the version 6th version of JDK,

The 5 Phases of the Java Program are as follows:-

1. Edit
2. Compile
3. Load
4. Verify
5. Execute

Let us see in detail the 5 Phases of the Java Program:-

Observe the below diagram for the 5 Phases of the Java Program:-
Let us see in detail the 5 Phases of the Java Program:-
Phase-1: Edit

When we write a Java program on any editor & save it, then it is stored in a disk with
an extension of .java. This .java file is platform-independent therefore a Java
program (.java file) written in one operating system can be used in any operating
system.

Phase-2: Compile

The compiler’s work is to convert the high-level language to bytecodes then store it
with an extension of .class. To compile we use the “javac” command.

After developing the Java program, we compile it through the “javac” command. The
compiler checks for syntax errors, and if everything is correct then it starts translating
the .java file else it gives a compile-time error. After compilation of the .java file,
the .java file is translated to .class file. Similar to the .java file, the .class file is also
platform-independent.

Phase-3: Load

The class loader reads the code, compiles it, and puts those bytecodes from the disk
to primary memory. From the class loader, the codes are stored in primary memory.

When we execute the “java” command to run the Java application then the .class file
(which contains bytecode) is loaded into the RAM, and this task is done by the class
loader.

Phase-4: Verify

This step confirms that the bytecodes are valid and make sure that they do not risk
the Java security restrictions.

Phase-5: Execute

In this step, the JVM (Java Virtual Machine) reads the byte and translates it to the
language that the machine can understand that is machine language then executes
the program and stores it in values in primary memory. This machine language will
be different for different operating

Java Hello World – Setting up IDE


Java is easy to learn, and its syntax is simple and easy to understand. Let’s
start with the most famous Hello World program.

Let’s start with using online IDE provided via jDoodle - [Link]
java-compiler/

Online Java - [Link]

The below-given program is the most simple program of Java printing “Hello
World” to the screen. Let us try to understand every bit of code step by step.

// This is a simple Java program.


// FileName : "[Link]".

public class HelloWorld


{
// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[])
{
[Link]("Hello, World");
}
}

The “Hello World!” program consists of three primary components: the


HelloWorld class definition, the main method, and source code comments.

1. Class definition
This line uses the keyword class to declare that a new class is being defined.
public class HelloWorld

2. HelloWorld
It is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace { and the
closing curly brace }.
3. main method:
In the Java programming language, every application must contain a main
method whose signature is:
public static void main(String[] args)
● public: So that JVM can execute the method from anywhere.
● static: The main method is to be called without an object. The
modifiers public and static can be written in either order.
● void: The main method doesn’t return anything.
● main(): Name configured in the JVM.
● String[]: The main method accepts a single argument, i.e., an array
of elements of type String.

Like in C/C++, the main method is the entry point for your application and will
subsequently invoke all the other methods required by your program. Every
programming language has a convention to define the entry point of the
project/ application.

Comments
They can either be multiline or single-line comments.
// This is a simple Java program.
// Call this file "[Link]".

Important Points
● The name of the class defined by the program is HelloWorld, which
is the same as the name of the file([Link]). This is not a
coincidence. In Java, all codes must reside inside a class, and there
is at most one public class which contains the main() method.

● By convention, the name of the main class(a class that contains the
main method) should match the name of the file that holds the
program.

For Advanced level, we will cover setting up Eclipse IDE on local machine.
[Link]

Detailed -
[Link]

Java Classes/Objects
Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

An object in Java is the physical as well as a logical entity, whereas, a class in Java
is a logical entity only.

What is an object in Java


An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.

An object has three characteristics:

● State: represents the data (value) of an object.

● Behavior: represents the behavior (functionality) of an object such as deposit,


withdraw, etc.

● Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its
state. It is used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which


objects are created. So, an object is the instance(result) of a class.

Object Definitions:

● An object is a real-world entity.

● An object is a runtime entity.

● The object is an entity which has state and behavior.

● The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

Fields

Methods

Constructors

Blocks

Nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }
Instance variable in Java
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known as
an instance variable.

Method in Java
In Java, a method is like a function which is used to expose the behavior of an
object.

Advantage of Method

● Code Reusability

● Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.

Object and Class Example: main within the class


In this example, we have created a Student class which has two data members id
and name. We are creating the object of the Student class by new keyword and
printing the object's value.

Here, we are creating a main() method inside the class.

File: [Link]

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. [Link]([Link]);//accessing member through reference variable
13. [Link]([Link]);
14. }
15. }

Output:

0 null

Object and Class Example: main outside the class


In real time development, we create classes and use it from another class. It is a
better approach than previous one. Let's see a simple example, where we are having
main() method in another class.

We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.

File: [Link]

1. //Java Program to demonstrate having the main method in


2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. [Link]([Link]);
13. [Link]([Link]);
14. }
15. }
Output 0 null

3 Ways to initialize object


There are 3 ways to initialize object in Java.

1. By reference variable

2. By method

3. By constructor

1) Object and Class Example: Initialization through reference


Initializing an object means storing data into the object. Let's see a simple example
where we are going to initialize the object through a reference variable.

File: [Link]

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. [Link]=101;
9. [Link]="Sonoo";
10. [Link]([Link]+" "+[Link]);//printing members with a white
space
11. }
12. }

Output:

101 Sonoo

ACTIVITY JB-1
Create Employee class with the following as the data members

i. EmpName [Link] [Link] [Link] and initialize them through Reference.

We can also create multiple objects and store information in it through reference
variable.

File: [Link]

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. [Link]=101;
12. [Link]="Sonoo";
13. [Link]=102;
14. [Link]="Amit";
15. //Printing data
16. [Link]([Link]+" "+[Link]);
17. [Link]([Link]+" "+[Link]);
18. }

Output:

101 Sonoo

102 Amit

2) Object and Class Example: Initialization through method


In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying
the state (data) of the objects by invoking the displayInformation() method.

1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){[Link](rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. [Link](111,"Karan");
15. [Link](222,"Aryan");
16. [Link]();
17. [Link]();
18. }
19. }

Output

111 Karan

222 Aryan
As you can see in the above figure, object gets the memory in heap memory area.
The 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.

3) Object and Class Example: Initialization through a


constructor
We will learn about constructors in Java later.

Object and Class Example: Employee


Let's see an example where we are maintaining records of employees.

File: [Link]

1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){[Link](id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. [Link](101,"ajeet",45000);
18. [Link](102,"irfan",25000);
19. [Link](103,"nakul",55000);
20. [Link]();
21. [Link]();
22. [Link]();
23. }
24. }

Output:

101 ajeet 45000

102 irfan 25000

103 nakul 55000

Object and Class Example: Rectangle


There is given another example that maintains the records of Rectangle class.

File: [Link]

1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){[Link](length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. [Link](11,5);
15. [Link](3,15);
16. [Link]();
17. [Link]();
18. }
19. }

Output:

55 45

What are the different ways to create an object in


Java?
There are many ways to create an object in java. They are:

● By new keyword

● By newInstance() method

● By clone() method

● By deserialization

● By factory method etc.

We will learn these ways to create object later.


Anonymous object
Anonymous simply means nameless. An object which has no reference is known as
an anonymous object. It can be used at the time of object creation only.

If you have to use an object only once, an anonymous object is a good approach. For
example:

1. new Calculation();//anonymous object

Calling method through a reference:

1. Calculation c=new Calculation();


2. [Link](5);
Calling method through an anonymous object

1. new Calculation().fact(5);

Let's see the full example of an anonymous object in Java.

1. class Calculation{
2. void fact(int n){
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. [Link]("factorial is "+fact);
8. }
9. public static void main(String args[]){
10. new Calculation().fact(5);//calling method with anonymous object
11. }
12. }

Output:

Factorial is 120

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

1. int a=10, b=20;

Initialization of refernce variables:

1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects


Let's see the example:

1. //Java Program to illustrate the use of Rectangle class which


2. //has length and width data members
3. class Rectangle{
4. int length;
5. int width;
6. void insert(int l,int w){
7. length=l;
8. width=w;
9. }
10. void calculateArea(){[Link](length*width);}
11. }
12. class TestRectangle2{
13. public static void main(String args[]){
14. Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
15. [Link](11,5);
16. [Link](3,15);
17. [Link]();
18. [Link]();
19. }
20. }

Output:

55

45

Real World Example: Account


File: [Link]

1. //Java Program to demonstrate the working of a banking-system


2. //where we deposit and withdraw amount from our account.
3. //Creating an Account class which has deposit() and withdraw() methods
4. class Account{
5. int acc_no;
6. String name;
7. float amount;
8. //Method to initialize object
9. void insert(int a,String n,float amt){
10. acc_no=a;
11. name=n;
12. amount=amt;
13. }
14. //deposit method
15. void deposit(float amt){
16. amount=amount+amt;
17. [Link](amt+" deposited");
18. }
19. //withdraw method
20. void withdraw(float amt){
21. if(amount<amt){
22. [Link]("Insufficient Balance");
23. }else{
24. amount=amount-amt;
25. [Link](amt+" withdrawn");
26. }
27. }
28. //method to check the balance of the account
29. void checkBalance(){[Link]("Balance is: "+amount);}
30. //method to display the values of an object
31. void display(){[Link](acc_no+" "+name+" "+amount);}
32. }
33. //Creating a test class to deposit and withdraw amount
34. class TestAccount{
35. public static void main(String[] args){
36. Account a1=new Account();
37. [Link](832345,"Ankit",1000);
38. [Link]();
39. [Link]();
40. [Link](40000);
41. [Link]();
42. [Link](15000);
43. [Link]();
44. }}

Output

83234 Ankita 10000


Balance is 1000.0
40000.0 deposited
Balance is 40000.0
50000.0 is withdrawn
Balance is 26000

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class

is created. At the time of calling constructor, memory for the object is allocated in the
memory.

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

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

It calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

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

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name

2. A Constructor must have no explicit return type

3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers

while declaring a constructor. It controls the object creation. In other words, we can have
private, protected, public or default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

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

Syntax of default constructor:

1. <class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.

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


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

Output

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Q) What is the purpose of a default constructor?

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

Example of default constructor that displays the


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

Output

0 null

0 null

Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor


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

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


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

111 Karan

222 Aryan

Constructor Overloading in Java


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

Constructor overloading in Java

is a technique of having more than one constructor with different parameter lists. They are
arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){[Link](id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. [Link]();
23. [Link]();
24. }
25. }

Output:

111 Karan 0

222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given
below.

Java Constructor Java Method

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


object. behavior of an object.

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

The constructor is invoked implicitly. The method is invoked


explicitly.

The Java compiler provides a default The method is not provided by


constructor if you don't have any constructor in the compiler in any case.
a class.

The constructor name must be same as the The method name may or may
class name. not be same as the class name.
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one
object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

● By constructor

● By assigning the values of one object into another

● By clone() method of Object class

In this example, we are going to copy the values of one object into another using
Java constructor.

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

Output

111 Karan

111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.

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

Output

111 Karan

111 Karan

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a
value).

Can constructor perform other tasks instead of


initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform any
operation in the constructor as you perform in the method.
Is there Constructor class in Java?

Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information
of a constructor in the class. It is found in the [Link] package.

Java Static Keyword –


Master the Concept of Static Methods in Java

In Java using a static keyword, we can have a static method, static class, static
block, static variable. This keyword is mainly used for the management of memory.
We can use static keyword with methods, variables, class, and blocks. It belongs to a
class rather than the instance of the class, It simply means that if you make any
variable static to can access it without its object.

Static can be:

1. Block

2. Variable (also known as a class variable)

3. Method (also known as a class method)

4. Class

Static Block in Java


A static block initializes the static variables. It executes
whenever the class is loaded in memory. One class can have
numerous static blocks, which will be executed in the same
sequence in which they are written.
Example-
package [Link];

public class StaticBlock

static String sentence;

static int number;

static

sentence = "Welcome to DataFlair";

number = 69;

public static void main(String args[])

[Link](sentence);

[Link]("Value of Integer: "+number);

Output

Welcome to Dataflair

Value of Integer 69
Static Variable in Java
*This topic is already covered

Static Methods in Java


Static methods in Java belong to classes, unlike other classes it
doesn’t belong to the instance of the class. This method can be
accessible to every instance but the methods defined in the
instance are only accessed by that member of the class. It can
access only static data.

1. These are declared with the keyword “static” when defining a


method

2. This method belongs to the class and not to the object.

3. It can access only static data. It can not access instance


variables.

4. A static method can call only static methods, non-static


methods are not called by a static method.

5. This method is can be accessed by the class name it doesn’t


need any object.

Example of Java Static Methods-


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

package [Link];

class Employee

int empId;

String empName;

static String companyName = "TCS";

//static method to valueChange the value of static variable


static void valueChange()

companyName = "DataFlair";

//constructor to initialize the variable

Employee(int id, String name){

empId = id;

empName = name;

//method to display values

void display()

[Link](empId+" "+empName+" "+companyName);

//class to create and display the values of object

public class Demo

public static void main(String args[])

[Link]();//calling valueChange method

//creating objects

Employee EmployeeObj = new Employee(218,"Kushal");


Employee EmployeeObj1 = new Employee(635,"Bhumika");

Employee EmployeeObj2 = new Employee(147,"Renuka");

//calling display method

[Link]();

[Link]();

[Link]();

Output

Java Static Class


Java allows us to define a class but not a static class which
simply means that we can define a class static only if it is a
nested class. In Java, a class can be static when it is a nested
class. Nested static class doesn’t need any reference of the Outer
class. Non-static members are not accessed by a static class.

Example-

// Java program to Demonstrate How to

// Implement Static and Non-static Classes


// Class 1

// Helper class

class OuterClass {

// Input string

private static String msg = "GeeksForGeeks";

// Static nested class

public static class NestedStaticClass {

// Only static members of Outer class

// is directly accessible in nested

// static class

public void printMessage()

// Try making 'message' a non-static

// variable, there will be compiler error

[Link](

"Message from nested static class: " +


msg);

// Non-static nested class -


// also called Inner class

public class InnerClass {

// Both static and non-static members

// of Outer class are accessible in

// this Inner class

public void display()

// Print statement whenever this method is

// called

[Link](

"Message from non-static nested class: "

+ msg);

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String args[])


{

// Creating instance of nested Static class

// inside main() method

[Link] printer

= new [Link]();

// Calling non-static method of nested

// static class

[Link]();

// Note: In order to create instance of Inner


class

// we need an Outer class instance

// Creating Outer class instance for creating

// non-static nested class

OuterClass outer = new OuterClass();

[Link] inner=new

[Link]();

// Calling non-static method of Inner class

[Link]();

// We can also combine above steps in one


// step to create instance of Inner class

[Link] innerObject

= new OuterClass().new InnerClass();

// Similarly calling inner class defined method

[Link]();

Output:

What is Java Instance Method?


An instance method in Java is basically a method of the class. In
other words, a non-static method which is declared inside a class
is an instance method. This kind of method requires an object of
its class to created before it can be called. To invoke an instance
method, we have to create the object of the class.
public void Dataflair(String name)

// code to be executed....

}
Instance Methods vs Static Methods
in Java
1. The instance method requires the object of its class to be
created before it can be called. Static methods in Java can be
called without creating the object of the class.

2. Java static method is declared using static keyword. An


instance method does not need any keyword.

3. The static method has a single copy for a class. But instance
methods have multiple copies depending on the number of
instances created for that particular class.

4. We can invoke a static method by using its class reference. An


instance method is invoked by using the object reference.

5. We can’t access instance methods and instance variables with


the help of Static methods in Java. We can access static variables
and static methods with the help of the Instance method.

this keyword in Java


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

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.

2. this can be used to invoke current class method (implicitly)

3. this() can be used to invoke current class constructor.

4. this can be passed as an argument in the method call.

5. this can be passed as argument in the constructor call.

6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usages of this keyword.

1) this: to refer current class instance variable

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

Understanding the problem without this keyword

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

output

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

Solution of the above problem by this keyword


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

If local variables(formal arguments) and instance variables are different, there is no


need to use this keyword like in the following program:

Program where this keyword is not required


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

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while invoking
the method. Let's see the example
1. class A{
2. void m(){[Link]("hello m");}
3. void n(){
4. [Link]("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

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

Calling parameterized constructor from default constructor:

1. class A{
2. A(){
3. this(5);
4. [Link]("hello a");
5. }
6. A(int x){
7. [Link](x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining. Let's see the example given below that displays the actual use
of this keyword.

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

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

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

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

The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling. Let's see the example:

1. class S2{
2. void m(S2 obj){
3. [Link]("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }

Output: Method is invoked

Application of this is that it can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to


another one. It is used to reuse one object in many methods.

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

We can pass the this keyword in the constructor also. It is useful if we have to use
one object in multiple classes. Let's see the example:

1. class B{
2. A4 obj;
3. B(A4 obj){
4. [Link]=obj;
5. }
6. void display(){
7. [Link]([Link]);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. [Link]();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }

Output: 10

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

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

Syntax of this that can be returned as a statement

1. return_type method_name(){
2. return this;
3. }

Example of this keyword that you return as a


statement from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){[Link]("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }

Output: Hello Java

Proving this keyword

Let's prove that this keyword refers to the current class instance variable. In this
program, we are printing the reference variable and this, output of both variables are
same.

1. class A5{
2. void m(){
3. [Link](this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. [Link](obj);//prints the reference ID
8. obj.m();
9. }
10. }

You might also like