You are on page 1of 73

' Function-ofiented pfogromming

0
LJ

t.. .; . . t
I +I ’L! •
. ”

’( 0f'#
J›zo0starXikSitñ›a,Gh&IN›@aii›toBtkJxt
pij«tiaJwl9l.ficué!Iiw0ffao¿ mdIBSmi Toa.
fiEll}, ilUM.MllI/g" Kt3ttll "#}ll EdGb li4§tfI/ flCttDi0lUI.g.
Java was originally developed by James Gosling at Sun Microsystems (which has since been
acquired by Oracle) and released in 1995 as a core component of Sun Microsystems' Java
platform.

How To Install JDK on Windows

1. Un-Install Older Version(s) of JDK/JRE. ...

2. Download JDK .... www.oracle.com/technetwork/java/javase/downloads/index.html

3. Install JDK. ...

4. Include JDK's "bin" Directory in the PATH. ...

5. Verify the JDK Installation. ...

6. Write a Hello-World Java Program. ...

7. Compile and Run the Hello-World Java Program.


Let's create the hello java program:

class Simple
{

public static void main(String args[])

System.out.println("Hello World");

save this file as Simple.java

To compile:

javac Simple.java

To execute:

java Simple

Output:Hello Java

Class: keyword is used to declare a class in java. Used to create an object.

Public: keyword is an access modifier which represents visibility. It means it is visible to all.

static is a keyword. If we declare any method as static, it is known as the static method. The
main method is executed by the JVM, so it doesn't require to create an object to invoke
the main method. So it saves memory.

void is the return type of the method. It means it doesn't return any value.

main represents the starting point of the program.

String[] args is used for command line argument. We will learn it later.
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.

For input the data Scanner object is require

import java.util.Scanner;

• Creation of object of Scanner class will be used to get input from the user.

Scanner input = new Scanner(System.in);

int number = input.nextInt();

Get float, double and String Input

import java.util.Scanner;

class Input

public static void main(String[] args)

{ Scanner input = new Scanner(System.in); // Getting float input


System.out.print("Enter float: ");

float myFloat = input.nextFloat();

System.out.println("Float entered = " + myFloat); // Getting double input


System.out.print("Enter double: ");

double myDouble = input.nextDouble();

System.out.println("Double entered = " + myDouble); // Getting String input

System.out.print("Enter text: ");

String myString = input.next();

// String myString = input.nextLine();

System.out.println("Text entered = " + myString);

}
Enter float: 2.343

Float entered = 2.343

Enter double: -23.4

Double entered = -23.4

Enter text: Hey!

Text entered = Hey!

2. import java.util.Scanner;

public class ScannerDemo1

{ public static void main(String[] args)

Scanner sc = new Scanner(System.in);

String name = sc.nextLine();

char gender = sc.next().charAt(0);

int age = sc.nextInt();

long mobileNo = sc.nextLong();

double cgpa = sc.nextDouble();

System.out.println("Name: "+name);

System.out.println("Gender: "+gender);

System.out.println("Age: "+age);

System.out.println("Mobile Number: "+mobileNo);

System.out.println("CGPA: "+cgpa);

Input :

Lucky

40

9876543210

9.9
Output :

Name: Lucky

Gender: M

Age: 40

Mobile Number: 9876543210

CGPA: 9.9

Keywords

• Keywords are the reserved words which are having predefined meaning in Java.

• All the keywords are defined in lower case and the meaning of these keywords can’t be
modified.

• We cannot use keywords as names for variables, classes, methods, or as any other
identifiers.

• const & goto are the keywords but no implementation available in Java. You cannot use in
Java.

Identifiers

• By the name, it is clear that identifiers are used for identification purpose.

• Identifiers can be a class name, method name, variable name, or a label name. For Example:

• class TestIntellipaat{
public static void main(String args[]){
int a=2;
}
}

In the above example,

• TestIntellipaatis a class name.

• main is a method name.

• String is a predefinedclass name.

• args and a is a variable name.

Rules for defining identifiers:

• Identifier can contain alphabets [A-Z] & [a-z], Digits [0-9], underscore(_) and dollar($).

• The first letter must be an alphabet, digit, underscore or dollar sign.

• Space is not allowed in between the identifier name.

• Keywords cannot be used as identifiers. For example:

• Valid Identifiers: ch, _integer, del123, deal_var, etc.


Invalid Identifiers: 12ch, @charm, My var, a+6, while, int, true, etc.

Data types

Data types represent the type of data you want to use and memory required for that data.
There are two types of data:

• Primitive Data Type

• Non-Primitive Data Type


PRIMITIVE DATA TYPE

Primitive Data Default Range Default Example


Types Values Size

Boolean False true/ false N/D boolean b =


true

Char 0 or 0 to 65535 (2^16-1) 2byte char c=’A’


\u0000 \u0000 to \uffff

Byte 0 -128(-2^7) to 127 (2^7 -1) 1byte byte b = 12

Short 0 -32,768 (-2^15) to 32,767(2^15 -1) 2byte short s=10

Int 0 – 2,147,483,648 (- 2byte int I = 100


2^31) to2147483647(2^31 -1)

long 0 -2^63 to 2^63-1 8byte long l= 1000L

float 0.0 1.4E-45 to 3.40E+38 4byte float f = 25.9f

double 0.0 4.9E-324 to 1.79E+308 8byte double d =


152.3

Any Null Reference of the corresponding type 8byte String str=null


Reference object
type

NON PRIMITIVE DATA TYPE

These are the user-defined data types. There are four types of non-primitive data types:

• Class type

• Interface type

• Enum type

• Annotation type
VARIABLE:

Variable holds the user data. The memory will be allocated for the variables according to the
data type. Value of the variable can be changed any number of times during the program
execution.

Syntax: <data type><var name>; or <data type><var name>=<value>;

Example: int a; int b=10; String s=”name”; String st;

There are two types of variables based on the data types used to declare the variable:

• Primitive variables

• Reference Variable

Primitive Variables

Variables declared with primitive data types are called as primitive variables.

• Example: int a, char c, double b=10.0, etc.

Reference Variable

Variables declared with used defined data types are called as reference variables.

Example:String str; String s=”Intellipaat”;

There are following types of variables based on the scope of the variables:

• Instance variables

• Static variables

• Local variables

EXAMPLE:

public class IntellipaatClass{


int a; // Instance Variable
static int b; // static variable
void show(){
int c=10; // local variable
}
}
class OperatorExample

public static void main(String args[])

System.out.println(10>>2); //10/2^2=10/4=2

System.out.println(20>>2) ;//20/2^2=20/4=5

System.out.println(20>>3); //20/2^3=20/8=2

}}

Output:

2
class OperatorExample

public static void main(String args[])

//For positive number, >> and >>> works same

System.out.println(20>>2);

System.out.println(10>>>2);

//For negative number, >>> changes parity bit (MSB) to 0

System.out.println(-20>>2);

System.out.println(-10>>>2);

}}

Output:

-5

1073741819

Java Encapsulation
❮ PreviousNext ❯

Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable
Get and Set
You learned from the previous chapter that private variables can only be
accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide
public get and set methods.

The get method returns the variable value, and the set method sets the
value.

Syntax for both is that they start with either get or set, followed by the
name of the variable, with the first letter in upper case:

Example
public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

this.name = newName;

Example explained

The get method returns the value of the variable name.


The set method takes a parameter (newName) and assigns it to
the name variable. The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it


from outside this class:

Example
public class MyClass {

public static void main(String[] args) {

Person myObj = new Person();

myObj.name = "John"; // error

System.out.println(myObj.name); // error

Run example »

If the variable was declared as public, we would expect the following output:

John

However, as we try to access a private variable, we get an error:

MyClass.java:4: error: name has private access in Person


myObj.name = "John";
^
MyClass.java:5: error: name has private access in Person
System.out.println(myObj.name);
^
2 errors

Instead, we use the getName() and setName() methods to acccess and


update the variable:

Example
public class MyClass {

public static void main(String[] args) {

Person myObj = new Person();


myObj.setName("John"); // Set the value of the name variable to
"John"

System.out.println(myObj.getName());

// Outputs "John"

Run example »

Why Encapsulation?
 Better control of class attributes and methods
 Class attributes can be made read-only (if you only use
the get method), or write-only (if you only use the set method)
 Flexible: the programmer can change one part of the code without
affecting other parts
 Increased security of data

Java Copy Constructor


There is no copy constructor in Java. However, we can copy the values from one object
to another like copy constructor in C++.

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

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

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

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

Output:

111 Karan
111 Karan

Copy Constructor in Java


Prerequisite – Constructors in Java
Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create
a default copy constructor if you don’t write your own.
Following is an example Java program that shows a simple use of copy constructor.
// filename: Main.java

class Complex {

private double re, im;

// A normal parametrized constructor

public Complex(double re, double im) {

this.re = re;

this.im = im;

// copy constructor

Complex(Complex c) {

System.out.println("Copy constructor called");

re = c.re;

im = c.im;

// Overriding the toString of Object class

@Override

public String toString() {

return "(" + re + " + " + im + "i)";

public class Main {

public static void main(String[] args) {

Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call

Complex c2 = new Complex(c1);


// Note that following doesn't involve a copy constructor call as

// non-primitive variables are just references.

Complex c3 = c2;

System.out.println(c2); // toString() of c2 is called here

Output:

Copy constructor called


(10.0 + 15.0i)

// filename: Main.java

class Complex {

private double re, im;

public Complex(double re, double im) {

this.re = re;

this.im = im;
}

public class Main {

public static void main(String[] args) {

Complex c1 = new Complex(10, 15);

Complex c2 = new Complex(c1); // compiler error here


}

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

/*************************************************************
*****************

Welcome to GDB Online.

GDB online is an online compiler and debugger tool for C, C++, Python, Java,
PHP, Ruby, Perl,

C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS,
JS, SQLite, Prolog.

Code, Compile, Run and Debug online from anywhere in world.

*************************************************************
******************/

class Complex {

private double re, im;

// A normal parametrized constructor

public Complex(double re, double im) {

this.re = re;

this.im = im;

}
// copy constructor

Complex(Complex c) {

System.out.println("Copy constructor called");

re = c.re;

im = c.im;

// Overriding the toString of Object class

// @Override

public String toString() {

return "(" + re + " + " + im + "i)";

public class Main {

public static void main(String[] args) {

Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call

// Complex c2 = new Complex(c1);

// Note that following doesn't involve a copy constructor call as

// non-primitive variables are just references.


Complex c3 = c1;

System.out.println(c3); // toString() of c2 is called here

import java.util.Scanner;
public class Demo {

public static void main(String[] args) {


double lt,bt,ht;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Length:");
lt=sc.nextDouble();
System.out.println("Enter Breadth:");
bt=sc.nextDouble();
System.out.println("Enter Height:");
ht=sc.nextDouble();
Cuboid ob=new Cuboid();
ob.setLength(lt);
ob.setBreadth(bt);
ob.setHeight(ht);
System.out.println(ob);
sc.close();
}

public class Cuboid {


private double lt,bt,ht;
public boolean setLength(double lt) {
if(lt>0)
{this.lt=lt;
return true;
}
else {
this.lt=0;
return false;}
}
public boolean setBreadth(double bt) {
if(bt>0)
{this.bt=bt;
return true;
}
else {
this.bt=0;
return false;
}

public boolean setHeight(double ht) {


if(ht>0)
{this.ht=ht;
return true;
}
else {
this.ht=0;
return false;}
}

public String getLength() {


return this.lt+"m";

}
public String getBreadth() {
return this.bt+"m";

}
public String getHeight() {
return this.ht+"m";

public String volume(double l,double b,double h) {


return l*b*h+"cu.m";
}

public String toString() {


String
s=String.format("Length=%s\nBreadth=%s\nHeight=%s\nVolume=%s",getLength(),g
etBreadth(),getHeight(),volume(lt, bt, ht));
return s;

}
1. What are getter and setter?
In Java, getter and setter are two conventional methods that are used for retrieving and updating
value of a variable.

The following code is an example of simple class with a private variable and a couple of
getter/setter methods:

1
public class SimpleGetterAndSetter {
2
private int number;
3

4 public int getNumber() {


5 return this.number;

6 }

8 public void setNumber(int num) {

this.number = num;
9
}
10
}
11

The class declares a private variable, number. Since number is private, code from outside this
class cannot access the variable directly, like this:

1 SimpleGetterAndSetter obj = new SimpleGetterAndSetter();

2 obj.number = 10; // compile error, since number is private

3 int num = obj.number; // same as above

Instead, the outside code have to invoke the getter, getNumber() and the setter, setNumber() in
order to read or update the variable, for example:
1 SimpleGetterAndSetter obj = new SimpleGetterAndSetter();

3 obj.setNumber(10); // OK

4 int num = obj.getNumber(); // fine

So, a setter is a method that updates value of a variable. And a getter is a method that reads
value of a variable.
Getter and setter are also known as accessor and mutator in Java.

2. Why getter and setter?


By using getter and setter, the programmer can control how his important variables are accessed
and updated in a correct manner, such as changing value of a variable within a specified range.
Consider the following code of a setter method:

1 public void setNumber(int num) {


2 if (num < 10 || num > 100) {
3 throw new IllegalArgumentException();

4 }

5 this.number = num;

}
6

That ensures the value of number is always set between 10 and 100. Suppose the
variable number can be updated directly, the caller can set any arbitrary value to it:

1 obj.number = 3;

And that violates the constraint for values ranging from 10 to 100 for that variable. Of course we
don’t expect that happens. Thus hiding the variable number as private and using a setter comes
to rescue.
On the other hand, a getter method is the only way for the outside world reads the variable’s
value:

1 public int getNumber() {

2 return this.number;

3 }

The following picture illustrates the situation:


So far, setter and getter methods protect a variable’s value from unexpected changes by outside
world - the caller code.
When a variable is hidden by private modifier and can be accessed only through getter and
setter, it is encapsulated. Encapsulation is one of the fundamental principles in object-oriented
programming (OOP), thus implementing getter and setter is one of ways to enforce
encapsulation in program’s code.

Some frameworks such as Hiberate, Spring, Struts… can inspect information or inject their utility
code through getter and setter. So providing getter and setter is necessary when integrating your
code with such frameworks.

3. Naming convention for getter and setter


The naming scheme of setter and getter should follow Java bean naming convention as follows:

getXXX() and setXXX()


where XXX is name of the variable. For example with the following variable name:

1 private String name;

then the appropriate setter and getter will be:

1 public void setName(String name) { }

2
3 public String getName() { }

If the variable is of type boolean, then the getter’s name can be either isXXX() or getXXX(),
but the former naming is preferred. For example:

1 private boolean single;

2
3 public String isSingle() { }

The following table shows some examples of getters and setters which are qualified for naming
convention:

Variable Getter method Setter method


declaration
int quantity int getQuantity() void setQuantity(int qty)

string firstName String getFirstName() void setFirstName(String fname)

Date birthday Date getBirthday() void setBirthday(Date bornDate)

boolean rich boolean isRich() void setRich(Boolean rich)


boolean getRich()

4. Common mistakes when implementing getter and


setter
People often make mistakes, so do developers. This section describes the most common
mistakes when implementing setter and getter in Java, and workarounds.

Mistake #1: Have setter and getter, but the variable is declared in less
restricted scope.
Consider the following code snippet:

1
public String firstName;
2

3 public void setFirstName(String fname) {


4 this.firstName = fname;

5 }

7 public String getFirstName() {

return this.firstName;
8
}
9

The variable firstName is declared as public, so it can be accessed using dot (.) operator
directly, making the setter and getter useless. Workaround for this case is using more restricted
access modifier such as protected and private:

1 private String firstName;

In the book Effective Java, Joshua Bloch points out this problem in the item 14: In public classes,
use accessor methods, not public fields.
Mistake #2: Assign object reference directly in setter
Considering the following setter method:

1 private int[] scores;


2

3 public void setScores(int[] scr) {

4 this.scores = scr;

5 }

And following is code that demonstrates the problem:

1 int[] myScores = {5, 5, 4, 3, 2, 4};


2

3 setScores(myScores);

5 displayScores();

7 myScores[1] = 1;

8
9 displayScores();

An array of integer numbers myScores is initialized with 6 values (line 1) and the array is passed
to the setScores() method (line 2). The method displayScores() simply prints out all scores
from the array:

1 public void displayScores() {


2 for (int i = 0; i < this.scores.length; i++) {
3 System.out.print(this.scores[i] + " ");

4 }

5 System.out.println();

}
6

Line 3 will produce the following output:

1 5 5 4 3 2 4

That are exactly all elements of the myScores array.

Now at line 4, we can modify the value of the 2nd element in the myScores array as follow:

1 myScores[1] = 1;
What will happen if we call the method displayScores() again at line 5? Well, it will produce the
following output:

1 5 1 4 3 2 4

You can realize that the value of 2nd element is changed from 5 to 1, as a result of the
assignment in line 4. Why does it matter? Well, that means the data can be modified outside
scope of the setter method which breaks encapsulation purpose of the setter. And why that
happens? Let’s look at the setScores() method again:

1 public void setScores(int[] scr) {

2 this.scores = scr;

3 }

The member variable scores is assigned to the method’s parameter variable scr directly. That
means both the variables are referring the same object in memory - the myScores array object.
So changes made to either scores variable or myScores variable are actually made on the same
object.

Workaround for this situation is to copy elements from scr array to scores array, one by one.
The modified version of the setter would be like this:

1 public void setScores(int[] scr) {


2 this.scores = new int[scr.length];

3 System.arraycopy(scr, 0, this.scores, 0, scr.length);

4 }

What’s difference? Well, the member variable scores is no longer referring to the object referred
by scr variable. Instead, the array scores is initialized to a new one with size equals to the size
of the array scr. Then we copy all elements from the array scr to the array scores,
using System.arraycopy() method.

Run the example again and it will give the following output:

1 5 5 4 3 2 4

2 5 5 4 3 2 4

Now the two invocation of displayScores()produce the same output. That means the
array scores is independent and different than the array scr passed into the setter, thus the
assignment:

1 myScores[1] = 1;

does not affect the array scores.

Access Modifiers in Java


1. Private access modifier
2.Role of private constructor
3.Default access modifier
4.Protected access modifier
5.Public access modifier
6.Access Modifier with Method Overriding

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

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

There are four types of Java access modifiers:

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

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

Understanding Java Access Modifiers


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

Access within within outside outside


Modifier class package package by package
subclass only
Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is a compile-time error.

1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:

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

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

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

Example of default access modifier

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

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

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

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

3) Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

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

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

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

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

Example of public access modifier

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

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

Java Access Modifiers with Method Overriding


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

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

The default modifier is more restrictive than protected. That is why, there is a compile-
time error.
Call by reference:

1. public class Int {

int x;

Int(int i) { x = i; }

public static void swap(Int i, Int j) {

int temp=i.x;

i.x = j.x;

j.x = temp;

public static void main(String[] args) {

Int i = new Int(10);

Int j = new Int(20);

//int i=10,j=20;

swap(i, j);

System.out.println("i = " + i.x + ", j = " + j.x);

2. public class Swap {

int x;

Swap(int i) { x = i; }

public static void swap(Swap i, Swap j) {

int temp=i.x;

i.x = j.x;
j.x = temp;

public static void main(String[] args) {

Swap i = new Swap(10);

Swap j = new Swap(20);

//int i=10,j=20;

swap(i, j);

System.out.println("i = " + i.x + ", j = " + j.x);

Call by value and Call by reference in Java

Call by Value means calling a method with a parameter as value. Through this, the
argument value is passed to the parameter.

While Call by Reference means calling a method with a parameter as a reference.


Through this, the argument reference is passed to the parameter.

In call by value, the modification done to the parameter passed does not reflect in
the caller's scope while in the call by reference, the modification done to the
parameter passed are persistent and changes are reflected in the caller's scope.

Following is the example of the call by value −

The following program shows an example of passing a parameter by value. The


values of the arguments remain the same even after the method invocation.

Example - Call By Value


Live Demo

public class Tester{


public static void main(String[] args){
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b =
" + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping
values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is
" + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + "
b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b
= " + b);
}
}

Output
This will produce the following result −

Before swapping, a = 30 and b = 45


Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

Example - Call By Reference


Java uses only call by value while passing reference variables as well. It creates a
copy of references and passes them as valuable to the methods. As reference points
to same address of object, creating a copy of reference is of no harm. But if new
object is assigned to reference it will not be reflected.

Live Demo

public class JavaTester {


public static void main(String[] args) {
IntWrapper a = new IntWrapper(30);
IntWrapper b = new IntWrapper(45);
System.out.println("Before swapping, a = " + a.a + " and b
= " + b.a);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping
values will be different here**:");
System.out.println("After swapping, a = " + a.a + " and b
is " + b.a);
}
public static void swapFunction(IntWrapper a, IntWrapper b) {
System.out.println("Before swapping(Inside), a = " + a.a +
" b = " + b.a);
// Swap n1 with n2
IntWrapper c = new IntWrapper(a.a);
a.a = b.a;
b.a = c.a;
System.out.println("After swapping(Inside), a = " + a.a + "
b = " + b.a);
}
}
class IntWrapper {
public int a;
public IntWrapper(int a){ this.a = a;}
}

This will produce the following result −

Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be different here**:
After swapping, a = 45 and b is 30
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 usage of this keyword.
next →← prev

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 usage of this keyword.
1) this: to refer current class instance variable

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

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given
below:

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

Test it Now

Output:

0 null 0.0
0 null 0.0

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

Solution of the above problem by this keyword

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

Test it Now

Output:

111 ankit 5000


112 sumit 6000

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


need to use this keyword like in the following program:

Program where this keyword is not required

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

Test it Now

Output:

111 ankit 5000


112 sumit 6000

It is better approach to use meaningful names for variables. So we use same


name for instance variables and parameters in real time, and always use this
keyword.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while invoking
the method. Let's see the example

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

Test it Now

Output:

hello n
hello m

3) this() : to invoke current class constructor

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

Calling default constructor from parameterized constructor:

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

Test it Now

Output:

hello a
10

Calling parameterized constructor from default constructor:

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

Test it Now

Output:

5
hello a

Real usage of this() constructor call

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

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

Test it Now

Output:

111 ankit java null


112 sumit java 6000

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

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

Test it Now

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

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

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

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

Test it Now

Output:

method is invoked

Application of this that can be passed as an argument:

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


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

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

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

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

Test it Now

Output:10

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

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

Syntax of this that can be returned as a statement

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

Example of this keyword that you return as a statement


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

Output:

Hello java

Proving this keyword

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

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

Test it Now

Output:

A5@22b3ea59
A5@22b3ea59
Java Constructors
A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It
can be used to set initial values for object attributes:

Example

Create a constructor:

// Create a MyClass class


public class MyClass {
int x; // Create a class attribute

// Create a class constructor for the MyClass class


public MyClass() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


MyClass myObj = new MyClass(); // Create an object of class
MyClass (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5

Run example »

Note that the constructor name must match the class name, and it
cannot have a return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class


constructor yourself, Java creates one for you. However, then you are not
able to set initial values for object attributes.

Constructor Parameters
Constructors can also take parameters, which is used to initialize
attributes.
The following example adds an int y parameter to the constructor. Inside
the constructor we set x to y (x=y). When we call the constructor, we
pass a parameter to the constructor (5), which will set the value of x to 5:

Example
public class MyClass {
int x;

public MyClass(int y) {
x = y;
}

public static void main(String[] args) {


MyClass myObj = new MyClass(5);
System.out.println(myObj.x);
}
}

// Outputs 5

Run example »

You can have as many parameters as you want:

Example
public class Car {
int modelYear;
String modelName;

public Car(int year, String name) {


modelYear = year;
modelName = name;
}

public static void main(String[] args) {


Car myCar = new Car(1969, "Mustang");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}

// Outputs 1969 Mustang

Run example »
Copy Constructor in Java
Prerequisite – Constructors in Java
Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a
default copy constructor if you don’t write your own.
Following is an example Java program that shows a simple use of copy constructor.

// filename: Main.java

class Complex {

private double re, im;

// A normal parametrized constructor


public Complex(double re, double im) {
this.re = re;
this.im = im;
}

// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}

// Overriding the toString of Object class


@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}

public class Main {

public static void main(String[] args) {


Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call


Complex c2 = new Complex(c1);

// Note that following doesn't involve a copy constructor call as


// non-primitive variables are just references.
Complex c3 = c2;
System.out.println(c2); // toString() of c2 is called here
}
}
Output:

NESTED CLASSES:

next →← prev

Java Inner Classes


1. Java Inner classes
2. Advantage of Inner class
3. Difference between nested class and inner class
4. Types of Nested classes

Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more rea

Additionally, it can access all the members of outer class including private data members and metho

Syntax of Inner class

1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members (d
class including private.

2) Nested classes are used to develop more readable and maintainable code because it logicall
place only.

3) Code Optimization: It requires less code to write.

Do You Know

o What is the internal code generated by the compiler for member inner class ?
o What are the two ways to create annonymous inner class ?
o Can we access the non-final local variable inside the local inner class ?
o How to access the static nested class ?
o Can we define an interface within the class ?
o Can we define a class within the interface ?

Difference between nested class and inner class in Java


Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes


There are two types of nested classes non-static and static nested classes.The non-static nested clas

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Type Description

Member Inner A class created within class and outside method.


Class
Anonymous A class created for implementing interface or
Inner Class extending class. Its name is decided by the java
compiler.

Local Inner A class created within method.


Class

Static Nested A static class created within class.


Class

Nested Interface An interface created within class or interface.

next →← prev

Java static nested class


A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class
name.

o It can access static data members of outer class including private.


o Static nested class cannot access non-static (instance) data member or
method.

Java static nested class example with instance


method
1. class TestOuter1{
2. static int data=30;
3. static class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter1.Inner obj=new TestOuter1.Inner();
8. obj.msg();
9. }
10. }

Java static nested class example with static method


If you have the static member inside static nested class, you don't need to create
instance of static nested class.

1. class TestOuter2{
2. static int data=30;
3. static class Inner{
4. static void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestOuter2.Inner.msg();//no need to create the instance of static nested class
8. }
9. }
Test it Now

Output:

data is 30

next →← prev

Java Local inner class


A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.

Java local inner class example


1. public class localInner1{
2. private int data=30;//instance variable
3. void display(){
4. class Local{
5. void msg(){System.out.println(data);}
6. }
7. Local l=new Local();
8. l.msg();
9. }
10. public static void main(String args[]){
11. localInner1 obj=new localInner1();
12. obj.display();
13. }
14. }
Test it Now

Output:

30

next →← prev

Java Member inner class


A non-static class that is created inside a class but outside a method is called member
inner class.

Syntax:

1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }

Java Member inner class example


In this example, we are creating msg() method in member inner class that is
accessing the private data member of outer class.

1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11. }
Test it Now

Output:

data is 30

Java Anonymous inner class


A class that have no name is known as anonymous inner class in java. It should be used
if you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


1. abstract class Person{
2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }
Test it Now

Output:

nice fruits

Internal working of given code


1. Person p=new Person(){
2. void eat(){System.out.println("nice fruits");}
3. };
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 Anonymous class is created that is referred by p reference variable
of Person type.

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }

Java anonymous inner class example using interface


1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
Test it Now

Output:

nice fruits

Internal working of given code


It performs two main tasks behind this code:

1. Eatable p=new Eatable(){


2. void eat(){System.out.println("nice fruits");}
3. };
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 Anonymous class is created that is referred by p reference variable
of Eatable type.

Internal class generated by the compiler


1. import java.io.PrintStream;
2. static class TestAnonymousInner1$1 implements Eatable
3. {
4. TestAnonymousInner1$1(){}
5. void eat(){System.out.println("nice fruits");}
6. }

Ex:
package section17;

public class Temp {

int temp1 = 1;
int temp2 = 2;
int temp3 = 3;
int temp4 = 4;
class Inner {
private int temp5 = 5;
private int getSum() {
return (temp1 + temp2 + temp3 + temp4 + temp5);
} }

public static void main(String[] args) {


Temp obj = new Temp();
Temp.Inner t=obj.new Inner();
System.out.println(t.getSum()); } }

If STATIC then

public class Outer

{
static int temp1 = 1;

static int temp2 = 2;

static int temp3 = 3;

static int temp4 = 4;

public static class Inner {

private static int temp5 = 5;

private static int getSum() {

return (temp1 + temp2 + temp3 + temp4 + temp5);

} }

public static void main(String[] args) {

Outer.Inner obj = new Outer.Inner();

System.out.println(obj.getSum()); } }
FILES
package section17;
import java.io.IOException;
import java.io.PrintStream;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import java.util.Arrays;
import java.util.List;

public class Files {

public static void main(String[] args) throws IOException {


createFileUsingFileClass();
createFileUsingFileOutputStreamClass();

// TODO code application logic here


}
private static void createFileUsingFileClass() throws IOException {
File file = new File("D://testFile9.txt");
int a,b;
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
File file2 = new File("D://testFile10.txt");
PrintStream p=new PrintStream(file2);
p.print("add"+(a+b));
//Create the file
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
BufferedReader in = new BufferedReader(new
FileReader("D://testFile9.txt"));
String str;

while ((str = in.readLine()) != null) {


System.out.println(str);
}
/* //Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();*/
}
private static void createFileUsingFileOutputStreamClass() throws
IOException {
String data = "Test data";
FileOutputStream out = new FileOutputStream("D://testFile4.txt");
out.write(data.getBytes());
out.close();
}
}
package section17;
import java.io.IOException;
import java.io.PrintStream;
import java.io.*;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import java.util.Arrays;
import java.util.List;

public class Files {

public static void main(String[] args) throws IOException {


createFileUsingFileClass();
// createFileUsingFileOutputStreamClass();

// TODO code application logic here


}
private static void createFileUsingFileClass() throws IOException {
File file = new File("D:/testFile1.txt");
FileWriter writer = new FileWriter("D:/testFile2.txt");
// int a,b;
Scanner s=new Scanner(file);
// File file2 = new File("D://testFile10.txt");
// Scanner s2=new Scanner(file2);
// while(s.hasNextLine())
//{
//s2.nextInt();
//}
while(s.hasNext())
{
String s3=s.nextLine();
writer.write(s3+"\n");
}
writer.flush();
// System.out.println("Num1="+s2.next());
//}

// File file2 = new File("D://testFile10.txt");


//PrintStream p=new PrintStream(file2);
//p.print("add"+(a+b));
//Create the file
/* if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
} */
/* BufferedReader in = new BufferedReader(new
FileReader("D://testFile10.txt"));
String str;

while ((str = in.readLine()) != null) {


System.out.println(str);
}
//Write Content
/* FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();*/
/* }
private static void createFileUsingFileOutputStreamClass() throws
IOException {
String data = "Test data";
FileOutputStream out = new FileOutputStream("D://testFile4.txt");
out.write(data.getBytes());
out.close();
} */
}
}
Array of Objects

As we have already said, arrays are capable of storing objects also. For example, we can
create an array of Strings which is a reference type variable. However, using a String as
a reference type to illustrate the concept of array of objects isn't too appropriate due to the
immutability of String objects. Therefore, for this purpose, we will use a class Student
containing a single instance variable marks. Following is the definition of this class.

class Student {
int marks;
}

An array of objects is created just like an array of primitive type data items in the following
way.

Student[] studentArray = new Student[7];

The above statement creates the array which can hold references to seven Student
objects. It doesn't create the Student objects themselves. They have to be created
separately using the constructor of the Student class. The studentArray contains seven
memory spaces in which the address of seven Student objects may be stored. If we try to
access the Student objects even before creating them, run time errors would occur. For
instance, the following statement throws a NullPointerException during runtime which
indicates that studentArray[0] isn't yet pointing to a Student object.

studentArray[0].marks = 100;

The Student objects have to be instantiated using the constructor of the Student class and
their references should be assigned to the array elements in the following way.

studentArray[0] = new Student();

In this way, we create the other Student objects also. If each of the Student objects have
to be created using a different constructor, we use a statement similar to the above several
times. However, in this particular case, we may use a for loop since all Student objects
are created with the same default constructor.

for ( int i=0; i<studentArray.length; i++) {


studentArray[i]=new Student();
}

The above for loop creates seven Student objects and assigns their reference to the array
elements. Now, a statement like the following would be valid.

studentArray[0].marks=100;
Enhanced for loops find a better application here as we not only get the Student object
but also we are capable of modifying it. This is because of the fact that Student is a
reference type. Therefore the variable in the header of the enhanced for loop would be
storing a reference to the Student object and not a copy of the Student object which was
the case when primitive type variables like int were used as array elements.

for ( Student x : studentArray ) {


x.marks = s.nextInt(); // s is a Scanner object
}

Recall that we were not able to assign to the array elements in a similar way when the
array was of type int.

Moreover, in the case of array of objects, when we pass an array element to a method,
the object is susceptible to changes. This is because the element being passed is also a
reference type item. This differs from the situation when we have an int array. Following
illustrates this concept.

public static void main(String[] args) {


Student[] studentArray = new Student[7];
studentArray[0] = new Student();
studentArray[0].marks = 99;
System.out.println(studentArray[0].marks); // prints 99
modify(studentArray[0]);
System.out.println(studentArray[0].marks); // prints 100 and not 99
// code
}

public static void modify(Student s) {


s.marks = 100;
}

Compare the output with the one when the array was of type int[].

Processing an array of objects is much similar to the processing of an array of primitive


type. the only thing to be kept in mind is the possibility of NullPointerException being
thrown during run time and also remembering that the array elements themselves are
reference types, which brings subtle differences from the case when they are passed as
parameters. Moreover, an enhanced for loop may be used to initialise the array elements.
Java Menu Driven Calculator Example

Given below is a java based menu driven program example to create a simple calculator
application.
package JavaMenuProgram;

import java.util.Scanner;

public class CalculatorMenu {

static int result;


public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Welcome to BhartiyaCalculators.com");

//Creating Menu
while(true){
System.out.println();
System.out.println("Enter first number::");
int firstNumber = scan.nextInt();
System.out.println("Enter second number::");
int secondNumber = scan.nextInt();

System.out.println("To perform addition, Enter 1");


System.out.println("To perform subtraction, Enter
2");
System.out.println("To perform division, Enter 3");
System.out.println("To perform multiplication, Enter
4");
System.out.println("To Exit, Enter 9");

System.out.println();
System.out.println("Enter choice::");
int choice = scan.nextInt();

switch(choice){
case 1: System.out.println("Adding the numbers");
add(firstNumber, secondNumber);
break;
case 2: System.out.println("Subtracting the
numbers");
subtract(firstNumber, secondNumber);
break;
case 3: System.out.println("Dividing the numbers");
divide(firstNumber, secondNumber);
break;
case 4: System.out.println("Multiplying the
numbers");
multiply(firstNumber, secondNumber);
break;
case 9: System.out.println("Thanks for ordering from
our App. Visit again");
System.exit(0);
break;
default: System.out.println("Incorrect input!!!
Please re-enter choice from our menu");
}
}
}

//Method for addition


public static void add(int num1, int num2){
result = num1+num2;
System.out.println("Addition result="+ result);

}
//Method for subtraction
public static void subtract(int num1, int num2){
result = num1-num2;
System.out.println("Subtraction result="+ result);
}
//Method for multiplication
public static void multiply(int num1, int num2){
result = num1*num2;
System.out.println("Multiplication result="+ result);
}
//Method for division
public static void divide(int num1, int num2){
result = num1/num2;
System.out.println("Division result="+ result);
}

}
OUTPUT:
Welcome to BhartiyaCalculators.com

Enter first number::


6
Enter second number::
8
To perform addition, Enter 1
To perform subtraction, Enter 2
To perform division, Enter 3
To perform multiplication, Enter 4
To Exit, Enter 9

Enter choice::
6
Incorrect input!!! Please re-enter choice from our menu

Enter first number::


6
Enter second number::
8
To perform addition, Enter 1
To perform subtraction, Enter 2
To perform division, Enter 3
To perform multiplication, Enter 4
To Exit, Enter 9

Enter choice::
4
Multiplying the numbers
Multiplication result=48

You might also like