Java Module 2
Java Module 2
class classname {
type instance-variable1;
type instance-variable2;
...
type instance-variableN;
type methodname1(parameter-list)
{ body of method }
type methodname2(parameter-list)
{ body of method }
...
type methodnameN(parameter-list)
{ body of method }
}
A Simple Class
class Box
{
double width;
double height;
double depth;
}
To create a Box object,
Box mybox = new Box();
To access class variables, dot (.) operator is used.
The dot operator links the name of the object with the name of an
instance variable
For example, mybox.width = 100;
/* A program that uses the Box class.
Call this file BoxDemo.java*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
// This program declares two Box objects.
class Box {
double width;
double height;
double depth; }
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10; //assign values to mybox1's instance variables
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3; //assign values to mybox1's instance variables
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
} }
Declaring Objects
Obtaining objects of a class is a two-step process.
First, you must declare a variable of the class type.
This variable does not define an object.
It is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and
assign it to that variable using new operator.
The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it.
This reference is then stored in the variable
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
We can combine both statements
Box mybox = new Box();
Assigning Object Reference Variables
What do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
What happens here ?
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Introducing Methods
General form of a method:
type name(parameter-list)
{
// body of method
}
type specifies the type of data returned by the method
any valid type, including class types that you create
If the method does not return a value, its return type must be void
The name of the method is specified by name
The parameter-list is a sequence of type and identifier pairs separated
by commas
If the method has no parameters, then the parameter list will be empty.
To return a value to the calling routine using return statement can be
used.
Eg:- return value;
Adding a Method to the Box Class
class Box { double width;
double height;
double depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10; // assign values to mybox1's instance variables
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3; /*assign different values to mybox2’s instance variables*/
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume(); // display volume of first box
mybox2.volume(); // display volume of second box
Returning a Value
class Box { double width;
double height;
double depth;
class BoxDemo4 {
double vol;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.height = 6;
mybox2.depth = 9;
} }
Method That Takes Parameters
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth; }
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d; } }
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
Constructors
double width;
double height;
double depth;
Box(Box ob) {
width = ob.width;
height = ob.height;
depth = ob.depth; }
{ width = w;
height = h;
depth = d; }
height = -1;
depth = -1; }
}
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); // create copy of mybox1
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
Argument Passing
There are two ways that a computer language can pass an argument to
a subroutine.
call-by-value and call-by-reference.
In call by value approach, it copies the value of an argument into the
formal parameter of the subroutine.
ie, changes made to the parameter of the subroutine have no effect on
the argument.
In call by reference approach, a reference to an argument (not the value
of the argument) is passed to the parameter. Inside the subroutine, this
reference is used to access the actual argument specified in the call.
ie, changes made to the parameter will affect the argument used to call
the subroutine.
Java uses both approaches, depending upon what is passed.
when you pass a primitive type to a method, it is passed by value.
Thus, what occurs to the parameter that receives the argument has no effect
outside the method.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
} }
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
} }
a and b before call: 15 20
a and b after call: 15 20
When you pass an object to a method, it is passed by call-by-
reference
When you create a variable of a class type, you are only creating
a reference to an object.
When you pass this reference to a method, the parameter that
receives it will refer to the same object as that referred to by the
argument.
This means that objects are passed to methods by use of call-by-
reference.
Changes to the object inside the method do affect the object
used as an argument.
class Test {
int a, b;
Test(int i, int j)
{ a = i;
b = j; }
void meth(Test o) // pass an object
{ o.a *= 2;
o.b /= 2;
} }
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
} }
ob.a and ob.b before call: 15 20
Returning Objects
A method can return any type of data, including class types that you
create.
For example, in the following program, the incrByTen( ) method returns
an object in which the value of a is ten greater than it is in the invoking
object.
// Returning an object.
class Test {
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
class RetOb
{
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
}
ob1.a: 2
ob2.a: 12
Recursion
Java supports recursion.
Recursion is the process of defining something in terms of
itself.
Recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive
The classic example of recursion is the computation of the
factorial of a number.
The factorial of a number N is the product of all the whole
numbers between 1 and N.
class Factorial {
int fact(int n) // this is a recursive method
{ int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
} }
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
} }
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
class RecTest {
int values[];
RecTest(int i) {
values = new int[i];
}
// display array -- recursively
void printArray(int i)
{
if(i==0) return;
else printArray(i-1);
System.out.println("[" + (i-1) + "] " + values[i-1]);
} }
class Recursion2
{
public static void main(String args[]) {
RecTest ob = new RecTest(10);
int i;
for(i=0; i<10; i++) ob.values[i] = i;
ob.printArray(10);
} }
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9
Access Control
Encapsulation provides another important attribute: access control
Through encapsulation, we can control what parts of a program can
access the members of a class.
By controlling access, we can prevent misuse.
Allowing access to data only through a well defined set of methods, you
can prevent the misuse of that data.
How a member can be accessed is determined by the access specifier
that modifies its declaration.
Java supplies a rich set of access specifiers. Some aspects of access
control are related mostly to inheritance or packages
Access Control
Java’s access specifiers are public, private, and protected
protected applies only when inheritance is involved
When a member of a class is modified by the public specifier, then that
member can be accessed by any other code.
When a member of a class is specified as private, then that member can
only be accessed by other members of its class.
When no access specifier is used, then by default the member of a class is
public within its own package, but cannot be accessed outside of its package.
An access specifier precedes the rest of a member’s type specification. That
is, it must begin a member’s declaration statement.
For example:
public int i;
private double j;
private int myMethod(int a, char b) { // ...
It is possible to define a class within another class; such classes are known
as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
If class B is defined within class A, then B does not exist independently of
A.
A nested class has access to the members, including private members, of
the class in which it is nested.
The enclosing class does not have access to the members of the nested
class.
A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class.
It is also possible to declare a nested class that is local to a block.
Nested and Inner Classes
There are two types of nested classes: static and non-
static.
A static nested class is one that has the static modifier
applied.
Because it is static, it must access the members of its
enclosing class through an object. That is, it cannot refer to
members of its enclosing class directly.
Because of this restriction, static nested classes are seldom
used.
An inner class is a non-static nested class.
It has access to all of the variables and methods of its outer
class and may refer to them directly in the same way that
other non-static members of the outer class do.
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display(); }
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
} } }
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
} }
strOb1.length());
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
Else
System.out.println("strOb1 != strOb3");
} }
Length of strOb1: 12
strOb1 != strOb2
strOb1 == strOb3
Command-Line Arguments
In Java, command-line arguments allow you to pass data to your
program when you run it from the command line.
These arguments are passed to the main method as an array of string
object.
public static void main(String[] args)
The args array contains the command-line arguments.
The number of arguments is determined by args.length
Each argument is accessed through args[index]
public class CommandLineArguments {
public static void main(String[] args) {
// Check if any arguments are passed
if (args.length > 0) {
System.out.println("Command-line arguments:");
// Loop through the arguments and print each one
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
} else {
System.out.println("No command-line arguments passed.");
} } }
javac CommandLineArguments.java
java CommandLineArguments arg1 arg2 arg3
Command-line arguments:
Argument 0: arg1
Argument 1: arg2
Argument 2: arg3