Java Unit-2 Material
Java Unit-2 Material
Introduction
Java is a pure object-oriented language. The class is the basis of an object-oriented
programming language. The class acts as a blueprint from which objects can be created. The
object is an instance of class. We can create any number of objects from a class. The class is the
type of the objects.
There are different types of classes. A class may be Top level class, nested class, derived
class, super class, or an anonymous class.
According to the convention of java language, a class name starts with Upper-Case latter.
In case if the class name contains more than one word, then all the words begin with Upper-Case
1
letters. Space is not allowed in the class name. There are certain rules to be followed for the
class name:
i. The class name should be simple and descriptive
ii. Class name should start with upper-case letter and should be nouns.
iii. Space in the class name is not allowed.
iv. Keywords cannot be used as class names.
Class Modifiers
The class modifiers are used to control the access to the class and its inheritance characteristics.
The Java has number of packages. The packages contain sub-packages and classes. The java has
various modifiers as follow:
Modifiers Description
No modifier The class declared without modifier is accessible to the classes in the
its own package.
public When a class is declared as public, it is accessible to all the classes in
all the packages.
private Class is accessible to other members of the Outer class
protected Class is accessible to other members of the Outer class as well as by
classes derived from the outer class.
final When a class is declared as final, it cannot be inherited.
The abstract class can contain abstract methods and non-abstract
abstract methods. The abstract methods contain method declaration, body
will be implemented by the derived class. Non-abstract method
contains body also.
2. Class Members
The members that are declared inside the class are called class members. These members
include fields, methods, nested classes, and interfaces. The field can be instance variable and
class variable. The instance variables are belong to an object, and every object keeps a copy of
these variables. The class variables are declared with modifier static. These are not copied to
objects, they always stay with class. All the objects will share the class variables.
Write a java Program to demonstrate the difference between instance variable and class
variable.
2
}
}
class ClassMembers
{
public static void main(String arg[])
{
EmpData emp1=new EmpData(" Herbert Schildt ",100);
[Link]();
EmpData emp2=new EmpData(" Anitha Seth ",200);
[Link]();
}
}
Example: [Link]
class Area
{
int length;
int width; Output:
}
public class Test
{
public static void main(String args[])
{
Area a1;
a1=new Area();
[Link]=10;
[Link]=20;
double area1=[Link]*[Link];
[Link]("The Area of the Field is :"+area1);
}
}
3
4. Assigning an object to Another Object
When an object of a class is assigned to another object of same class, the first object can access
the data and methods of second object. This can be understood from the following program:
Example,
Output:
class AssignObjectToAnother
{
//instance variables
int length,width;
}
class Test
{
public static void main(String args[])
{
//create objects
AssignObjectToAnother f1=new AssignObjectToAnother();
AssignObjectToAnother f2=new AssignObjectToAnother();
//initialize instance variables of obj1 object
[Link]=25;
[Link]=40;
[Link]("The width of f1 before assigning is :"+[Link]);
f2=f1;
[Link]=100;
[Link]("The width of f2 is :"+[Link]);
[Link]("The width of f1 is :"+[Link]);
}
}
In the above program two objects f1 and f2 are created from the same class. The instance
variables of object f1 are assigned. And later f1 is assigned to f2 object. The instance variable
‘width’ of f2 is assigned as [Link]=40. When we print the value of instance variable width of
both f1 and f2 after assignment it is printed as 100. But, before assignment the value of the
instance variable width of f1 is 40. From this we can understand that when an object a class is
assigned to another object of same class, both will be pointing the same memory, and hence both
objects instance variables values will be same.
4
5. Access Control for Class Members
The access to the class members can be controlled by placing the suitable
modifier/access specifier before the member in the class definition. There are three access
specifiers: public, private, and protected. The syntax for access specifiers will be as follow:
Access specifier type indentifier;
Example:
int x=25;
public int a=20;
private float f=3.45f;
protected double y=12.34;
5
int i=1, j=1,count=2,k; //instance variables
void fib(int num)
{ [Link]("Fibonacci Series:");
[Link](i+" "+j);
while(count<num)
{
k=i+j; Output:
[Link](" "+k);
i=j;
j=k;
count++;
}
if(count==num)
{
[Link]();
[Link]("nth digit:"+k);
}
}
}
public class FibonacciSeries
{
public static void main(String args[])
{
Fibonacci f1=new Fibonacci();
Scanner in = new Scanner([Link]);
[Link]("Enter range of n valiue");
int num=[Link]();
[Link](num);
}
}
Example,
class PrivateMembers
{
private int length,width; //private data members and instance variables
}
public class PrivateDemo {
public static void main(String arg[]) {
PrivateMembers pm=new PrivateMembers(); //create objects
[Link]=25; //accessing the private members outside the class
[Link]=40;
6
int area=[Link]*[Link]; //accessing private data
[Link]("The area is :"+area);
}
}
Output:
However, with the help of the public method of the class, the private members can be accessed.
We can define a public method called setSides(). This method is accessed outside the class to
initialize the private data members. Along with this we also can define another public method
called “area()” to find the area of the Farm as shown in the following program.
Example,
class PrivateData
{
private int length,width; //private data members and instance variables
public int setSides(int l,int w) Output:
{
length=l;
width=w;
return(length*width);
}
}
class PrivateMembers {
public static void main(String arg[]) {
PrivateData p1=new PrivateData(); //create objects
//access public methods here with object p1
[Link]("Area of the Rectangle is :"+[Link](25,40));
}
}
7
Accessing the Private Methods of a Class:
You can call the private method from outside the class by changing the runtime behavior
of the class. If we want to hide the methods from accessing by user outside the class, then the
methods are declared as private. If we want to access private method, it could be done with the
help of the public method. A call to the private method is made inside the public method
definition. This is shown in the following program
Exampe,
class PrivateDemo
{
private int length, width; //private data members and instance variables
private void setSides(int l, int w) //private method
{
length=l; Output:
width=w;
}
public int area(int l, int w)
{
setSides(l,w); //call to the private method
return(length*width);
}
}
public class PrivateMembers{
public static void main(String arg[])
{
PrivateDemo p1=new PrivateDemo(); //create objects
//access public method here with object p1
[Link]("The area of the Rectangle is :"+[Link](4,5));
}
}
8. Constructor Methods for Class
A constructor is a block of code similar to the method. It is called when an instance of
the class is created. It is a special type of method which is used to automatically initialize the
object. Every time an object is created using the new keyword, at least one constructor is called.
A constructor name must be the same as its class name and it should not return a value not
even void..
We have two types of constructors. They are default constructor and parameterized
constructor. The default construct cannot take any arguments. Whereas, the parameterized
constructor will take parameters. A Java constructor cannot be abstract, static, final, and
synchronized. At the time of calling constructor, memory for the object is allocated in the
memory.
Example, [Link]
class BankAccount
{
long accno;
String name;
String bankName;
String ifscCode;
8
float balance;
BankAccount(String bn, String ifsc,long ano,String n,float bal) // This is the constructor method
{
bankName=bn;
ifscCode=ifsc; Output:
accno=ano;
name=n;
balance=bal;
}
void displayAccountDetails() {
[Link]("Name of Bank :"+bankName);
[Link]("IFSC Code :"+ifscCode);
[Link]("A/C Holder Name :"+name);
[Link]("A/C No :"+accno);
[Link]("Balance Amount :"+balance);
}
void withDraw(float withDrawAmt) {
if(balance>=withDrawAmt) {
balance=balance-withDrawAmt;
[Link]("After Withdrawing the Balance Amount is :"+balance);
}
else
[Link]("In sufficient founds available.......");
}
void deposit(float depositAmt) {
balance=balance+depositAmt;
}
}
public class ConstructorExample
{
public static void main(String args[])
{
BankAccount ac1=new BankAccount("SBI","SBIN0001009",741256526,"Karth",90000);
[Link]();
[Link](50000);
[Link]("After depositing balance Amount is:"+[Link]);
[Link](20000);
}
}
9
Example, [Link]
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate an uninitialized box
height = -1;
depth = -1;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
} Output:
// compute and return volume
double volume() {
return width * height * depth;
}
}
public class OverloadConstructors {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(5, 10, 8);
Box mybox2 = new Box();
Box mycube = new Box(4);
double vol;
// get volume of first box
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
// get volume of second box
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
// get volume of cube
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}
10
objects are required to perform similar tasks but using different input parameters. This is
similar to the constructor overloading.
Example, [Link]
import [Link].*;
class Summation {
int sum(int a, int b) // Overloaded sum(). This sum takes two integer parameters
{
return (a + b);
}
float sum(float x, float y, float z) //Overloaded sum(). This sum takes three float parameters
{
return (x + y + z);
}
// Overloaded sum(). This sum takes four double parameters
double sum(double x, double y, double z, double k)
{
return (x + y + z + k);
}
}
public class MetodOverloading
{ Output:
public static void main(String args[])
{
Summation s = new Summation();
Scanner in = new Scanner([Link]);
[Link]("Enter a value");
int a = [Link]();
[Link]("Enter the b value");
int b = [Link]();
int sum1= [Link](a, b);
[Link]("Summation1:"+sum1);
[Link]("Enter x value");
float x= [Link]();
[Link]("Enter the y value");
float y = [Link]();
[Link]("Enter the z value");
float z = [Link]();
float sum2=[Link](x,y,z);
[Link]("Summation2:"+sum2);
double sum3=[Link](10.5, 20.5, 25.0, 40.5);
[Link]("Summation3:"+sum3);
}
}
11
If the inner class is declared as static, it can be accessed without creating object an object
of outer class. If the inner class is declared as non-static, then we have to create object from the
outer class first, and create object of inner class, and then access the inner class object using the
outer class object.
Write a java program to demonstrate non-static Inner class? [Link]
class Outer
{
int length,width;
public void display(int l, int w)
{
length=l;
width=w;
Inner iner=new Inner(); //inner class object is created inside the outer class
[Link]();
}
class Inner //non-static Inner Class Output:
{
public void area()
{
int a=length*width;
[Link]("The area is :"+a);
}
}
}
public class NestedClasses
{
public static void main(String arg[])
{
Outer ob1=new Outer(); //Create object from Outer class
[Link](10,20);
}
}
Important Points:
1. The inner class has access to all the outer class members.
2. The outer class doesn’t have direct access to inner class members. It is possible through
the reference of the inner class object.
3. The object of inner class may be declared in the scope of outer class.
4. The method of inner object may be accessed through the object of inner class by the
outer class object.
Anonymous Class:
We can write a class inside another class. This is called nesting of classes. It is possible
to create a nested class without giving any name. The nested class that doesn’t contain any name
is called “Anonymous Class”. The Syntax of the anonymous class will be as follow:
class AnonymousEx
{ public static void main(String args[])
{
12
Object1=new Type(parameters_list) { //defining the anonymous class
//body of the anonymous class
};
}
}
The anonymous classes usually extend super class or implement the interface. The
keywords ‘extends’ or ‘implements’ do not appear in the definition. Anonymous class is
used where the class has to be used only once.
Write a java program to demonstrate the Anonymous class by extending the super class.
class Person
{ void display()
{
[Link](“Welcome to SACET");
}
}
class AnonymousEx
{ public static void main(String args[])
{ //object creation
Person p=new Person() { //body of the anonymous class Output:
void display()
{
[Link](" Welcome to CSE");
}
}; //end of anonymous class
[Link](); //calling the display method
}
}
13
Local Class:
A local class is declared in a block or method, and hence the scope of the Local class is
limited to the block or method in which it is defined. These classes can refer local variables or
parameters which are declared as final (constants).These are not visible outside the block or
method, and hence access modifiers such as public, private, and protected cannot be applied to
these classes.
Write a java program to demonstrate Local Class. [Link]
class LocalDemo
{
public static void main(String arg[])
{
final double PI=3.14;
class LocalClass //Local Class Definition starts here Output:
{
void circleArea(int r)
{
double a=PI*r*r;
[Link]("The area of Circle is :"+a);
}
}
//creating object from local class and calling the method
LocalClass lc=new LocalClass ();
[Link](2);
}
}
class StaticNested
{ static int length,width;
static class Inner //static Inner Class
{
14
public static void main(String arg[])
{
//Inner class object is accessed using outer class name.
[Link] i1=new [Link]();
[Link](4,5);
[Link]();
}
}
12. Attribute Final
final keyword is used in different contexts. First of all, final is a non access modifier applicable
only to a variable, a method, or a class. The java final keyword can be used in many context as
follows:
i. final variable
ii. final method
iii. final class
i. final variables
When a variable is declared with the final keyword, its value can’t be modified,
essentially, a constant. If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.
class BikeRace{
final int speedlimit=90; //final variable
void run()
{
speedlimit=100; // final variable value can’t be change
}
public static void main(String args[])
{
BikeRace obj=new BikeRace();
[Link]();
}
} Output: Compile time Error
ii. final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. We must declare methods with the final keyword for
which we are required to follow the same implementation throughout all the derived
classes.
Example , Write a java program to demonstrate Final Method
class A { //A is super class
final void meth() { // final method
[Link]("This is a final method.");
}
}
class B extends A { //B is sub class
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}}
15
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so,
a compile-time error will result.
iii. final class
When a class is declared with final keyword, it is called a final class. A final class cannot
be extended(inherited). Declaring a class as final implicitly declares all of its methods as
final, too.
For example, Write a java program to demonstrate Final class
final class A
{
void dispA()
{
[Link]("Method of class A");
}
}
class B extends A //here A cannot be inherited Output:
{
void dispB()
{
[Link]("Method of class B");
}
}
class FinalTest
{
public static void main(String arg[])
{
B b=new B();
[Link]();
[Link]();
}
}
16
public class StaticExample { Output:
static int num = 500; //static variable
static String str = “II CSE SACET";
static void display() // This is Static meth od
{
[Link]("\nStatic number is " + num);
[Link]("\nStatic string is " + str);
}
void nonstatic() // non-static method
{
display(); // Static method can also access in non static method
}
public static void main(String args[]) // main method
{
StaticExample obj = new StaticExample(); //object creation
[Link](); // This is object to call non static function
[Link](); // static method can called directly without an obj
}
}
17
Scanner in = new Scanner([Link]);
[Link]("Enter the n valiue");
int num=[Link]();
[Link]("Factorial of given Number: "+[Link](num));
}
}
15. Keyword this
• There may be a situation where the names of the local variables and the instance variable
names could be same. In such a context the local variables will hide the instance
variables.
• To access the instance variables in such a situation is done with the help of ‘this’
keyword. The ‘this’ keyword will provide the reference to the current object.
• The ‘this’ keyword is used before the instance variable with dot operator. (syntax:
this.instance_variable=local_variable;)
class Rectangle
{
int length,width; // instance variables
Rectangle(int length,int width) //local variables
{
[Link]=length;
[Link]=width;
}
void area()
{
18
[Link]("The area of Rectangle is :"+(length*width));
}
} Output:
class ThisDemo
{
public static void main(String arg[])
{
Rectangle r=new Rectangle(5,4);
[Link]();
}
}
19
Test(int l, int w)
{
length=l;
width=w;
}
void area (Test t ) //here t is object and its type is Test
{
int a=[Link]*[Link]; Output:
[Link]("The area is:"+a);
}
}
class ObjectAsParameter
{
public static void main(String args[])
{
Test t1=new Test(20,30);
[Link](t1); //here t1 is an object and is passed as argument
}
}
[Link] Arguments byValue and by Reference (or)Call by Value and Call by Reference
• When a method is defined with local variables, the values are passed by value, that is,
the values of actual arguments are copied to the formal parameters. The method may
manipulate these values without affecting the actual arguments. This is called passing
arguments by values.
• However, if a method is defined with parameters as Objects, and if method changes
values of the instance variables of the object, then the changed values are retained by the
object. That means, if the values are changed in parameters of the method, it will affect
the actual arguments also. This is called passing arguments through reference.
Write a java program to demonstrate the passing arguments by values.
class PassByValue
{
void swap(int x,int y) //here x, and y are parameters
{
int temp; Output:
temp=x;
x=y;
y=temp;
}
}
class PassByValueTest {
public static void main(String arg[]) {
int a=5,b=6;
PassByValue pbv=new PassByValue();
[Link]("Before swap a=%d and b=%d\n",a,b);
[Link](a,b); //here a and b are actual arguments
[Link]("After swap a=%d and b=%d\n",a,b);
}
}
20
Write a java program to demonstrate the passing arguments through reference.
class PassByReference
{
int a,b; //instance variables
PassByReference(int m,int n) //m and n are parameters of constructor
{
a=m;
b=n;
}
void swap(PassByReference pbr) //here object is parameter
{
int temp; Output:
temp=pbr.a;
pbr.a=pbr.b;
pbr.b=temp;
}
}
class PassByRefTest
{
public static void main(String arg[])
{
PassByReference pbr=new PassByReference(5,6);
[Link]("Before swap a=%d and b=%d\n",pbr.a,pbr.b);
[Link](pbr); //here pbr object is actual argument
[Link]("After swap a=%d and b=%d\n",pbr.a,pbr.b);
}
}
For example ,
class Shape
{
void draw()
{
[Link]("Drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
[Link]("Drawing Rectangle...");
}
21
}
class Circle extends Shape
{
void draw()
{
[Link]("Drawing Circle...");
}
}
class Triangle extends Shape Output:
{
void draw()
{
[Link]("Drawing Triangle...");
}
}
public class MethodOverriding
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
[Link]();
s=new Circle();
[Link]();
s=new Triangle();
[Link]();
}
}
FAQs
Subject : JAVA PROGRAMMING Year/Sem: II [Link] – II Sem
Academic Year: 2022-23 Regulation: R20
UNIT-2:
1. What is an Object? How to allocate memory for objects? How to assign the values to the
variables in the class during the time of creation of an object to that class? Explain with
an example.
2. What is the difference between ‘static’ and ‘non-static’ methods in JAVA? Describe the
usage of static members and nesting members with suitable example programs in java.
3. a) What is a Constructor? What is the main purpose of Constructors? How to invoke a
constructor in JAVA?
b) Write a java program to illustrate the Methods by passing arguments by Value and
passing arguments by reference.
22
4. a) Explain the use of ‘this’ keyword with an example.
b) Write about ‘Final’ keyword and explain with an example.
5. a) Write the importance of static constructor.
b) What is the importance of constructor? Write a java program to perform constructor
overloading. Can we use constructors with parameters? What kind of parameters can be
given? Explain with area of various geometric shapes example.
6. a) Design a class that represents a bank account and construct the methods to
i) Assign initial values
ii) Deposit an amount
iii) Withdraw amount after checking balance
iv) Display the name and balance.
b) Do you need to use static keyword for the above bank account program? Explain.
7. a) Write a program that shows an Employee class which contains various methods for
accessing employee’s personal information and methods for paying an employee.
8. a) Discuss the significance of Overriding Methods with a program.
b) Write a Java method to find minimum values in given two values.
9. a) Write a Java program to read a number of any lengths. Perform the addition and
subtraction on the largest and smallest digits of it.
b) Write a Java Program to find sum of natural numbers.
10. a) Explain the concept of Nesting of Methods with an example.
b) Write a Java Program to swap two numbers using bitwise operator.
11. a) Compare the working of constructor overloading with method overloading.
b) Demonstrate method overriding with an example java program.
12. a) Compare the pass-by-value with the pass-by-reference method using an example.
b) Demonstrate Nested class concept with an example.
13. a) Develop a program to carry out withdrawal operations in ATM.
b) Develop a method that initializes the attributes of an object.
14. a) Develop a program to compute the GCD of two numbers using Recursion.
b) Is it possible to access Private members of a class? Justify your answer.
15. a) Define recursion. Discuss the advantages of recursion.
b) Is it possible to define a class within another class? Justify your answer.
23