20CS6205C Fund. of JAVA Programming UNIT-I (1)
20CS6205C Fund. of JAVA Programming UNIT-I (1)
UNIT- I
1.1 Introduction
a. Software Crisis
To build today’s complex software it is just not enough to put together a sequence of
programming statements and sets of procedures and modules; we need to incorporate sound
construction techniques and program structures that are easy to comprehend implement and
modify.
With the advent of languages such as c, structured programming became very popular
and was the main technique of the 1980’s. Structured programming was a powerful tool that
enabled programmers to write moderately complex programs fairly easily. However, as the
programs grew larger, even the structured approach failed to show the desired result in terms of
bug-free, easy-to- maintain, and reusable programs.
concepts. It is a new way of organizing and developing programs and has nothing to do with any
particular language. However, not all languages are suitable to implement the OOP concepts
Dr. K. Praveen Kumar
easily.
ASSOC. PROFESSOR, CSE
b. Procedure-Oriented Programming
In the procedure oriented approach, the problem is viewed as the sequence of things to
be done such as reading, calculating and printing such as Cobol, Fortran and C. The primary
focus is on functions. A typical structure for procedural programming is shown in fig.1.2. The
technique of hierarchical decomposition has been used to specify the tasks to be completed for
solving a problem.
In a multi- function program, many important data items are placed as global so that they
may be accessed by all the functions. Each function may have its own local data. Global data are
more vulnerable to an inadvertent change by a function. In a large program it is very difficult to
identify what data is used by which function. In case we need to revise an external data structure,
we also need to revise all functions that access the data. This provides an opportunity for bugs to
creep in.
2
Page
Object Oriented Programming or OOP is the technique to create programs based on the
real world. Unlike procedural programming, here in the OOP programming model programs are
organized around objects and data rather than actions and logic.
OOP treats data as a critical element in the program development and does not allow it to
flow freely / openly around the system.
Divided Into In POP, program is divided into In OOP, program is divided into
small parts called functions. parts called objects.
Access Specifiers POP does not have any access OOP has access specifiers named
specifier. Public, Private, Protected, etc.
Data Moving In POP, Data can move freely In OOP, objects can move and
from function to function in the communicate with each other
system. through member functions.
Expansion To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.
Data Access In POP, Most function uses In OOP, data cannot move easily
Global data for sharing that can from function to function, it can be
be accessed freely from function kept public or private so we can
to function in the system. control the access of data.
Data Hiding POP does not have any proper OOP provides Data Hiding so
way for hiding data so it is less provides more security.
secure.
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
i. Objects: Objects are the basic run time entities/ real world entities in an object-
oriented system.An object represents an individual, identifiable item, unit, or entity, either real or
abstract, with a well-defined role in the problem domain. They may represent a person, a place,
a bank account, a table of data or any item that the program has to handle. They may also
represent user-defined data such as vectors, time and lists. Programming problem is analyzed in
term of objects and the nature of communication between them. Program objects should be
chosen such that they match closely with the real-world objects. Objects take up space in the
memory and have an associated address like a record in Pascal, or a structure in c.
When a program is executed, the objects interact by sending messages to one another. For
example, if “customer” and “account” are to object in a program, then the customer object may
send a message to the count object requesting for the bank balance. Each object contain data, and
code to manipulate data. Objects can interact without having to know details of each other’s data
or code. It is a sufficient to know the type of message accepted, and the type of response returned
by the objects. Although different author represents them differently fig 1.5 shows two notations
that are popularly used in object-oriented analysis and design.
OBJECT: STUDENT
DATA
Name
Date-of-birth
Marks
6
FUNCTIONS
Page
………
Fig. 1.5 representing an object
ii. Classes:- Class is the logical unit upon which the entire java language is built
because it defines the shape and nature of an object. “User defined Data type” , “Definition”
, “Blue print”, “Template” and “Prototype” that defines and describe about all objects that
are same kind. A class is nothing but a blueprint or a template for creating different objects
which defines its properties and behaviors. We just mentioned that objects contain data, and
code to manipulate that data. The entire set of data and code of an object can be made a user
-defined data type with the help of class. In fact, objects are variables of the type class. Once
a class has been defined, we can create any number of objects belonging to that class. Each
object is associated with the data of type class with which they are created. A class is thus a
collection of objects similar types. For examples, Mango, Apple and orange members of
class fruit. Classes are user-defined that types and behave like the built-in types of a
programming language. The syntax used to create an object is not different then the syntax
used to create an integer object in C. If fruit has been defines as a class, then the statement
Fruit Mango;
iii. Encapsulation:- The wrapping up of data and function into a single unit (called
class) is known as encapsulation. Data and encapsulation is the most striking feature of a
class. The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between the object’s
data and the program. This insulation of the data from direct access by the program is called
data hiding or information hiding.
The attributes are sometime called data members because they hold information.
The functions that operate on these data are sometimes called methods or member function.
iv. Inheritance:- Inheritance is the process by which objects of one class acquired
the properties of objects of another classes. It supports the concept of hierarchical
classification. For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a
part of the class ‘bird’. The principal behind this sort of division is that each derived class
7
shares common characteristics with the class from which it is derived as illustrated in fig 1.6.
Page
Fig. 1.7 illustrates that a single function name can be used to handle different number
and different types of argument. This is something similar to a particular word having several
different meanings depending upon the context. Using a single function name to perform
different type of task is known as function overloading.
8
Page
vii. Dynamic Binding: -Binding refers to the linking of a procedure call to the code
to be executed in response to the call. Dynamic binding means that the code associated with a
given procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance. A function call associated with a polymorphic reference depends
on the dynamic type of that reference.
Consider the procedure “draw” in fig. 1.7. by inheritance, every object will have this procedure.
Its algorithm is, however, unique to each object and so the draw procedure will be redefined in
each class that defines the object. At run-time, the code matching the object under current
reference will be called.
viii. Message Passing: -An object-oriented program consists of a set of objects that
communicate with each other. The process of programming in an object-oriented language,
involves the following basic steps:
A Message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving object that generates the desired results.
Message passing involves specifying the name of object, the name of the function (message)
and the information to be sent. Example:
Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.
OOP offers several benefits to both the program designer and the user. Object-
Orientation contributes to the solution of many problems associated with the development and
quality of software products. The new technology promises greater programmer productivity,
better quality of software and lesser maintenance cost. The principal advantages:
• Through inheritance, we can eliminate redundant code extend the use of existing
• Classes.
• We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that
cannot be invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any
interference.
• It is possible to map object in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
10
• The data-centered design approach enables us to capture more detail of a model can
Page
implemental form.
OOP has become one of the programming buzzwords today. There appears to be a great
deal of excitement and interest among software engineers in using OOP. Applications of OOP
are beginning to gain importance in many areas. The most popular application of object-oriented
programming, up to now, has been in the area of user interface design such as window. Hundreds
of windowing systems have been developed, using the OOP techniques.
Real-business system is often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it can
simplify a complex problem. The promising areas of application of OOP include:
• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expert text
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
The object-oriented paradigm sprang from the language, has matured into design, and has
recently moved into analysis. It is believed that the richness of OOP environment will enable the
software industry to improve not only the quality of software system but also its productivity.
Object-oriented technology is certainly going to change the way the software engineers think,
analyze, design and implement future system.
11
Page
UNIT- I
Java is an object oriented programming language used to develop web based applications
for internet and intranet systems. Java is a computer programming language created by Sun
Microsystems. Java is used mainly on the Internet and uses a virtual machine which has been
implemented in most browsers to translate Java into a specific application on different computer
system. With most programming languages, you either compile or interpret a program so that
you can run it on your computer. The Java programming language is unusual in that a program is
both compiled and interpreted. The most common Java programs are applications and applets.
Applications are standalone programs, such as the HotJava browser. Applets are similar to
applications, but they don't run standalone. Instead, applets adhere to a set of conventions that
lets them run within a Java-compatible browser.
Java was originally developed by James Gosling at Sun Microsystems (which has
since merged into Oracle Corporation) and released in 1995 as a core component
of Sun Microsystems' Java platform. The language derives much of its syntax
from C and C++, but it has fewer low-level facilities than either of them.
To date, the Java platform has attracted more than 9 million software developers. It's used
in every major industry segment and has a presence in a wide range of devices, computers, and
networks.
Java technology's versatility, efficiency, platform portability, and security make it the
ideal technology for network computing. From laptops to datacenters, game consoles to scientific
supercomputers, cell phones to the Internet, Java is everywhere!
Java powers set-top boxes, printers, Web cams, games, car navigation systems,
Page
Java has been tested, refined, extended, and proven by a dedicated community. More than
9 million Java developers make it the largest and most active development community on the
planet. With its versatility, efficiency, and portability, Java has become invaluable to developers
by enabling them to:
Write software on one platform and run it on virtually any other platform
Create programs that can run within a web browser and access available web services
Develop server-side applications for online forums, stores, polls, HTML forms
processing, and more
Combine applications or services using the Java language to create highly customized
applications or services
Write powerful and efficient applications for mobile phones, remote processors, low-cost
consumer products, and practically any other device with a digital heartbeat
Java Programming Language was conceived by the effort of 5 great people, James
Gosling, Patrick Naughton, Chris Warth, Mike Sheridan and Ed Frank. They all worked for Sun
Microsystems, Inc and came up with Java in 1991. The language took 18 months to develop and
had a initial name as "Oak" which was renamed to Java in 1995, due to copyright issues.
The idea was to develop a language which was platform-independent and which could create
embedded software’s for consumer electronic devices. C and C++ were quite inefficient for the
purpose because they were not platform-independent as there programs have to be compiled for
particular hardware before execution. Also, the compiled code was inefficient for other
processors and it had to be recompiled. So the team of 5 also called as Green Team began to
work in developing an easier and cost-efficient solution. They worked for 18 months in
developing a portable, platform-independent language that could create a code which can run on
variety of processors under differing environments.
The above necessity led to creation of Java. At the same time, Internet and WWW were
becoming popular day-by-day. The web programs lacked the features of platform-independence.
It required programs that could run on any operating system irrespective of hardware and
software configuration. It required small and portable programs that could be securely
transported over the network. The programming language available to suit such requirements
was Java. Many developers soon realized that architectural neutral language like Java would be
best for writing programs for internet. Thus focus of Java was shifted from consumer electronics
to World Wide Web.
13
Page
Java is a well-known technology which allows you for software designed and
written only once for an” virtual machine" to run on a different computer, supports various
Operating System like Windows PCs, Macintoshes, and Unix computers. On the web aspect,
Java is popular on web servers, used by many of the largest interactive websites. Java is used to
create standalone applications which may run on a single computer or in distributed network. It
is also be used to create a small application program based on applet, which is further used for
Web page. Applets make easy and possible to interact with the Web page.
JDK Tools: The JDK tools provide compiling, Interpreter, running, monitoring,
debugging, and documenting your applications. The main tools used are
the Javac compiler, the javalauncher, and the javadoc documentation tool.
Application Programming Interface (API): The API provides the core functionality of
the Java programming language. It gives a wide collection of useful classes, which is
further used in your own applications. It provides basic objects and interface to
networking and security, to XML generation and database access, and much more.
14
Page
checks initially weather users are always up to date with the latest version of your
software. If an update is available for it, the Java Web Start software will automatically
Page
The Java Virtual Machine is the root for the Java platform and is integrated into various
hardware-based platforms.
The API is a vast collection of various software components that provide you much useful
functionality to the application. It is grouped into logical collection of related classes and
interfaces; these logical collections are known as packages.
Fig:The API and Java Virtual Machine insulate the program from hardware.
Java work on platform-independent environment, the Java platform is bit slower than native
code. However, new changes in compiler and virtual machine brings performance close to that
of native code without posing any threatening to portability security.
All source code is written in text files (Notepad Editor) save with the .java extension in the Java
programming language.
The source files are compiled into .class files by the java compiler. A .class file contains byte
codes? the machine language of the Java Virtual Machine (JVM). The java launcher tool runs
16
JVM works on different Operating System. The .class files(byte code) capable of running on
various Operating System. There are some virtual machines, such as the Java Hotspots virtual
machine that boost up your application performance at runtime. This includes various tasks such
as Efficiency of Programme and recompiling (to native code) which is frequently used sections
of
Code.
b) JDK, JRE
Writing Java applets and applications needs development tools like JDK. The JDK includes the
Java Runtime Environment, the Java compiler and the Java APIs. It's easy for both new and
experienced programmers to get started.
17
What is the difference between the JRE and the Java SE platform?
Page
JRE JDK
(Java Runtime environment) (Java Development Kit)
It is an implementation of the It is a bundle of software that you can use to develop
Java Virtual Machine* which Java based applications.
actually executes Java programs.
Java Runtime Environment is a Java Development Kit is needed for developing java
plug-in needed for running java applications.
programs.
The JRE is smaller than the JDK The JDK needs more Disk space as it contains the JRE
so it needs less Disk space. along with various development tools.
The JRE can be The JDK can be downloaded/supported freely from
downloaded/supported freely oracle.com/technetwork/java/javase/downloads/
from
java.com
It includes the JVM, Core It includes the JRE, set of API classes, Java compiler,
libraries and other additional Webstart and additional files needed to write Java
components to run applications applets and applications.
and applets written in Java.
There were five primary goals in the creation of the Java language:
5. It should be easy to use by selecting what was considered the good parts of other object-
oriented languages.
Page
Anything that is platform independent can run on any operating system and hardware. Java is
platform independent so java can run on any operating system and hardware.
This is because of the magic of Byte Code which is OS independent. When java compiler
compile any code then it generate the byte code not the machine native code (unlike C
compiler).Now this byte code need a interpreter to execute on a machine. This interpreter is
JVM. So JVM read that byte code (that is machine independent) and execute it. Different JVM is
designed for different OS and byte code is able to run on different OS. In case of C or
C++(language that are not platform independent) compiler generate the .exe file that is OS
dependent so when we run this .exe file on another OS it will not run because this file is OS
dependent so is not compatible with the another OS. Finally an intermediate OS independent
Byte code makes the java platform independent.
Typically, the compiled code is the exact set of instructions the CPU requires to "execute" the
program. In Java, the compiled code is an exact set of instructions for a "virtual CPU" which is
required to work the same on every physical machine.So, in a sense, the designers of the Java
language decided that the language and the compiled code was going to be platform independent,
but since the code eventually has to run on a physical platform, they opted to put all the platform
dependent code in the JVM.
This requirement for a JVM is in contrast to your Turbo C example. With Turbo C, the compiler
will produce platform dependent code, and there is no need for a JVM work-alike because the
compiled Turbo C program can be executed by the CPU directly.
With Java, the CPU executes the JVM, which is platform dependent. This running JVM then
19
executes the Java byte code which is platform independent, provided that you have a JVM
available for it to execute upon. You might say that writing Java code, you don't program for the
Page
The only way that all this Java byte code works on all Java virtual machines is that a rather strict
standard has been written for how Java virtual machines work. This means that no matter what
physical platform you are using, the part where the Java byte code interfaces with the JVM is
guaranteed to work only one way. Since all the JVMs work exactly the same, the same code
works exactly the same everywhere without recompiling. If you can't pass the tests to make sure
it's the same, you're not allowed to call your virtual machine a "Java virtual machine".
ii) Simple
Java is a simple Language because it contains many features of other Languages like c and C++
and Java Removes Complexity because it doesn’t use pointers, Storage Classes and Go to
Statements and java doesn’t support Multiple Inheritance. There are various features that make
the java as a simple language. Programs are easy to write and debug because java does not use
the pointers explicitly. It is much harder to write the java programs that can crash the system but
we cannot say about the other programming languages. Java provides the bug free system due to
the strong memory management. It also has the automatic memory allocation and deallocation
system.
To be an Object Oriented language, any language must follow at least the four characteristics.
Inheritance : It is the process of creating the new classes and using the behavior of the
existing classes by extending them just toreuse the existing code and adding the
additional features as needed.
Encapsulation: It is the mechanism of combining the information and providing the
abstraction.
Polymorphism: As the name suggest one name multiple form, Polymorphism is the way
of providing the different functionality by the functions having the same name based on
the signatures of the methods.
Dynamic binding: Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.
As the languages like Objective C, C++ fulfills the above four characteristics yet they are not
fully object oriented languages because they are structured as well as object oriented languages.
But in case of java, it is a fully Object Oriented language because object is at the outer most level
20
of data structure in java. No stand alone methods, constants, and variables are there in java.
Page
iv) Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any syntax errors and
interpreter checks any run time errors and makes the system secure from crash. All of the above
features make the java language robust.
v) Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can
call functions on these protocols and can get access the files from any remote machine on the
internet rather than writing codes on their local system.
vi) Portable
The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM. Java also has the standard data size irrespective of
operating system or the processor. These features make the java as a portable language.
vii) Dynamic
While executing the java program the user can get the required files dynamically from a local
drive or from a computer thousands of miles away from the user just by connecting with the
Internet.
viii) Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk. Java uses the public key encryption system to allow
the java applications to transmit over the internet in the secure encrypted form. The bytecode
Verifier checks the classes after loading.
ix) Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted the performance slow but the advance version of JVM uses
the adaptive and just in time compilation technique that improves the performance.
21
Page
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be
more delighted to know another feature of Java which is Multithreaded.Java is also a
multithreaded programming language. Multithreading means a single program having different
threads executing independently at the same time. Multiple threads execute instructions
according to the program code in a process or a program. Multithreading works the similar way
as multiple processes run on one computer.
Xi)Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as
Java, programs run directly from the source code. The interpreter program reads the source code
and translates it on the fly into computations. Thus, Java as an interpreted language depends on
an interpreter program.The versatility of being platform independent makes Java to outshine
from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this
any error occurring in the program gets traced. This is how it is different to work with Java.
The term architectural neutral seems to be weird, but yes Java is an architectural neutral language
as well. The growing popularity of networks makes developers think distributed. In the world of
network it is essential that the applications must be able to migrate easily to different computer
systems. Not only to computer systems but to a wide variety of hardware architecture and
operating system architectures as well. The Java compiler does this by generating byte code
instructions, to be easily interpreted on any machine and to be easily translated into native
machine code on the fly. The compiler generates an architecture-neutral object file format to
enable a Java application to execute anywhere on the network and then the compiled code is
executed on many processors, given the presence of the Java runtime system. Hence Java was
designed to support applications on network.
22
Page
C++ Java
Compatible with C source code, except for a No backward compatibility with any previous
few corner cases. language. The syntax is, however, strongly
influenced by C/C++. There are things such as
reserved keywords, such as xor and const that
don't do anything so that people who write on
C++ don't get confused.
Write once, compile anywhere (WOCA). Write once, run anywhere / everywhere (WORA
/ WORE).
Allows direct calls to native system libraries. Call through the Java Native Interface and
recently Java Native Access
Only provides object types and type names. Is reflective, allowing meta programming and
dynamic code generation at runtime.
Has multiple binary compatibility standards Has a binary compatibility standard, allowing
(commonly Microsoft and Itanium/GNU). runtime check of correctness of libraries.
Standardized minimum limits for all Standardized limits and sizes of all primitive
Pointers, references, and pass-by-value are Primitive and reference data types always passed
supported. by value.[1]
Supports classes, structs, and unions, and can Only supports classes, and allocates them on
allocate them on heap or stack. the heap. Java SE 6 optimizes with escape
analysis to allocate some objects on the stack.
Allows explicitly overriding types. Rigid type safety except for widening
conversions. Autoboxing/unboxing added in
Java 1.5.
The C++ Standard Library has a much more The standard library has grown with each
limited scope and functionality than the Java release. By version 1.6, the library included
standard library but includes language support for locales, logging, containers and
support, diagnostics, general utilities, strings, iterators, algorithms, GUI programming (but not
locales, containers, algorithms, iterators, using the system GUI), graphics, multi-
numerics, input/output, and Standard C threading, networking, platform security,
Library. The Boost library offers more introspection, dynamic class loading, blocking
functionality, including threads and network and non-blocking I/O. It provided interfaces or
I/O. Users must choose from a plethora of support classes for XML,XSLT, MIDI, database
(mostly mutually incompatible) third-party connectivity, naming services (e.g. LDAP),
libraries for GUI and other functionality. cryptography, security services (e.g. Kerberos),
print services, and web services. SWT offers an
abstraction for platform-specific GUIs.
24
Full Multiple inheritance, including virtual Only single inheritance is allowed. A class can
inheritance. implement multiple Interfaces, but can inherit
neither data members nor function bodies from
more than one ancestor.
Function pointers, function objects, and No function pointer mechanism. Instead, idioms
interfaces. such as Interface, Adapter, and Listener are
extensively used.
Const keyword for defining immutable final provides a version of const, equivalent
variables and member functions that do not to type* const pointers for objects and
change the object. plainconst for primitive types only.
No const member functions, nor any equivalent
to const type* pointers.
Supports the goto statement. It may Supports labels with loops and statement blocks.
cause Spaghetti Programming.
Source code can be written to be platform- Compiled into byte code for the JVM. Byte code
independent (can be compiled is dependent on the Java platform, but is
for Windows, BSD,Linux, Mac OS typically independent of operating
X, Solaris, etc., without modification) and system specific features.
written to take advantage of platform-specific
features. Typically compiled into native
machine code.
25
Page
UNIT- I
3.1.1
For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz
computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).
Java JDK 5
Java has advanced through the years in both functionality and reach. Current editions are on the
Java 2 Platform. The Java 2 Platform has various incarnations as well, including Java 2 Platform.
Java 2 Standard Edition (J2SE):J2SE is used primarily for writing applets and other Java-based
applications.
Java 2 Enterprise Edition (J2EE):J2EE is the Java architecture for developing multitier
enterprise applications. As part of J2EE, JSP pages have access to all J2EE components,
including JavaBeans and Enterprise JavaBeans components and Java servlets. JSP pages are
actually compiled into servlets, so they have all of the benefits of these flexible, server-side Java
applications.
26
Java 2 Micro Edition (J2ME): J2ME is a technology that allows programmers to use the java
programming language and related tools to develop programs for mobile wireless information
Page
Another important functionality made possible by J2SE is JavaBeans. These are reusable
applications that can be developed and assembled easily in order to create more sophisticated
applications. Basically, they are the building blocks of personalized J2SE applications.
import java.io.*;
public class Hello
{
public static void main (String[ ] args)
{
System.out.println("This is a literal print.");
System.out.print("Yea!");
System.out.println("Go Java!");
}
}
27
}
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
3.1.4 Creating Your First Application
Your first application, HelloWorldApp, will simply display the greeting "Hello world!". To
create this program, you will:
A source file contains code, written in the Java programming language, that you and
other programmers can understand. You can use any text editor to create and edit source
files.
The Java programming language compiler (javac) takes your source file and translates its
text into instructions that the Java virtual machine can understand. The instructions
contained within this file are known as bytecodes.
The Java application launcher tool (java) uses the Java virtual machine to run your
application.
You can save the file HelloWorldApp.java on your computer and avoid a lot of typing.
Then, you can go straight to Compile the Source File into a .class File.
Or, you can use the following (longer) instructions.
First, start your editor. You can launch the Notepad editor from the Start menu by
selecting Programs > Accessories > Notepad. In a new document, type in the following code:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
29
Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose
the File > Save As menu item. Then, in the Save As dialog box:
1. Using the Save in combo box, specify the folder (directory) where you'll save your file.
In this example, the directory is java on the C drive.
2. In the File name text field, type "HelloWorldApp.java", including the quotation marks.
3. From the Save as type combo box, choose Text Documents (*.txt).
4. In the Encoding combo box, leave the encoding as ANSI.
Programming in Java into three steps:
1. Create the program by typing it into a text editor and saving it to a file named,
say, HelloWorldApp.java.
2. Compile it by typing "javac HelloWorldApp.java" in the terminal window.
3. Run (or execute) it by typing "java HelloWorldApp" in the terminal window.
Class Declaration: Class is the building block in Java, each and every methods & variable exists
within the class or object. (Instance of program is called object). The public word specifies the
accessibility of the class. The visibility of the class or function can be public, private, etc. The
following code declares a new class "HelloWorld" with the public accessibility:
The main Method: The main method is the entry point in the Java program and java program
can't run without main method. JVM calls the main method of the class. This method is always
first thing that is executed in a java program. Here is the main method:
......
.....
}
30
Page
prints the "Hello World" on the console. The above line calls the println method
of System.out class.
The keyword static: The keyword static indicates that the method is a class method, which can
be called without the requirement to instantiate an object of the class. This is used by the Java
interpreter to launch the program by invoking the main method of the class identified in the
command to start the program.
The public static void main function is important function in Java programming language
The main method is the first method, which the Java Virtual Machine executes. When
you execute a class with the Java interpreter, the runtime system starts by calling the
class's main() method. The main() method then calls all the other methods required to run your
application. It can be said that the main method is the entry point in the Java program and java
program can't run without this method.
The method signature for the main() method contains three modifiers:
public indicates that the main() method can be called by any object.
static indicates that the main() method is a class method.
31
Page
Java Program
Structure:
All Java components require names. Names used for classes, variables, and methods are
called identifiers. In Java, there are several points to remember about identifiers. They are as
follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).After the first character, identifiers can have any combination of characters.A key
word cannot be used as an identifier.Most importantly, identifiers are case sensitive.
3.2 Keywords
Page
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different datatypes to
variables, you can store integers, decimals, or characters in these variables.
Primitive Datatypes
There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the
language and named by a keyword. Let us now look into the eight primitive data types in detail.
33
byte:
Page
This datatype is generally used as the default data type for decimal values, generally the
default choice
Double datatype should never be used for precise values such as currency
34
char:
char datatype is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char datatype is used to store any character
Example: char letterA ='A'
Reference Datatypes
Reference variables are created using defined constructors of the classes. They are used
to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
A reference variable can be used to refer any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Java Literals
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well.
3.4 Variables
35
A variable provides us with named storage that our programs can manipulate. Each
Page
variable in Java has a specific type, which determines the size and layout of the variable's
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
memory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form of a
variable declaration:
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
This topic will explain various variable types available in Java Language. There are three
kinds of variables in Java:
1. Local variables
2. Instance variables
3. Class/Static variables
Local Variables
Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
37
Page
However, within static methods (when instance variables are given accessibility), they should
be called using the fully qualified name
ObjectReference.VariableName.
Example
import java.io.*;
public class Employee
{
//this instance variable is visible for any child class.
public String name;
//salary variable is visible in Employee class only.
private double salary;
//The name variable is assigned in the constructor.
// The salary variable is assigned a value.
public void setSalary(double empSal)
{
salary = empSal;
}
}
Page
name : Ransika
Class/static Variables
Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program
stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned
during the declaration or within the constructor. Additionally, values can be assigned
in special static initializer blocks.
ClassName.VariableName.
When declaring class variables as public static final, then variable names (constants) are
all in upper case. If the static variables are not public and final, the naming syntax is the same
as instance and local variables.
39
Page
import java.io.*;
public class Employee{
//DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
}
}
Note: If the variables are accessed from an outside class, the constant should be accessedas
Employee.DEPARTMENT
Java provides a number of access modifiers to set access levels for classes, variables, methods,
and constructors. The four access levels are:
Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc.
A variable or method declared without any access control modifier is available to any
40
other class in the same package. The fields in an interface are implicitly public static final and
Page
Variables and methods can be declared without any modifiers, as in the following examples:
booleanprocessOrder()
{
return true;
}
Methods, variables, and constructors that are declared private can only be accessed within
the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed outside the class, if public getter methods are
present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from
the outside world.
Example
}
public void setFormat(String format) {
this.format = format;
}
41
}
Page
So, to make this variable available to the outside world, we defined two public methods:
getFormat(), which returns the value of format, and setFormat(String), which sets its value.
A class, method, constructor, interface, etc. declared public can be accessed from any
other class. Therefore, fields, methods, blocks declared inside a public class can be accessed
from any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the
public class still needs to be imported. Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
Example
The main() method of an application has to be public. Otherwise, it could not be called by a Java
interpreter (such as java) to run the class.
Variables, methods, and constructors, which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the protected
members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields
can be declared protected, however methods and fields in a interface cannot be declared
protected.
Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.
42
Page
The following parent class uses protected access control, to allow its child class override
openSpeaker() method:
class AudioPlayer {
protected booleanopenSpeaker(Speaker sp) { //
implementation details
}
}
class StreamingAudioPlayer {
booleanopenSpeaker(Speaker sp) { //
implementation details
Here, if we define openSpeaker() method as private, then it would not be accessible from any
other class other than AudioPlayer. If we define it as public, then it would become accessible to
all the outside world. But our intention is to expose this method to its subclass only, that’s why
we have used protected modifier.
Java is much stronger than C++ in the type conversions that are allowed. In this topic we
will discuss conversions among different primitive types i.e. char, byte, short, int, long, float, and
double.
Booleans cannot be converted to other types. For the other primitive types (char, byte,
short, int, long, float, and double), there are two kinds of conversion: implicit and explicit.
Implicit conversions:
An implicit conversion means that a value of one type is changed to a value of another type
without any special directive from the programmer. A char can be implicitly converted to an int,
a long, a float, or a double. For example, the following will compile without error:
char c = 'a';
int k = c;
43
long x = c;
Page
float y = c;
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
double d = c;
For the other (numeric) primitive types, the basic rule is that implicit conversions can be done
from one type to another if the range of values of the first type is a subset of the range of values
of the second type. For example, a byte can be converted to a short, int, long or float; a short can
be converted to an int, long, float, or double, etc.
Explicit conversions:
Explicit conversions are done via casting. The name of the type to which you want a value
converted is given, in parentheses, in front of the value. For example, the following code casts a
value of type double to a value of type int, and a value of type double to a value of type short:
double d = 5.6;
int k = (int)d;
short s = (short)(d * 2.0);
Casting can be used to convert among any of the primitive types except boolean. Please note that
casting can lose information; for example, floating-point values are truncated when they are cast
to integers (e.g. the value of k in the code fragment given above is 5).
3.5 Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and...,
numbers[99] to represent individual variables.
This topic introduces how to declare array variables, create arrays, and process arrays
using indexed variables.
44
Page
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
or
Example
The following code snippets are examples of this syntax:
or
Creating Arrays
You can create an array by using the new operator with the following syntax:
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
45
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.
Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.
47
Example
Page
The following code displays all the elements in the array myList:
1.9
2.9
3.4
3.5
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array:
}
}
You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2:
A method may also return an array. For example, the following method returns an array that is
the reversal of another array:
}
return result;
}
Class is the logical unit upon which the entire java language is built because it defines the
shape and nature of an object. “User defined Data type”, “Definition”, “Blue print”, “Template”
and “Prototype” that defines and describe about all objects that are same kind.
Classes create objects and objects use methods to communicate between them. They
provide a convenient method for packaging a group of logically related data items and functions
that work on them. Class essentially serves as a template for an object and behaves like a basic
data type “int”.
In the real world, you'll often find many individual objects all of the same kind. There
may be thousands of other bicycles in existence, all of the same make and model. Each bicycle
was built from the same set of blueprints and therefore contains the same components. In object-
oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.
A class is the blueprint from which individual objects are created.
Java class is nothing but a template for object you are going to create or it’s a blue print
49
by using this we create an object. In simple word we can say it’s a specification or a pattern
Page
which we define and every object we define will follow that pattern.
• When we create class in java the first step is keyword class and then name of the class or
identifier we can say.
• Next is class body which starts with curly braces {} and between this all things related
with that class means their property and method will come here.
When we create a class its totally incomplete without defining any member of this class same
like we can understand one family is incomplete if they have no members.
Field:
Field is nothing but the property of the class or object which we are going to create .for example
if we are creating a class called computer then they have property like model, mem_size,
hd_size, os_type etc.
Method :
Method is nothing but the operation that an object can perform it define the behavior of object
how an object can interact with outside world .startMethod (), shutdownMethod(). Access Level
of members: Access level is nothing but where we can use that members of the class.
Each field and method has an access level:
Syntax:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
50
Page
type methodname1(parameter-list) {
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, it is the methods that determine how a class’ data
can be used.
As stated earlier, each object has its own copies of the instance variables. This means
that if you have two Box objects, each has its own copy of depth, width, and height. It is
important to understand that changes to the instance variables of one object have no effect on
the instance variables of another.
Example :
class Box
{
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[])
{
51
double vol;
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance 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);
}
}
You should call the file that contains this program BoxDemo.java, because the main( ) method is
in the class called BoxDemo, not the class called Box. When you compile this program, you will
find that two .class files have been created, one for Box and one for BoxDemo. The Java
compiler automatically puts each class into its own .class file. It is not necessary for both the Box
and the BoxDemo class to actually be in the same source file. You could put each class in its
own file, called Box.java and BoxDemo.java, respectively. To run this program, you must
execute BoxDemo.class. When you do, you will see the following output: Volume is 3000.0
Objects are the basic run time entity or in other words object is an instance of a class. An
object is a software bundle of variables and related methods of the special class. In real-world
objects share two characteristics: They have all state and behavior. For example, The squares
have state such as : sides and behaviors such as its areas and perimeters. Rectangles have state
such as: length, breadth and behavior such as its areas and perimeters. A object implements its
behavior with methods of it's classes. A method is a function (subroutine) associated with an
object.
i) Creating Objects
52
As you know, a class provides the blueprint for objects; you create an object from a class. Each
of the following statements taken from the BoxDemo program creates an object and assigns it to
Page
a variable:
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
Box mybox1= new Box( );
1. Declaration: The code set in bold are all variable declarations that associate a variable
name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which initializes
the new object.
type name;
This notifies the compiler that you will use name to refer to data whose type is type. With
a primitive variable, this declaration also reserves the proper amount of memory for the variable.
You can also declare a reference variable on its own line. For example:
Box mybox1;
If you declare myBox1 like this, its value will be undetermined until an object is actually
created and assigned to it. Simply declaring a reference variable does not create an object. For
that, you need to use the new operator, as described in the next section. You must assign an
object to myBox1 before you use it in your code. Otherwise, you will get a compiler error.
A variable in this state, which currently references no object, can be illustrated as follows (the
variable name, myBox1, plus a reference pointing to nothing):
The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you
create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
53
Page
The new operator returns a reference to the object it created. This reference is usually
assigned to a variable of the appropriate type, like:
The reference returned by the new operator does not have to be assigned to a variable. It
can also be used directly in an expression. For example:
class Box
{
double width;
double height;
double depth;
// Constructor call
public Box( )
{
width=0.0;
height=0.0;
depth=0.0;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The constructor in the Box class
initializes default values to instance variables.
The only required elements of a method declaration are the method's return type, name, a
pair of parentheses, (), and a body between braces, {}.
• Modifiers—such as public, private, and others you will learn about later.
• The return type—the data type of the value returned by the method, or void if the method
does not return a value.
• The method name—the rules for field names apply to method names as well, but the
convention is a little different.
• The parameter list in parenthesis—a comma-delimited list of input parameters, preceded
by their data types, enclosed by parentheses, (). If there are no parameters, you must use
empty parentheses.
• An exception list—to be discussed later.
• The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
Modifiers return types, and parameters will be discussed later in this lesson. Exceptions
are discussed in a later lesson.
Naming a Method
Although a method name can be any legal identifier, code conventions restrict
method names. By convention, method names should be a verb in lowercase or a multi-word
name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word
names, the first letter of each of the second and following words should be capitalized. Here are
some examples:
55
run
Page
runFast
Typically, a method has a unique name within its class. However, a method might
have the same name as other methods due to method overloading.
Once you've created an object, you probably want to use it for something. You may need to use
the value of one of its fields, change one of its fields, or call one of its methods to perform an
action.
Object fields are accessed by their name. You must use a name that is unambiguous.
You may use a simple name for a field within its own class. For example, we can add a
statement within the Box class that prints the width and height:
Code that is outside the object's class must use an object reference or expression,
followed by the dot (.) operator, followed by a simple field name, as in:
objectReference.fieldName
For example
class Box
{
56
double width;
double height;
Page
double depth;
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
Box()
{
width=0.0;
height=0.0;
depth=0.0;
}
double volume()
{
return width*height*depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
The code in the BoxDemo class is outside the code for the Box class. So to refer to
Page
the depth , width , and height fields within the Box object named myBox1,
Dr. K. Praveen Kumar
ASSOC. PROFESSOR, CSE
the BoxDemo class must use the names myBox1.depth, myBox1.width,
and myBox1.height, respectively. The program uses two of these names to display
the width and the height of myBox1
Attempting to use the simple names width and height from the code in
the BoxDemo class doesn't make sense — those fields exist only within an object — and results
in a compiler error.
Later, the program uses similar code to display information about myBox2. Objects of
the same type have their own copy of the same instance fields. Thus, each Rectangle object has
fields named depth, width, and height. When you access an instance field through an object
reference, you reference that particular object's field. The two objects myBox1 and myBox2 in
the BoxDemo program have different depth, width, and height fields.
To access a field, you can use a named reference to an object, as in the previous
examples, or you can use any expression that returns an object reference. Recall that the new
operator returns a reference to an object. So you could use the value returned from new to access
a new object's fields:
This statement creates a new Box object and immediately gets its height. In essence, the
statement calculates the default height of a Box. Note that after this statement has been executed,
the program no longer has a reference to the created Box, because the program never stored the
reference anywhere. The object is unreferenced, and its resources are free to be recycled by the
Java Virtual Machine.
You also use an object reference to invoke an object's method. You append the method's
simple name to the object reference, with an intervening dot operator (.). Also, you provide,
within enclosing parentheses, any arguments to the method. If the method does not require any
arguments, use empty parentheses.
objectReference.methodName(argumentList);
or:
objectReference.methodName();
58
The Box class has a method: volume() to compute the Box's volume. Here's
the BoxDemo code that invokes a method volume() :
Page
As with instance fields, objectReference must be a reference to an object. You can use a variable
name, but you also can use any expression that returns an object reference.
The new operator returns an object reference, so you can use the value returned from new
to invoke a new object's methods:
Some object-oriented languages require that you keep track of all the objects you create
and that you explicitly destroy them when they are no longer needed. Managing memory
explicitly is tedious and error-prone. The Java platform allows you to create as many objects as
you want (limited, of course, by what your system can handle), and you don't have to worry
about destroying them. The Java runtime environment deletes objects when it determines that
they are no longer being used. This process is called garbage collection.
An object is eligible for garbage collection when there are no more references to that
object. References that are held in a variable are usually dropped when the variable goes out of
scope. Or, you can explicitly drop an object reference by setting the variable to the special
value null. Remember that a program can have multiple references to the same object; all
references to an object must be dropped before the object is eligible for garbage collection.
The Java runtime environment has a garbage collector that periodically frees the memory
used by objects that are no longer referenced. The garbage collector does its job automatically
when it determines that the time is right.
Example:
Page
This example explains how to access instance variables and methods of a class:
int puppyAge;
If we compile and run the above program then it would produce following result:
4.6 Constructors
Constructor is a special type of method that is used to initialize the state of an object. Constructor
is invoked at the time of object creation. It constructs the values i.e. data for the object that is
why it is known as constructor.
60
Page
Constructor is just like the instance method but it does not have any explicit return type.
Constructors may include parameters of various types. When the constructor is invoked
using the new operator, the types must match those that are specified in the constructor
definition.
Java provides a default constructor which takes no arguments and performs no special
actions or initializations, when no explicit constructors are provided.
Every class has a constructor. If we do not explicitly write a constructor for a class the
java compiler builds a default constructor for that class.
Each time a new object is created at least one constructor will be invoked. The main rule
of constructors is that they should have the same name as the class. A class can have more than
one constructor.
1. Constructors can use any access modifier, including private. (A private constructor means
only code within the class itself cans instantiate an object of that type, so if
the private constructor class wants to allow an instance of the class to be used, the class
must provide a static method or variable that allows access to an instance created from
within the class.)
61
1) Default Constructor
<class_name>()
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
class Box{
Box(){
System.out.println("Box is created");
}
63
class Box {
double width;
double height;
double depth;
void volume() {
System.out.print("volume is");
System.out.println(width * height * depth);
}
}
class Boxdemo
{
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.volume();
mybox2.volume();
}
}
Output:
0.0
0.0
Explanation:In the above class,you are not creating any constructor so compiler provides you
a default constructor. Here 0 and null values are provided by default constructor.
64
Page
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
class Box {
double width;
double height;
double depth;
double vol;
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
In addition to overloading normal methods, you can also overload constructor methods.
In fact, for most real-world classes that you create, overloaded constructors will be the norm,
not the exception. To understand why, we can take example for this below program.
class Box {
double width;
double height;
double depth;
Box ( double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
As you can see, the Box() constructor requires three parameters. This means that all
declarations of Box objects must pass three arguments to the Box() constructor. For example,
the following statement is currently invalid:
Box ob = new Box();
Since Box() requires three arguments, it’s an error to call it without them. This raises
some important questions. What if you simply wanted a box and did not care ( or know) what
its initial dimensions were? Or, what if you want to be able to initialize a cube by specifying
only one value that would be used for all three dimensions? As the Box class is currently
written, these other options are not available to you.
Fortunately, the solution to these problems is quite easy: simply overload
the Box constructor so that it handles the situations just described. Here is a program that
contains an improved version of Box that does just that:
class Box{
double width;
66
double height;
double depth;
Page
Copy Constructors’
Copying the values of one object to another like copy constructor in C++
There are many ways to copy the values of one object into another.
They are:
• By constructor
67
class Box {
double width;
double height;
double depth;
class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(mybox1);
double vol;
There can be a lot of usage of this keyword. In java, this is a reference variable that refers
to the current object.
Within an instance method or a constructor, this is a reference to the current object — the object
whose method or constructor is being called. You can refer to any member of the current object
from within an instance method or a constructor by using this.
The most common reason for using the keyword is because a field is shadowed by a method or
constructor parameter.
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
69
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the constructor shadows one of the object's fields — inside the constructor x is
a local copy of the constructor's first argument. To refer to the Point field x, the constructor must
use this.x.
From within a constructor, you can also use the this keyword to call another constructor in the
same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class,
with a different implementation from the one in the Objects section.
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's
member variables. The constructors provide a default value for any member variable whose
initial value is not provided by an argument. For example, the no-argument constructor calls the
four-argument constructor with four 0 values and the two-argument constructor calls the four-
70
argument constructor with two 0 values. As before, the compiler determines which constructor to
call, based on the number and the type of arguments. If present, the invocation of another
Page