cs23312-unit 1
cs23312-unit 1
1. Define objects and classes in Java (2) (Nov/Dec 2019) (Nov/Dec 2018)
2. Explain the characteristics of OOPs (6) (Nov/Dec 2019)
3. Explain the features and characteristics of Java (7) (Nov/Dec 2019)
4. Define Encapsulation in Java(2) (APR/MAY 2021)
5. Discuss the three OOP principles in detail (7) (APR/MAY 2019)
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity that has state and behavior is
known as an object. Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing details of each other's data or code,
the only necessary thing is that the type of message accepted and type of response returned by the objects.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to
the external user. But it is used internally by the JVM to identify each object uniquely.
1
CLASS
Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from
which you can create an individual object. A class consists of Data members and methods. The primary
purpose of a class is to hold data/information. The member functions determine the behavior of the class,
i.e. provide a definition for supporting various operations on data held in the form of an object. Class doesn’t
store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from the parent
class. When one object acquires all the properties and behaviours of another object, it is known as
inheritance. It provides code reusability and establishes relationships between different classes. A class
which inherits the properties is known as Child Class (sub-class or derived class) whereas a class whose
properties are inherited is known as Parent class (super-class or base class). Types of inheritance in java:
single, multilevel and hierarchical inheritance. Multiple and hybrid inheritance is supported through
interface only.
POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism. For example: to convince
the customer differently, to draw something e.g. shape or rectangle etc.
2
Method Overriding (Run time Polymorphism)
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java. In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only functionality to the
user. For example: phone call, we don't know the internal processing. In java, we use abstract class and
interface to achieve abstraction.
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines. A java class is the example of encapsulation
2. OVERVIEW OF JAVA
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
3
o Java Programs run inside virtual machine sandbox
• Class loader: Class loader in Java is a part of the Java Runtime Environment(JRE) which is used to
dynamically load Java classes into the Java Virtual Machine. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
These security are provided by java language. Some security can also be provided by application
developerthrough SSL, JAAS, Cryptography etc.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing java applications. It is used to provide
runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries + other
files that JVM uses at runtime. Implementation of JVMs are also actively released by other companies
besides Sun Micro Systems.
4
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.
5
Provides runtime environmentJVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
1. What is Java? Explain the internal architecture of JVM with neat sketch?(13) (NOV/DEC 2019)
2. How Java changed the internet?(9) (APR/MAY 2021)
3. If semicolons are needed at the end of each statement, why does the comment line not end
with asemicolon ?(4) (APR/MAY 2021)
4. Outline the arithmetic operators in Java.(6) (NOV/DEC 2021)
5. Name the four integer types in Java and outline the bitwise operators that can be applied to
theinteger types.(7) (NOV/DEC 2021)
6. Outline the iteration statements in Java with syntax and example.(9) (NOV/DEC 2021)
7. What are the three categories of control statements used in Java ? Explain each category
withexample.(13) (APR/MAY 2021)
8. Write a java code using do-while loop that counts down to 1 from 10 printing exactly ten lines
of“Hello”(6) (APR/MAY 2019)
The main objective of Java programming language creation was to make it portable, simple and secure
programming language. Java is platform independent because it is different from other languages like C,
C++ etc. which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform
thatruns on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
6
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
1. Can a Java source file be saved using a name other than the class name?
Justify (2) (APR/MAY 2019)
2. Define Access Specifier(2) (Nov/Dec 2018)
3. What is Method?How method is defined? Give Example. (Nov/Dec 2018)
4. What is Java Doc?(2) (Nov/Dec 2019)
5. Explain in detail about Constructor with an example?(13)
A program is written in JAVA, the javac compiles it. The result of the JAVA compiler is the .class file
orthe bytecode and not the machine native code (unlike C compiler). The bytecode generated is a non-
executable code and needs an interpreter to execute on a machine. Thisinterpreter is the JVM and t us
7
the Bytecode is executed by the JVM. And finally program runs to give the desired output.
The term programming paradigm is used to specify an overall approach to writing program code.
The object-oriented programming paradigm (OOP) introduces a fundamentally different approach to
program design. All computer programs consist of two elements: code and data. Furthermore, a program
can be conceptually organized around its code or around its data. That is, some programs are written
around “what is happening” and others are written around “who is being affected.” These are the two
paradigms that govern how a program is constructed.
The first way is called the process- oriented model. This approach characterizes a program as a
series of linear steps (that is, code). The process-oriented model can be thought of as code acting on data.
Procedural languages such as C employ this model to considerable success. To manage increasing
complexity, the second approach, called object- oriented programming, was conceived. Object-oriented
programming organizes a program around its data (that is, objects) and a set of well-defined interfaces tothat
data. An object-oriented program can be characterized as data controlling access to code.
Object-oriented programming (OOP) is a programming paradigm based upon objects that aims to
incorporate the advantages of modularity and reusability. Objects, which are usually instances of classes, are
8
used to interact with one another to design applications and computer programs.
Object–Oriented Analysis (OOA) is the procedure of identifying software engineering requirements
and developing software specifications in terms of a software system’s object model, which comprises of
interacting objects.
Object–Oriented Design (OOD) involves implementation of the conceptual model produced during
object-oriented analysis. In OOD, concepts in the analysis model, which are technology−independent, are
mapped onto implementing classes, constraints are identified and interfaces are designed, resulting in a
model for the solution domain, i.e., a detailed description of how the system is to be built on concrete
technologies.
In POP, program is divided into small In OOP, program is divided into parts called
parts called functions objects.
In POP, Importance is not given to data but In OOP, Importance is given to the data
to rather
functions as well as sequence of actions to than procedures or functions because it works
be as
done. a real world.
POP follows Top-Down approach. OOP follows Bottom-Up approach.
POP does not have any access specifier. OOP has access specifiers named Public,
Private,
Protected, etc.
In POP, Data can move freely from function In OOP, objects can move and communicate
to with
function in the system. each other through member functions.
To add new data and function in POP is not OOP provides an easy way to add new data
so and
easy. function.
In POP, most function uses Global data for In OOP, data cann ot move easily from
sharing that can be accessed freely from functionto function, it can be kept public or
function private so we can control the access of data.
to function in the system.
POP does not have any proper way for OOP provides Data Hiding so provides
hiding more
data so it is less secure. security.
In POP, Overloading is not possible. In OOP, overloading is possible in the form
of
Function Overloading and Operator
Overloading.
Example of POP are: C, VB, FORTRAN, Example of OOP are: C++, JAVA, VB.NET,
Pascal. C#.NET.
9
The important features of Object Oriented programming are:
▪ Inheritance
▪ Polymorphism
▪ Data Hiding
▪ Encapsulation
▪ Overloading
▪ Reusability
It is important to know some new terminologies used in Object Oriented programming namely
▪ Objects
▪ Classes
Objects:
10
In other words, object is an instance of a class.
Classes:
These contain data and functions bundled together under a unit. In other words, class is a collection of
similar objects. When we define a class, it just creates template or Skelton. So, no memory is created when
class is created. Memory is occupied only by object.
Example:
Class classname
{
Data
Functions
};
main ( )
{
classname objectname1,objectname2,..;
}
Member functions:
The functions defined inside the class as above are called member functions.
Here the concept of Data Hiding figures
Example
// Define a class
class Dog {
// Attributes
String name;
int age;
// Method
void bark()
{
System.out.println(name + " is barking!");
}
}
11
// Main class
public class Main
{
public static void main(String[] args)
{
// Create an object
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // Output: Buddy is barking!
}
}
// Define a class
class Dog
{
This line defines a new class named Dog. In Java, a class is a blueprint for creating objects. The keyword class is
followed by the name of the class.
// Attributes
String name;
int age;
These lines declare two attributes (also called fields or instance variables) for the Dog class.
String name; declares a variable name of type String that will hold the dog's name.
int age; declares a variable age of type int that will hold the dog's age.
// Method
void bark()
{
System.out.println(name + " is barking!");
}
This is a method named bark in the Dog class. A method defines a behavior for the objects created from this
class.
void indicates that this method does not return any value.
Inside the method, System.out.println(name + " is barking!"); is a statement that prints the dog's name followed
by the text " is barking!" to the console. The name variable is concatenated with the string " is barking!".
// Main class
public class Main
{
This line defines another class named Main. This class contains the main method, which is the entry point for the
program.
String[] args is an array of String objects that can store command-line arguments.
// Create an object
Dog myDog = new Dog();
This line creates an object of the Dog class.
Dog myDog; declares a variable myDog of type Dog.
new Dog(); creates a new instance of the Dog class and assigns it to myDog.
myDog.name = "Buddy";
myDog.age = 3;
These lines set the attributes of the myDog object.
myDog.name = "Buddy"; assigns the string "Buddy" to the name attribute of the myDog object.
myDog.age = 3; assigns the integer 3 to the age attribute of the myDog object.
}
}
These closing braces } close the main method and the Main class, respectively.
Methods: Functions defined inside a class that describe the behaviors of the objects.
class Cat {
// Attributes
String name;
int age;
13
// Method
void meow() {
System.out.println(name + " says Meow!");
}
}
Simple Algorithm
Define a class named Cat with attributes name and age.
Define a method named meow in the Cat class that prints a message including the cat's name.
Define a Main class containing the main method.
In the main method:
Create an instance of the Cat class.
Assign values to the name and age attributes of the cat instance.
Call the meow method on the cat instance to print the message.
Line-by-Line Explanation
class Cat
{
This line defines a new class named Cat. In Java, a class is a blueprint for creating objects. The keyword class is
followed by the name of the class.
// Attributes
String name;
int age;
These lines declare two attributes (also called fields or instance variables) for the Cat class.
String name; declares a variable name of type String that will hold the cat's name.
int age; declares a variable age of type int that will hold the cat's age.
// Method
void meow() {
System.out.println(name + " says Meow!");
}
This is a method named meow in the Cat class. A method defines a behavior for the objects created from this
class.
void indicates that this method does not return any value.
14
Inside the method, System.out.println(name + " says Meow!"); is a statement that prints the cat's name followed
by the text " says Meow!" to the console. The name variable is concatenated with the string " says Meow!".
}
This closing brace } marks the end of the Cat class definition.
Summary
Class Definition: class Cat and class Main
Attributes: String name and int age inside the Cat class
Method: void meow() inside the Cat class
Object Creation: Cat myCat = new Cat();
Setting Attributes: myCat.name = "Whiskers"; and myCat.age = 2;
Method Invocation: myCat.meow();
This program defines a Cat class with attributes name and age, and a method meow(). The Main class
contains the main method, which creates a Cat object, sets its attributes, and calls its meow method to display
the cat's name followed by "says Meow!" on the console.
15
Data Hiding:
This concept is the main heart of an Object oriented programming. The data is hidden inside the class
by declaring it as private inside the class. When data or functions are defined as private it can be accessed
only by the class in which it is defined. When data or functions are defined as public then it can be accessed
anywhere outside the class. Object Oriented programming gives importance to protecting data which in any
system. This is done by declaring data as private and making it accessible only to the class in which it is
defined. This concept is called data hiding. But one can keep member functions as public.
Example:
Class classname
{
private:
datatype data;
public:
Member functions
};
main ( )
{
classname objectname1,objectname2,..;
}
Encapsulation:
The technical term for combining data and functions together as a bundle is encapsulation.
Inheritance:
Inheritance as the name suggests is the concept of inheriting or deriving properties of an exiting class
to get new class or classes. In other words we may have common features or characteristics that may be
needed by number of classes. So those features can be placed in a common tree class called base class and the
other classes which have these charaterisics can take the tree class and define only the new things that they
have on their own in their classes. These classes are called derived class. The main advantage of using this
concept of inheritance in Object oriented programming is it helps in reducing the code size since the common
characteristic is placed separately called as base class and it is just referred in the derived class. This provide
the users the important usage of terminology called as reusability
Reusability:
This usage is achieved by the above explained terminology called as inheritance. Reusability is nothing
but re- usage of structure without changing the existing one but adding new features or characteristics to it. It
is very much needed for any programmers in different situations. Reusability gives the following advantages
16
to user. It helps in reducing the code size since classes can be just derived from existing one and one need to
add only the new features and it helps users to save their time.
For instance if there is a class defined to draw different graphical figures say there is a user who want
to draw graphical figure and also add the features of adding color to the graphical figure. In this scenario
instead of defining a class to draw a graphical figure and coloring it what the user can do is make use of the
existing class for drawing graphical figure by deriving the class and add new feature to the derived class
namely add the feature of adding colors to the graphical figure.
Thus the above given important features of object oriented programming among the numerous
features it have gives the following advantages to the programming world.
Abstraction: Hiding complex implementation details and showing only the essential features.
Encapsulation: Wrapping the data (attributes) and methods into a single unit or class. Access to the data is
restricted by using access modifiers.
Example
class Person {
// Private attributes
private String name;
private int age;
Inheritance
Inheritance: Mechanism where one class (subclass) inherits the attributes and methods of another class
(superclass).
Example
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
18
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
Polymorphism
Polymorphism: The ability to take many forms. It allows methods to do different things based on the object it is
acting upon, even though they share the same name.
Example
class Animal {
void sound() {
System.out.println("Some sound.");
}
}
19
class Dog extends Animal {
void sound() {
System.out.println("The dog barks.");
}
}
A Simple Class
class called Box thatdefines three instance variables: width, height, and depth.
class Box
{
20
double width;
double height;
double depth;
}
The new data type is called Box. This name is used to declare objects of type Box. The class
declarationonly creates a template. It does not create an actual object.
Example1:
/* 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);
}
}
Output:
Volume is 3000.0
Example2:
// This program declares two Box objects.
class Box {
double width;double height;double depth;
}
class BoxDemo2
{
21
public static void main(String args[])
{Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2'sinstance variables
*/
mybox2.width = 3;
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);
}
}
Output:
Volume is 3000.0
Volume is 162.0
Declaring Objects
First, declare a variable of the class type. This variable does not define an object.Instead, 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. This is
done using the 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. Thus,
in Java, all class objects must be dynamically allocated.
Syntax:
Box mybox = new Box();
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box. At this point, mybox does not
yet refer to an actual object. The next line allocates an object and assigns a reference to it to mybox.
After the second line executes, we can use mybox as if it were a Box object. But in reality, mybox
simply holds, in essence, the memory address of the actual Box object.
22
Assigning Object Reference
VariablesSyntax:
Box b1 = new Box();
Box b2 = b1;
b2 is being assigned a reference to a copy of the object referred to by b1. b1 and b2 will both refer to
the
same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the
objectthrough b2 will affect the object to which b1 is referring, since they are the same object.
CONSTRUCTORS
Constructors are special member functions whose task is to initialize the objects of its class.
It is a special member function; it has the same as the class name.
Java constructors are invoked when their objects are created. It is named such because, it
constructsthe value, that is provides data for the object and are used to initialize objects.
Every class has a constructor when we don't explicitly declare a constructor for any java
class thecompiler creates a default constructor for that class which does not have any
return type.
The constructor in Java cannot be abstract, static, final or synchronized and these modifiers
are notallowed for the constructor.
23
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
new Box( ) is calling the Box( ) constructor. When the constructor for a class is not explicitly defined ,
then Java creates a default constructor for the class. The default constructor automatically initializes
all instance variables to their default values, which are zero, null, and false, for numeric types,
24
reference types, and boolean, respectively.
Parameterized Constructors
A constructor which has a specific number of parameters is called parameterized constructor.
Parameterizedconstructor is used to provide different values to the distinct objects.
Example:
/* Here, Box uses a parameterized constructor toinitialize the dimensions of abox.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box
objectsBox mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second
boxvol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
Box mybox1 = new Box(10, 20, 15);
The values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object. Thus,
mybox1’scopy of width, height, and depth will contain the values 10, 20, and 15 respectively.
Overloading
ConstructorsExample:
/* Here, Box defines three constructors to initializethe dimensions of a box various ways.
*/
25
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
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons
{
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);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second
boxvol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
26
Volume of mycube is 343.0
METHODS
Syntax:
type name(parameter-list) {
// body of method
}
type specifies the type of data returned by the method. This can be any valid type, including
classtypes 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. Parameters
are essentially variables that receive the value of the arguments passed to the method when it
is called. Ifthe method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
Syntax:
return value;
Example:
// This program includes a method inside the box
class.class Box {
double width;
double height;
double depth;
// display volume of a box
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();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to
mybox2'sinstance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
27
Output:
olume is 3000.0
Volume is 162.0
The first line here invokes the volume( ) method on mybox1. That is, it calls volume( ) relative to the
mybox1 object, using the object’s name followed by the dot operator. Thus, the call to
mybox1.volume( ) displays the volume of the box defined by mybox1, and the call to
mybox2.volume( ) displays the volume of the box defined by mybox2. Each time volume( ) is
invoked, it displays the volume for the specified box.
Returning a
ValueExample:
// Now, volume() returns the volume of a box.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[])
{Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2'sinstance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000
Volume is 162
when volume( ) is called, it is put on the right side of an assignment statement. On the left is a
variable, inthis case vol, that will receive the value returned by volume( ).
28
Syntax:
vol = mybox1.volume();
executes, the value of mybox1.volume( ) is 3,000 and this value then is stored in vol.
29
This Keyword
this keyword is used to to refer to the object that invoked it. this can be used inside any method to
refer tothe current object. That is, this is always a reference to the object on which the method was
invoked. this() can be used to invoke current class constructor.
Syntax:
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
Example:
class Student
{
int id;
String name;
student(int id, String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student stud1 = new Student(01,"Tarun");
Student stud2 = new Student(02,"Barun");
stud1.display();
stud2.display();
}
}
Output:
01 Tarun
02 Barun
Overloading Methods
When two or more methods within the same class that have the same name, but their parameter
declarations are different. The methods are said to be overloaded, and the process is referred to as
method overloading. Method overloading is one of the ways that Java supports polymorphism.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
Example:
// Demonstrate method overloading.
30
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
When a method in a subclass has the same name and type signature as a method in its superclass,
then the method in the subclass is said to override the method in the superclass. When an
overridden method is called from within its subclass, it will always refer to the version of that
method defined by the subclass. The version of the method defined by the superclass will be hidden.
Example:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
31
i = a;
j = b;
}
// display i and j
void show() {
32
ACCESS SPECIFIERS
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class.There are 4 types of java access modifiers:
❖ private
❖ default
❖ protected
❖ public
1) Private Access Modifier
The private access modifier is accessible only within
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 compile
time error.
class A{
private int data=40;
private void msg()
{System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
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:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
If you make any class constructor private, you cannot create the instance of that class from outside
the class.For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
33
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
34
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:
Hello
Access Modifier Within Class Within Package Outside Package Outside Package
By Subclass Only
Private Y N N N
Default Y Y N N
Protecte Y Y Y N
d
Public Y Y Y Y
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
35
restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why there is compile time error.
STATIC MEMBERS
Static is a non-access modifier in Java which is applicable for the following:
❖ blocks
❖ variables
❖ methods
❖ nested classes
Static blocks
If you need to do computation in order to initialize your static variables, you can declare a static
block thatgets executed exactly once, when the class is first loaded.
Example:
// Java program to demonstrate use of static blocks
class Test
{
// static variable
static int a = 10;
static int b;
// static
blockstatic {
System.out.println("Static block initialized.");
b = a * 4;
}
}
}
Output:
Static block
initialized.from main
36
Value of a : 10
Value of b : 40
Static variables
When a variable is declared as static, then a single copy of variable is created and shared among all
objects at class level. Static variables are, essentially, global variables. All instances of the class share
the same static variable.
Important points for static variables :-
• We can create static variables at class-level only.
• static block and static variables are executed in order they are present in a program.
Example:
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
Output:
Static block
initialized.x = 42
a=3
b = 12
37
Static methods
When a method is declared with static keyword, it is known as static method.
When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object. The most common
example of a static method is main( ) method. Methods declared as static have
several restrictions:
▪ They can only directly call other static methods.
▪ They can only directly access static data.
▪ They cannot refer to this or super in any way.
Syntax:
classname.method( )
Example:
//Inside main( ), the static method callme( ) and the static variable b are accessed
through their classname
/
/
St
at
ic
D
e
m
o.
cl
a
ss
St
at
ic
D
e
m
o
{
static int a = 42;
static int b = 99;
static void
callme() {
System.out.prin
tln("a = " + a);
}
}
class StaticByName {
public static void
main(String args[]) {
StaticDemo.callme();
System.out.println("b = "
+ StaticDemo.b);
}
}
Output:
a = 42
b = 99
Finalize method
1. Define a Class: Create a class that will contain the finalize method.
2. Create a Constructor: Define a constructor for the class to initialize objects and optionally
print a message when an object is created.
3. Override the finalize Method: Override the finalize method from the Object class. Inside this
method, add the code to be executed just before the object is garbage collected.
4. Create an Object: In the main method, create an instance of the class.
5. Make the Object Eligible for Garbage Collection: Set the object reference to null to make it
eligible for garbage collection.
6. Request Garbage Collection: Call System.gc() to suggest that the JVM performs garbage
collection.
7. Wait for Garbage Collection: Optionally, add a small delay to give the garbage collector time
to run.
8. End the Program: Print a message indicating the end of the program.
Step-by-Step Example
java
Copy code
public class Car {
java
Copy code
// Constructor
public Car() {
System.out.println("Car is created");
}
java
Copy code
// The finalize method is called when the object is about to be garbage collected
@Override
protected void finalize() throws Throwable {
try {
System.out.println("Car is being destroyed");
} finally {
super.finalize(); // Ensure the superclass finalize method is called
}
}
java
Copy code
public static void main(String[] args) {
Car myCar = new Car(); // Create a Car object
java
Copy code
myCar = null; // Make the Car object eligible for garbage collection
java
Copy code
// Requesting garbage collection
System.gc();
java
Copy code
// Adding a small delay to ensure garbage collection happens
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
java
Copy code
System.out.println("End of main method");
}
}
Full Example
java
Copy code
public class Car {
// Constructor
public Car() {
System.out.println("Car is created");
}
// The finalize method is called when the object is about to be garbage collected
@Override
protected void finalize() throws Throwable {
try {
System.out.println("Car is being destroyed");
} finally {
super.finalize(); // Ensure the superclass finalize method is called
}
}
Summary
This step-by-step algorithm helps you understand how to use the finalize method in Java. By
following these steps, you can see how the finalize method works in conjunction with garbage
collection to perform cleanup tasks before an object is destroyed.
The finalize method in Java was traditionally used for cleanup activities before an object is garbage
collected. However, it has several drawbacks, such as unpredictability in its execution time,
performance issues, and potential risks of resource leaks if not handled properly. Because of these
issues, its use is generally discouraged in favor of more reliable and predictable resource management
techniques.
1. Resource Cleanup: finalize was used to release resources like file handles, sockets, and
database connections that are not automatically managed by the garbage collector.
2. Native Resources: Cleanup of native resources allocated in JNI (Java Native Interface) code.
3. Logging: Logging when an object is garbage collected for debugging or monitoring purposes.
4.
Why Avoid finalize
1. Unpredictability: You cannot predict when (or even if) the garbage collector will call finalize.
2. Performance: Objects with finalize methods take longer to be reclaimed by the garbage
collector, leading to memory pressure.
3. Complexity: Using finalize can introduce complex bugs and unintended behavior, especially if
exceptions occur within the finalize method.
Modern Alternatives
java
Copy code
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// Use the resource
} catch (IOException e) {
e.printStackTrace();
}
2. Explicit Cleanup Methods: Define an explicit method to release resources and ensure it is
called by the client code.
java
Copy code
public class Resource {
public void close() {
// Cleanup code
}
}
3. Phantom References and Cleaner API: For more advanced use cases, Java provides the
java.lang.ref.Cleaner API and phantom references for managing resource cleanup more
effectively.
java
Copy code
public class Resource {
private static final Cleaner cleaner = Cleaner.create();
private final Cleaner.Cleanable cleanable;
public Resource() {
this.cleanable = cleaner.register(this, new ResourceCleanup());
}
Conclusion
While the finalize method was historically used for cleanup purposes, its drawbacks and the
availability of better alternatives have led to it being deprecated and discouraged in modern Java
development. Using try-with-resources, explicit cleanup methods, or the Cleaner API are
recommended approaches for managing resource cleanup in a more reliable and predictable manner.
1. Write a Java program to compute the specified expressions and print the output.
Test Data:
((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5))
Expected Output
2.138888888888889
4. Write a Java program that takes three numbers as input to calculate and print the average of
the numbers.
23. Write a Java program to check whether Java is installed on your computer.
Expected Output
Java Version: 1.8.0_71
Java Runtime Version: 1.8.0_71-b15
Java Home: /opt/jdk/jdk1.8.0_71/jre
Java Vendor: Oracle Corporation
Java Vendor URL: http://Java.oracle.com/
Java Class Path: .
25. Write a Java program and compute the sum of the digits of an integer.
Input Data:
Input an integer: 25
Expected Output
The sum of the digits is: 7
28. Write a Java program to compute the distance between two points on the surface of earth.
Distance between the two points [ (x1,y1) & (x2,y2)]
d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2))
Radius of the earth r = 6371.01 Kilometers
Input Data:
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 35.5
Input the longitude of coordinate 2: 25.5
Expected Output
The distance between those points is: 1480.0848451069087 km