Professional Documents
Culture Documents
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.
class Simple
{
System.out.println("Hello World");
To compile:
javac Simple.java
To execute:
java Simple
Output:Hello Java
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.
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.
import java.util.Scanner;
• Creation of object of Scanner class will be used to get input from the user.
import java.util.Scanner;
class Input
}
Enter float: 2.343
2. import java.util.Scanner;
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("CGPA: "+cgpa);
Input :
Lucky
40
9876543210
9.9
Output :
Name: Lucky
Gender: M
Age: 40
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;
}
}
• Identifier can contain alphabets [A-Z] & [a-z], Digits [0-9], underscore(_) and dollar($).
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:
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.
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.
Reference Variable
Variables declared with used defined data types are called as reference variables.
There are following types of variables based on the scope of the variables:
• Instance variables
• Static variables
• Local variables
EXAMPLE:
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
System.out.println(20>>2);
System.out.println(10>>>2);
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:
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 {
// Getter
return name;
// Setter
this.name = newName;
Example explained
Example
public class MyClass {
System.out.println(myObj.name); // error
Run example »
If the variable was declared as public, we would expect the following output:
John
Example
public class MyClass {
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
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
class Complex {
this.re = re;
this.im = im;
// copy constructor
Complex(Complex c) {
re = c.re;
im = c.im;
@Override
Complex c3 = c2;
Output:
// filename: Main.java
class Complex {
this.re = re;
this.im = im;
}
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
/*************************************************************
*****************
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.
*************************************************************
******************/
class Complex {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
re = c.re;
im = c.im;
// @Override
import java.util.Scanner;
public class Demo {
}
public String getBreadth() {
return this.bt+"m";
}
public String getHeight() {
return this.ht+"m";
}
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
6 }
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:
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
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.
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:
2 return this.number;
3 }
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.
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:
2
3 public String isSingle() { }
The following table shows some examples of getters and setters which are qualified for naming
convention:
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
5 }
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:
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:
4 this.scores = scr;
5 }
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:
4 }
5 System.out.println();
}
6
1 5 5 4 3 2 4
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:
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:
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;
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.
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.
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.
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. }
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It
provides more accessibility than private. But, it is more restrictive than protected, and
public.
In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
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.
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method
of this package is declared as protected, so it can be accessed from outside the class
only through inheritance.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
1. //save by 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
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:
int x;
Int(int i) { x = i; }
int temp=i.x;
i.x = j.x;
j.x = temp;
//int i=10,j=20;
swap(i, j);
int x;
Swap(int i) { x = i; }
int temp=i.x;
i.x = j.x;
j.x = temp;
//int i=10,j=20;
swap(i, j);
Call by Value means calling a method with a parameter as value. Through this, the
argument value 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.
Output
This will produce the following result −
Live Demo
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.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
next →← prev
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.
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.
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:
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:
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
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.
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
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
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:
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
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
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
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:
1. return_type method_name(){
2. return this;
3. }
return_type method_name(){
return this;
}
Output:
Hello java
Let's prove that this keyword refers to the current class instance variable. In this
program, we are printing the reference variable and this, output of both variables
are same.
1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
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:
// 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.
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;
}
// Outputs 5
Run example »
Example
public class Car {
int modelYear;
String modelName;
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 {
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
NESTED CLASSES:
next →← prev
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
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
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.
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 ?
Type Description
next →← prev
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
Output:
30
next →← prev
Syntax:
1. class Outer{
2. //code
3. class Inner{
4. //code
5. }
6. }
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
Output:
nice fruits
Output:
nice fruits
Ex:
package section17;
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);
} }
If STATIC then
{
static int temp1 = 1;
} }
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;
import java.util.Arrays;
import java.util.List;
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.
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.
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.
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.
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.
Compare the output with the one when the array was of type int[].
Given below is a java based menu driven program example to create a simple calculator
application.
package JavaMenuProgram;
import java.util.Scanner;
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();
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 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 choice::
6
Incorrect input!!! Please re-enter choice from our menu
Enter choice::
4
Multiplying the numbers
Multiplication result=48