Java Unit1
Java Unit1
Thinking
1
1 Object-Oriented Thinking
When computers were first invented, programming was done manually by toggling in a binary machine
instructions by use of front panel. As programs began to grow, high level languages were introduced
that gives the programmer more tools to handle complexity. The first widespread high level language is
FORTRAN. Which gave birth to structured programming in 1960’s. The Main problem with the high
level language was they have no specific structure and programs becomes larger, the problem of
complexity also increases. So C became the popular structured oriented language to solve all the above
problems.
However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new
way of programming was invented and it was Object Oriented Programming. Object Oriented
Programming is a programming methodology that helps to organize complex programs through the use
of inheritance, encapsulation & polymorphism. Object Oriented Programming is a Revolutionary idea
totally unlike anything that has came before in programming Object Oriented Programming is an
evolutionary step following naturally on the heels of earlier programming abstractions.
At the risk of belaboring a point, let me emphasize that the mechanism I used to solve my
problem was to find an appropriate agent (namely, Flora) and to pass to her a message containing my
request. It is the responsibility of Flora to satisfy my request. There is some method or some algorithm
or set of operations used by Flora to do this. I do not need to know the particular method that Flora will
use to satisfy my request; indeed, often I do not want to know the details. This information is usually
hidden from my inspection.
If I investigated however, I might discover that Flora delivers a slightly diferent message to another
againt in my friend's city. That agent , in turn, perhaps has a subordinate who makes the flflflowers
arrangement. The agent then passes the flowers , along with yet another message, to a delivery person,
and so on. Earlier, the agent in Sally's city had obtained her flowers from a flower wholesaler who, in
turn, had interactions with the flowers growers, each of whom had to manage a team of gardeners.
So, our first observation of object-oriented problem solving is that the solution to my problem
required the help of many other individuals (Figure 1.1). Without their help, my problem could not be
easily solved. We phrase this in a general fashion as the following:
An object oriented program is structured as a community of interacting agents, called objects. Each
object has a role to play. Each object provides a service, or performs an action, that is used by other
members of the community.
3
1.1.2 Messages and Methods
The chain reaction that ultimately resulted in the solution to my program began with my request to
Flora. This request lead to other requests, which lead to still more requests, until my flowers
ultimately reached my friend. We see, therefore, that members of this community interact with each
other by making requests. So, our next principle of object- oriented problem solving is the vehicle by
which activities are initiated:
We have noted the important principle of information hiding in regard to message passing that
is, the client sending the request need not know the actual means by which the request will be
honored. There is another principle, all too human, that we see is implicit in message passing. If there
is a task to perform, the first thought of the client is to find somebody else he or she can ask to do the
work. This second reaction often becomes thin in many programmers with extensive experience in
conventional techniques. Frequently, a dificult hurdle to overcome is the idea in the programmer's
mind that he or she must write everything and not use the services of others.
4
The second is that the interpretation of the message (that is, the method used to respond to the
message) is dependent on the receiver and can vary with difierent receivers. I can give a message to
my neighbor Elizabeth, for example, and she will understand it and a satisfactory outcome will be
produced (that is, flflowers will be delivered to my friend). However, the method Elizabeth uses to
satisfy the request (in all likelihood, simply passing the request on to Flora) will be different from that
used by Flora in response to the same request. If I ask , someother to send flowers to my friend, he
may not have a method for solving that problem.
Let us move our discussion back to the level of computers and programs. There, the distinction
between message passing and procedure calling is that, in message passing, there is a designated
receiver, and the interpretation may vary with difierent receivers(the selection of a method to execute
in response to the message). Usually, the specific receiver for any given message will not be known
until run time, so the determination of which method to invoke cannot be made until then. Thus, we
say there is late binding between the message (function or procedure name) and the code fragment
(method) used to respond to the message. This situation is in contrast to the very early (compile-time
or link-time) binding of name to code fragment in conventional procedure calls.
1.1.3 Responsibilities
A traditional program often operates by acting on data structures, for example changing fields
in an array or record. In contrast, an object oriented program requests data structures (that is, objects)
to perform a service. This difference between viewing software in traditional, structured terms and
viewing it from an object-oriented perspective can be summarized by a twist on a well-known quote:
5
“Ask not what you can do to your data structures, but rather ask what your data structures can do for you”.
Although I have only dealt with Flora a few times, I have a rough idea of the behavior I can expect
when I go into her shop and present her with my request. I am able to make certain assumptions
because I have information about forists in general, and I expect that Flora, being an instance of this
category, will fit the general pattern. We can use the term Florist to represent the category (or class) of
all forists. Let us incorporate these notions into our next principle of object-oriented programming:
All objects are instances of a class.The method invoked by an object in response to a message is
determined
by the class of the receiver. All objects of a given class use the same method in response to similar
messages.
6
1.1.5 Class Hierarches - Inheritance
I have more information about Flora not necessarily because she is a florist but because she is a
shopkeeper. I know, for example, that I probably will be asked for money as part of the transaction,
and that in return for payment I will be given a receipt. These actions are true of grocers, stationers,
and other shopkeepers. Since the category Florist is a more specialized form of the category
Shopkeeper, any knowledge I have of Shopkeepers is also true of Florists and hence of Flora.
One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy
of categories (see Figure 1.2). Flora is a Florist, but Florist is a specialized form of Shopkeeper.
Furthermore, a Shopkeeper is also a Human; so I know, for example, that Flora is probably bipedal. A
Human is a Mammal (therefore they nurse their young and have hair), and a Mammal is an Animal
(therefore it breathes oxygen), and an Animal is a Material Object (therefore it has mass and weight).
Thus, quite a lot of knowledge that I have that is applicable to Flora is not directly associated with her,
or even with her category Florist.
There is an alternative graphical technique often used to illustrate this relationship, particularly
when there are many individuals.. This technique shows classes listed in a hierarchical tree-like
structure, with more abstract classes (such as Material Object or Animal) listed near the top of the
tree, and more specific classes, and finally individuals, are listed near the bottom. Figure 1.3 shows
this class hierarchy for Flora.
“Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will inherit
attributes from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for
which there are no direct instances; it is used only to create subclasses.”
I know that mammals give birth to live children, but Phyl is certainly a Mammal, but it lays eggs. To
accommodate this, we need to find a technique to encode exceptions to a general rule.
The search for a method to invoke in response to a given message begins with the class of the receiver. If no
appropriate method is found, the search is conducted in the parent class of this class. The search continues up
the parent class chain until either a method is found or the parent class chain is exhausted. In the former case
the method is executed; in the latter case, an error message is issued. If methods with the same name can be
found higher in the class hierarchy, the method executed is said to override the inherited behavior.
8
Even if the compiler cannot determine which method will be invoked at run time, in many
object-oriented languages, such as Java, it can determine whether there will be an appropriate method
and issue an error message as a compile-time error diagnostic rather than as a run-time message.
Everything is an object.
An object is a runtime entity in an object oriented programming
Computation is performed by objects communicating with each other. Objects
communicate by sending and receiving messages. A message is a request for action
bundled with whatever arguments may be necessary to complete the task.
Each object has its own memory, which consists of other objects.
Every object is an instance of a class. A class simply represents a grouping of similar
objects, such as integers or lists.
The class is the repository for behavior associated with an object. That is, all objects that
are instances of the same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called the inheritance hierarchy.
Memory and behavior associated with instances of a class are automatically available to
any class associated with a descendant in this tree structure.
Wrapping of data and methods into a single unit (called class)is known as
“encapsulation”
Encapsulation makes it possible to treat Object as a blackbox each performing a specific
task without any conceren for internal implementation.
9
Figure 1.3:Encapusulation
Insulation of the data from direct acess by the program is called as “data hiding”.
Abstraction refers to the act of representing essential features without including
background details or exaplanations
Inheritance is the process by which objects of one class acquire the properties of objects
of another class.Inheritance supports the concept of hierarchical classification as shown
below.
Polymorphism means the ability to take more than one form.For example ,an operation
may exhibit different behaviour in different instance.
10
Figure 1.5:Polymorphism
Attributes: Attributes are data that defines the traits of an object. This data can be as simple as integers and
real numbers. It can also be a reference to a complex object.
Methods: They define the behavior and are also called functions or procedures.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
12
Figure 1.6: Features of Java
Simple:
13
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independence :
Java provides software-based platform. The Java platform differs from most other platforms in
the sense that it's a software-based platform that runs on top of other hardware-based platforms.
It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g.Windows,Linux,SunSolaris,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).
14
Secured:
Java is secured because
Robust :
Robust simply means strong. Java uses strong memory management. There is automatic
garbage collection in java. There is exception handling and type checking mechanism in java.
All these points makes java robust.
Architecture-neutral:
Portable :
High-performance:
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Distributed :
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
15
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
Platform : Any hardware or software environment in which a program runs, known as a platform.
Since Java has its own Runtime Environment (JRE) and API, it is called platform.
History of Java
Java team members (also known as Green Team), initiated a revolutionary task to develop a language
for digital devices such as set-top boxes, televisions etc. It was best suited for internet programming.
Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There
are given the major points that describes the history of java.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
Firstly, it was called "Greentalk" by James Gosling and file extension as .gt.After that, it was called
Oak and was developed as a part of the Green project.
Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France,
Germany, Romania etc. In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies. Java is an island of Indonesia where first coffee was produced (called java coffee).
16
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
Applications using Java: There are mainly 4 type of applications that can be created using java
a. Standalone Application:
b. Web Application:
An application that runs on the server side and creates dynamic page, is called web application.
Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web applications in
java.
c. Enterprise Application:
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.
17
d. Mobile Application:
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
JRE is an acronym for Java Runtime Environment.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.
18
Figure 1.9: Java Runtime Environment (JRE)
JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime
Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java enabled system without
any adjustment. This is all possible because of JVM.
JVM is an abstract machine. It is a specification that provides runtime environment in which java
bytecode can be executed . JVMs are available for many hardware and software platforms.
JVM is:
NOTE:JVM, JRE and JDK are platform dependent because configuration of each OS differs.
But, Java is platform independent
When we compile a .java file, .class files(contains byte-code) with the same class names
present in .java file are generated by the Java compiler. This .class file goes into various
steps when we run it. These steps together describe the whole JVM.
19
Class Loader Subsystem
Loading
Linking
Initialization
Loading : The Class loader reads the .class file, generate the corresponding binary data
and save it in method area.
20
Linking : Performs verification, preparation, and (optionally) resolution.
o Verification : It ensures the correctness of .class file i.e. it check whether this file is
properly formatted and generated by valid compiler or not. If verification
fails, we get run-time exception java.lang.VerifyError.
o Preparation : JVM allocates memory for class variables and initializing the memory to
default values.
o Resolution : It is the process of replacing symbolic references from the type with
direct references. It is done by searching into method area to locate the
referenced entity.
Initialization : In this phase, all static variables are assigned with their values defined in the
code and static block(if any). This is executed from top to bottom in a class and from parent to
child in class hierarchy.
Method area /Class area:In method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There is only
one method area per JVM, and it is a shared resource.
Heap area :Information of all objects is stored in heap area. There is also one Heap Area per JVM. It
is also a shared resource.
Stack area :For every thread, JVM create one run-time stack which is stored here. Every block of this
stack is called “activation record/stack frame” which store methods calls. All local variables of that
method are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be
destroyed by JVM. It is not a shared resource.
PC Registers :Store address of current execution instruction of a thread. Obviously each thread has
separate PC Registers.
Native method stacks :For every thread, separate native stack is created. It stores native method
information.
21
Execution Engine
Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and
information present in various memory area and execute instructions. It can be classified in three parts
:-
Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is that
when one method is called multiple times, every time interpretation is required.
22
Java Native Interface (JNI) :
It is an interface which interacts with the Native Method Libraries and provides the native libraries(C,
C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++
libraries which may be specific to hardware.
It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.
Installation of Java
The following steps will demonstrate the installation of Java
23
24
3. On the page that loads, scroll down until you see “Java SE Development Kit (JDK).”
Click on the “Download” button to the right.
NOTE: At the time of writing (January 2009) the latest version of the JDK is 6 Update 11.
4. On the page that loads, choose Windows as your platform, set language to Multi-
Language, and select the checkbox. Finally, click the orange “Continue >>” button.
NOTE: If you are confident that you are on a 64-bit Windows installation, you can select
Windows x64 as your platform, but do not need to do so.
25
5. On the next screen that loads click to download the “Java SE Development Kit.”
NOTE: You may be requested to use the Sun Downloader to download Java. I advise just
using the directly linked full download.
26
7. loading the file may take a couple of minutes based on your connection speed.
27
9. Launch the installer. If User Account Control given a security warning click the “Yes”
button. The installer should begin loading. Please be patient.
10. Eventually you will be presented with an End User License Agreement (EULA). Read
it before clicking the “Accept >” button.
28
11. For this course, a default installation is completely fine, so just click the
“Next >” button.
NOTE: Pay attention to the “Install to:” location, you will need it later.
29
13. You will then be asked to install the Java Runtime Engine (JRE.) Click the “Next >”
button.
30
15. You are now done installing Java. All that is left is configuration.
Note: You may be asked to reboot your computer at this point. If you are, please do so.
31
Setting of path and class path
1. Now load the System Information Window by right clicking on “Computer” in the start
menu and selecting properties.
Note: This step can be done in other ways too. Such as…
32
2. The System Information Window should load.
33
4. System Properties window should open with the “Advanced” tab already selected.
Click on “Environment Variables” button.
34
6. In the “System variables” region, scroll down until you see the “Path” variable.
35
8. You should now be editing the “Path” variable.
9. Remember the “Install to:” location on Step 12? That is the line you need to add to the
end of the path. Be sure to prefix the location with a ; and post fix it with bin
Therefore you want to add:
;<YOUR_INSTALL_LOCATION>bin
On MY computer, a Windows 7 beta x64 machines where I installed the 32-bit JDK, that
meant:
36
10. Click the “OK” button to confirm your change.
37
12. Click the “OK” button in the System Properties dialog.
13. Close the System information window by clicking on the x icon on the top right.
38
14. Now to test our changes. Open the “Command Prompt” by going to:
Note: This step can be done in other ways too. Such as…
Opening the Run Dialog and entering the command “cmd” (without the
quotes.)
Searching for “Command Prompt” in the start menu.
39
16. Enter the command “path” (without the quotes) and press enter. You should see the new
path location, which includes your update.
17. Enter the command “java -version” (without the quotes) and press enter. You should
see the JRE version you have installed.
40
18. Enter the command “javac -version” (without the quotes) and press enter. You should
see the JDK version you have installed.
19. Close the command prompt by click on the x on the top right or typing “exit”
(without the quotes) and pressing enter.
At this point, you can delete the JDK installer that you downloaded on step 6.
41
Setting of CLASSPATH in Java
o You need to load a class that is not present in the current directory or any sub-directories.
o You need to load a class that is not in a location specified by the extensions mechanism.
In the above command, The set is an internal DOS command that allows the user to change the
variable value. CLASSPATH is a variable name. The variable enclosed in percentage sign (%) is an
existing environment variable. The semicolon is a separator, and after the (;) there is the PATH of
rt.jar file.
Step 1: Click on the Windows button and choose Control Panel. Select System.
Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a
semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable
name as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector
Java.jar;.;
43
Java Programming 44
PATH CLASSPATH
It is used by the operating It is used by Application ClassLoader to locate the .class file.
system to find the executable
files (.exe).
You are required to include the You are required to include all the directories which contain
directory which contains .exe .class and JAR files.
files.
44
Java Programming 45
1.Open a simple text editor program such as Notepad and type the following content:
2.Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java
Now let’s compile our first program in the HelloWorld.java file using javac tool.
Syntax: javac programname.java
Type the following command to change the current directory to the one where the source file is stored:
It’s now ready to run our first Java program. To run java program use following Syntax
That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no .java or
.class extension). You would see the following output:
45
Java Programming 46
Structure of a java program is the standard format released by Language developer to the Industry
programmer.
Sun Micro System has prescribed the following structure for the java programmers for developing
java application.
{ {
{ }
} {
Obj.display();
46
Java Programming 47
A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of
classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package
is known as default package.
Class is keyword used for developing user defined data type and every java program must start with a
concept of class.
"ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.
Data member represents either instance or static they will be selected based on the name of the class.
User-defined methods represents either instance or static they are meant for performing the operations
either once or each and every time.
Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.
Since main() method of java is not returning any value and hence its return type must be void.
Since main() method of java executes only once throughout the java program execution and hence its
nature must be static.
Since main() method must be accessed by every java programmer and hence whose access specifier must
be public.
Each and every main() method of java must take array of objects of String.
Block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.
The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.
Java is a free-form language. This means that you do not need to follow any special indentation rules. For
example, the Example program could have been written all on one line or in any other strange way you felt like
typing it, as long as there was at least one whitespace character between each token that was not already delineated
by an operator or separator. In java, whitespace is a space, tab, or new line.
47
Java Programming 48
Identifiers:
Identifiers are used for class names, method names, and variable names. An identifier may be any
descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign characters. They
must not begin with a number, lest they be confused with a numeric literal. Again, java is case-sensitive,
so VALUE is a different identifier the Value. Some examples of valid identifiers are:
Literals:
Using a literal representation of it creates a constant value in java. For example, here are some literals:
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character
constant, and the last is a string. A literal can be used anywhere a value of its type is allowed.
Comments:
As mentioned, there are three types of comments defined by java. You have already seen two: single-line
and multilane. The third type is called a documentation comment. This type of comment is used to produce an
HTML file that documents your program. The documentation comment begins with a /** and ends with a*/.
Separators
There are few symbols in java that are used as separators.The most commonly used separator in java is the
semicolon ' ; '. some other separators are Parentheses '( )' , Braces ' {} ' , Bracket ' [] ' , Comma ' , ' , Period ' . ' .
Java Keywords
There are 49 reserved keywords currently defined in java. These keywords cannot be used as names for a variable,
class or method.
Every variable has a type, every expression has a type and all types are strictly define .Every assignment
should be checked by the compiler by the type compatibility hence java language is considered as
strongly typed language. In java, There are two types of Data Types:
48
Java Programming 49
byte
short
int
long
float
double
49
Java Programming 50
Values of class type are references. Strings are references to an instance of class String.
-9223372036854775808 to
long 8 0
9223372036854775807
2. Non-Primitive Data Types:Derived data types are those that are made by using any other data type
and can make a variable to store multiple values ,for example, arrays.
3. User Defined Data Types: User defined data types are those that user / programmer himself
defines. For example, classes, interfaces.
Note : int a
MyClass obj;
Here obj is a variable of data type MyClass and we call them reference variables as they can be used
to store the reference to the object of that class.
In java char uses 2 byte in java because java uses unicode system rather than ASCII code system.
\u0000 is the lowest range of unicode system.
Unicode System
50
Java Programming 51
1.1.11 Variables
Introduction of variables:
Name
Value
The binary data contained in memory. The value is interpreted according to the variable's
datatype.
Address
The location in memory where the value is stored.
Size
The number of bytes that the variable occupies in memory.
51
Java Programming 52
Datatype
The interpretation of the value.
Range
The minimum and maximum values of the variable. The range of a variable depends on its size. In
general, the bigger the size in bytes, the bigger the range.
Declaration of variables:
Syntax:
Datatype variable_name;
Initialization of Variable:
ii.Runtime initialization
Syntax:
Datatype variable_name=value;
52
Java Programming 53
Datatype variable_name=Expression;
double a =10.0,b=20.0;
double d=Math.squart(49)+a+b;
ii)Runtime Initialization
In Java, there are three different ways for reading input from the user in the command line
environment(console).
This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping
the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we
can read input from the user in the command line.
Advantages
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.
import java.io.*;
class Readdemo
53
Java Programming 54
{
public static void main(String args[]) throws IOException
{
int x;String str;
System.out.println("enter x value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Integer.parseInt(br.readLine());
System.out.println("x value is"+x);
System.out.println("enter ur name");
str=br.readLine();
System.out.println(" ur name is"+str);
}
}
Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read
multiple values, we use split().
This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however it is also can be used to read input
from the user in the command line.
Advantages:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
Drawback:
The reading methods are not synchronized
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
System.out.println("enter a string”);
String s = in.nextLine();
System.out.println("enter a integer”);
int a = in.nextInt();
System.out.println("enter a float”);
float b = in.nextFloat();
System.out.println("You entered string "+s);
System.out.println("You entered integer "+a);
System.out.println("You entered float "+b);
}
54
Java Programming 55
}
Output:
enter a string
CMREC
enter a integer
12
enter a float
3.4
It has been becoming a preferred way for reading user’s input from the command line. In addition, it can
be used for reading password-like input without echoing the characters entered by the user; the format
string syntax can also be used (like System.out.printf()).
Advantages:
import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
55
Java Programming 56
56
Java Programming 57
Local Variable
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable .
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
} //end of class
The scope determines what objects are visible to other parts of program and also determine Lifetime of
the those objects.
In java,scope is defined by the class and by the method.The instance variables and static variables are
declared which the class and out of any method ,so this types variables are available through out the class
57
Java Programming 58
The local variables are declared in side the method .so this avariables are available with the block in
which there are declared.
The process of converting one data type to another data type is called as Casting
Types of castings:
Casting larger data type into smaller data type may result in a loss of data.
This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the
value narrower.
To create a conversion between two incompatible types, you must use a cast. A cast is
double m=50.00;
int n=(int)m;
58
Java Programming 59
When one type of data is assigned to another type of variable, an automatic type conversion
When these two conditions are met, a widening conversion takes place.
Example:
int i=30;
double x;
x=i;
The double type is always large enough to hold all valid int values, so no explicit cast statement is
required.
class Typecastdemo
double f=3.141,x;
int i,j=30;
i=(int)f;//explicit conversion
x=j;//implicit conversion
59
Java Programming 60
Output: i value is 3
x value is 30.00
The sequence of promotion rules that are applied while implicit type conversion is as follows: All
byte,short and char are automatically converted to int; then
1. if one of the operands is long, the other will be converted to long and the result will be long
2. else, if one of the operands is float, the other will be converted to float and the result will be float
3. else, if one of the operands is double, the other will be converted to double and the result will be
.The final result of an expression is converted to the type of the variable on the left of the assignment sign
before assigning the value to it. However the following changes are introduced during the final
assignment.
Float to int causes truncation of the fractional part. Double to float causes rounding of digits.
60
Java Programming 61
Long int to int causes dropping of the excess higher order bits.
1.1.12 Arrays
Introduction
Definition of Array
Normally, array is a collection of similar type of elements that have contiguous memory location.
Sytax:
Datatype arrayname[ ];
Or
Datatype[ ] arrayname;
Example :
int a[ ];
61
Java Programming 62
int[ ] a; //recommended to use because name is clearly separated from the type int
[ ]a;
At the time of declaration we can’t specify the size otherwise we will get compile time error.
Example :
int[ ] a;//valid
int[5] a;//invalid
Every array in java is an object hence we can create by using new operator.
arrayname=new datatype[size];
Example :
a= new int[3];
Example:
Diagram:
62
Java Programming 63
For every array type corresponding classes are available but these classes are part of java
language and not available to the programmer level.
Rules for creating an Array
Rule 1 :
At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.
Example :
Rule 2:
Example :
Rule 3 :
If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.
Example :
Rule 4:
The allowed data types to specify array size are byte, short, char, int. By mistake if we are using
any other type we will get compile time error.
63
Java Programming 64
Example :
byte b=10;
Rule 5 :
The maximum allowed array size in java is maximum value of int size [2147483647].
Example :
Array initialization:
arrayname[subscript]=value;
Example:
a[0]=10;
64
Java Programming 65
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4
a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4
Diagram:
Note:if we are trying to access array element with out of range index we will
get RuntimeException saying ArrayIndexOutOfBoundsException
Example:
int [] a={10,20,30};//valid
String[] s={"abc","def","jog","lmn”};(valid)
65
Java Programming 66
Whenever we are creating an array every element is initialized with defaultvalue automatically.
Example 1:
Array Length:
length Vs length():
length:
length() method:
Example:
66
Java Programming 67
System.out.println(x.length);//3
Example:
String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
class Testarray1
{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output :
33
3
4
5
67
Java Programming 68
Passing Array to method in java. We can pass the java array to method so that we can reuse the same
logic on any array.
Let's see the simple example to get minimum number of an array using method.
class Testarray2 {
static void min(int arr[]) {
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a); //passing array to method
}
}
Output: 3
2.Multidimensional Array
68
Java Programming 69
In java multidimensional arrays are implemented as array of arrays approach but not matrix
form.
The main advantage of this approach is to improve memory utilization.
Datatype arrayname[ ][ ];
Or
Datatype[ ][ ] arrayname;
int [ ][ ]a;
int [ ][ ]a;
int [ ] [ ]a;
int [ ] a[ ];
int [ ]a[ ];
Example :
69
Java Programming 70
syntax:
Example:
int a[ ] [ ];
a=new int[3][2];
Syntax
Example1:
70
Java Programming 71
a[0]=new int[2];
a[1]=new int[4];
a[2]=new int[3];
Example:
int[][] a={{10,20,30},{40,50}};`
Diagram:
If we want to use this short cut compulsory we should perform declaration, construction and
initialization in a single line. If we are trying to divide into multiple lines then we will get compile
time error.
Length variable applicable only for arrays where as length()method is applicable for String objects.
Example :
71
Java Programming 72
Diagram:
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
}
Output:1 2 3
245
445
72
Java Programming 73
class twodarrayaddition
{
public static void main(String args[]) {
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output : 2 6 8
6 8 10
73
Java Programming 74
int[ ][ ][ ] a;
int [ ][ ][ ]a;
int [ ] a[ ][ ];
int [ ][ ]a[ ];
Anonymous Arrays:
Sometimes we can create an array without name such type of nameless arrays are called
anonymous arrays.
The main objective of anonymous arrays is “just for instant use”.
We can create anonymous array as follows.
At the time of anonymous array creation we can’t specify the size otherwise we will get compile time
error.
Example :
74
Java Programming 75
o Code Optimization : It makes the code optimized, we can retrieve or sort the data easily.
o Random access : We can get any data located at any index position.
o Readability : we can represent multiple values with the same name so that readability of the
code will be improved
o Fixed in size that is once we created an array there is no chance of increasing or decreasing
the size based on our requirement that is to use arrays concept compulsory we should know
the size in advance which may not possible always.
o We can resolve this problem by using collections.
1.1.13 Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators −
75
Java Programming 76
Show Examples
- (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10
* (Multiplication) Multiplies values on either side of the operator. A * B will give 200
Assume variable A holds 10 and variable B holds 20, then −Show Examples
76
Java Programming 77
>= (greater than Checks if the value of left operand is greater than or equal to
(A >= B) is not true.
or equal to) the value of right operand, if yes then condition becomes true.
<= (less than or Checks if the value of left operand is less than or equal to the
(A <= B) is true.
equal to) value of right operand, if yes then condition becomes true.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char,
and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Show Examples
77
Java Programming 78
Binary Ones Complement Operator (~A ) will give -61 which is 1100 0011 in 2's
~ (bitwise
is unary and has the effect of complement form due to a signed binary
compliment)
'flipping' bits. number.
78
Java Programming 79
Show Examples
Show Examples
79
Java Programming 80
Miscellaneous Operators
80
Java Programming 81
Conditional Operator ( ? : )
instanceof Operator
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be
assigned to the variable. The operator is written as −
Example
publicclassTest {
publicstaticvoid main(String args[]){
int a, b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}
Output
Value of b is : 30
Value of b is : 20
81
Java Programming 82
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type (class type or interface type). instanceof operator is written as −
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −
Example
publicclassTest{
publicstaticvoid main(String args[]) {
String name ="James";
// following will return true since name is type of String
boolean result = name instanceofString;
System.out.println( result );
}
}
Output
true
This operator will still return true, if the object being compared is the assignment compatible with the
type on the right. Following is one more example −
Example
classVehicle{}
publicclassCarextendsVehicle{
publicstaticvoid main(String args[]){
Vehicle a =newCar();
82
Java Programming 83
Output
true
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
83
Java Programming 84
84
Java Programming 85
One of the most common operators that you'll encounter is the simple assignment operator " =".
int cadence = 0;
int speed = 0;
int gear = 1;
classArithmeticDemo {
int result = 1 + 2;
// result is now 3
intoriginal_result = result;
result = result - 1;
// result is now 2
original_result = result;
result = result * 2;
// result is now 4
85
Java Programming 86
original_result = result;
result = result / 2;
// result is now 2
original_result = result;
result = result + 8;
// result is now 10
original_result = result;
result = result % 7;
// result is now 3
1+2=3
3-1=2
2*2=4
4/2=2
2 + 8 = 10
10 % 7 = 3
86
Java Programming 87
You can also combine the arithmetic operators with the simple assignment operator to create
compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the
following ConcatDemo program:
classConcatDemo
System.out.println(thirdString);
The unary operators require only one operand; they perform various operations such as incrementing /
decrementing a value by one, negating an expression, or inverting the value of a boolean.
Operator Description
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
87
Java Programming 88
ClassUnaryDemo {
// result is now 1
System.out.println(result);
result--;
// result is now 0
System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = -result;
// result is now -1
System.out.println(result);
// false
System.out.println(success);
// true
System.out.println(!success);
88
Java Programming 89
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The
code result++; and ++result; will both end in result being incremented by one. The only difference is that
the prefix version (++result) evaluates to the incremented value, whereas the postfix version ( result++)
evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't
really matter which version you choose. But if you use this operator in part of a larger expression, the
one that you choose may make a significant difference.
The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:
classPrePostDemo {
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
89
Java Programming 90
90
Java Programming 91
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean
expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand
is evaluated only if needed.
Operator Description
&& Conditional-AND
|| Conditional-OR
class ConditionalDemo1 {
int value1 = 1;
int value2 = 2;
91
Java Programming 92
class ConditionalDemo2 {
int value1 = 1;
int value2 = 2;
int result;
booleansomeCondition = true;
System.out.println(result);
Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of
an if-then-else statement if it makes your code more readable; for example, when the expressions
are compact and without side-effects (such as assignments).
The Java programming language also provides operators that perform bitwise and bit shift operations
on integral types. The operators discussed in this section are less commonly used. Therefore, their
coverage is brief; the intent is to simply make you aware that these operators exist.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral
types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this
operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator
">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number
92
Java Programming 93
of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero
into the leftmost position, while the leftmost position after ">>" depends on sign extension.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard
output.
classBitDemo {
intval = 0x2222;
// prints "2"
System.out.println(val& bitmask);
93
Java Programming 94
1.1.14 Expressions
Definition: An expression is a series of variables, operators, and method calls (constructed according to
the syntax of the language) that evaluates to a single value. As discussed in the previous section, operators
return a value, so the use of an operator is an expression. This partial listing of
the MaxVariablesDemo program shows some of the program's expressions in boldface:
...
...
if (Character.isUpperCase(aChar)) {
... }
Each expression performs an operation and returns a value, as shown in the following table.
94
Java Programming 95
The data type of the value returned by an expression depends on the elements used in the expression. The
expression aChar = 'S' returns a character because the assignment operator returns a value of the same data
type as its operands and aChar and 'S' are characters. As you see from the other expressions, an expression
can return a boolean value, a string, and so on.
The Java programming language allows you to construct compound expressions and statements from
various smaller expressions as long as the data type required by one part of the expression matches the
data type of the other. Here's an example of a compound expression:
x*y*z
. For example, the following expression gives different results, depending on whether you perform the
addition or the division operation first:
x + y / 100 //ambiguous
You can specify exactly how you want an expression to be evaluated, using balanced parentheses—
( and ). For example, to make the previous expression unambiguous, you could write:
If you don't explicitly indicate the order in which you want the operations in a compound expression to be
performed, the order is determined by the precedence assigned to the operators in use within the
expression. Operators with a higher precedence get evaluated first. For example, the division operator has
a higher precedence than does the addition operator. Thus, the two following statements are equivalent:
x + y / 100
When writing compound expressions, you should be explicit and indicate with parentheses which
operators should be evaluated first. This pratice will make your code easier to read and to maintain.
95
Java Programming 96
A control statement works as a determiner for deciding the next task of the other statements whether to
execute or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute
first between the two. In Java, the control statements are divided into three categories which are selection
statements, iteration statements, and jump statements. A program can execute from top to bottom but if
we use a control statement. We can set order for executing a program based on values and logic, see below
table .
Simple if Statement
if…else Statement
Nested if statement
if...else if…else statement
Switch statement
While
Do…while
For
For-Each Loop
Break
Continue
Return
96
Java Programming 97
Decision making statements are statements which decides what to execute and when. They are similar to
decision making in real time. Control flow statements control the flow of a program’s execution. Here
flow of execution will be based on state of a program. We have 4 decision making statements available in
Java.
Simple if Statement :
Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code
should be executed based on the condition.
Syntax:
if (condition)
{
Statemen 1; //if condition becomes true then this will be executed
}
Example:
class ifTest {
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
Output:
After if statement
97
Java Programming 98
if…else Statement :
In if…else statement, if condition is true then statements in if block will be executed but if it comes out as
false then else block will be executed.
Syntax: if (condition) {
Example:
class ifelseTest {
int x = 9;
if (x > 10)
else
Output:
98
Java Programming 99
i is less than 10
Nested if statement :
Nested if statement is if inside an if block. It is same as normal if…else statement but they are written
inside another if…else statement.
Syntax: if (condition1)
{
Statemen 1; //executed when condition1 is true
if (condition2)
{
Statement 2; //executed when condition2 is true
}
else
{
Statement 3; //executed when condition2 is false
}
}
Example:
class nestedifTest {
int x = 25;
if (x > 10) {
if (x%2==0)
99
Java Programming 100
else
else {
Output:
if…else statement :
if…else if statements will be used when we need to compare the value with more than 2 conditions. They
are executed from top to bottom approach. As soon as the code finds the matching condition, that block
will be executed. But if no condition is matching then the last else statement will be executed.
Syntax:
if (condition1) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will be executed
}
....
....
else {
Statement 3; //executed when no matching condition found
100
}
Java Programming 101
Example:
class ifelseifTest {
int x = 2;
if (x > 10) {
else if (x <10)
else {
System.out.println("i is 10");
Output:
i is less than 10
101
Java Programming 102
Switch statement :
Java switch statement compares the value and executes one of the case blocks based on the condition. It is
same as if…else if ladder. Below are some points to consider while working with switch statements:
» case value must be of the same type as expression used in switch statement
» case value must be a constant or literal. It doesn’t allow variables
» case values should be unique. If it is duplicate, then program will give compile time error
class switchDemo{
int i=2;
switch(i){
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
102
Java Programming 103
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
break;
Looping statements are the statements which executes a block of code repeatedly until some condition
meet to the criteria. Loops can be considered as repeating if statements. There are 3 types of loops
available in Java.
While :
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes
the body of loop. This is repeated until the condition becomes false. Condition in while loop must be
given as a Boolean expression. If int or string is used instead, compile will give the error.
Syntax:
Initialization;
while (condition)
{
statement1;
increment/decrement;
}
103
Java Programming 104
Example:
class whileLoopTest {
int j = 1;
System.out.println(j);
j = j+2;
Output:
1 3 5 7 9
Do…while :
Do…while works same as while loop. It has only one difference that in do…while, condition is checked
after the execution of the loop body. That is why this loop is considered as exit control loop. In do…while
loop, body of loop will be executed at least once before checking the condition
Syntax: do
{
statement1;
}while(condition);
104
Java Programming 105
Example:
class dowhileLoopTest {
int j = 10;
do {
System.out.println(j);
j = j+1;
Output: 10
For Statement :
It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in
code as initialization of a variable, a condition and increment/decrement are declared only in a single line
of code. It is easy to debug structure in Java.
Syntax:
for (initialization; condition; increment/decrement)
statement;
105
Java Programming 106
Example:
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:
For-Each Loop :
For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to
increment the value. It returns the elements from the array or collection one by one.
Example:
class foreachDemo {
for (int i : a) {
106
Java Programming 107
System.out.println(i);
Output:
10
15
20
25
30
Branching statements jump from one statement to another and transfer the execution flow. There are 3
branching statements in Java.
Break :
Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly
used in loop to stop the execution and comes out of loop. When there are nested loops then break will
terminate the innermost loop.
Example:
class breakTest {
107
Java Programming 108
if (j == 4)
break;
System.out.println(j);
System.out.println("After loop");
Output:
After loop
Continue :
Continue statement works same as break but the difference is it only comes out of loop for that iteration
and continue to execute the code for next iterations. So it only bypasses the current iteration.
Example:
class continueTest {
108
Java Programming 109
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
Output:
02468
ASIS FOR
BREAK CONTINUE
COMPARISON
Control after 'break' resumes the control of the 'continue' resumes the control
break/continue program to the end of loop enclosing of the program to the next
enclosing 'continue'.
109
Java Programming 110
Continuation 'break' stops the continuation of loop. 'continue' do not stops the
Other uses 'break' can be used with 'switch', 'continue' can not be
'labels'.
Return :
Return statement is used to transfer the control back to calling method. Compiler will always bypass any
sentences after return statement. So, it must be at the end of any method. They can also return a value to
the calling method.
Class fundamentals
» Creating Java applications, including the main() method and how to pass arguments to a
Java program from a command line
110
Java Programming 111
Definition :
A class is a sort of template which has attributes and methods. An object is an instance of a class,
e.g. Ram is an object of type Person.
class classname {
type var1;
type var2;
// declare methods
type method1(parameters) {
// body of method
type method2(parameters) {
// body of method
// ...
type methodN(parameters) {
// body of method
The classes we have used so far had only one method, main(), however not all classes specify a
main method. The main method is found in the main class of a program (starting point of
program).
111
Java Programming 112
A Simple Class
Let’s begin our study of the class with a simple example. Here is a class called Box that defines three
instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will
be added soon).
class Box {
double width;
double height;
double depth;
As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use
this name to declare objects of type Box. It is important to remember that a class declaration only creates a
template; it does not create an actual object. Thus, the preceding code does not cause any objects of type
Box to come into existence.
To create an object of the class we use new keyword as shown below syntaxt
After this statement executes, mybox will be an instance of Box. Thus, it will have “physical” reality.
For the moment, don’t worry about the details of this statement.
As mentioned earlier, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class. Thus, every Box object will contain
its own copies of the instance variables width, height, and depth. To access these variables, you will use
the dot (.) operator. The dot operator links the name of the object with the name of an instance variable.
112
Java Programming 113
object.member=value;
For example, to assign the width variable of mybox the value 100, you would use the following statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the mybox object
the value of 100. In general, you use the dot operator to access both the instance variables and the methods
within an object.
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box {
double width;
double height;
double depth;
class BoxDemo {
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
113
Java Programming 114
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
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.
Constructors
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Rules for creating Constructor
There are basically two rules defined for the constructor.
2. parameterized constructor
1) Default Constructor
class_name( )
Statements;
In this example, we are creating the no-arg constructor in the DefaultConstructor class. It will be invoked
at the time of object creation.
class DefaultConstructor
{
DefaultConstructor()
{
System.out.println("hai");
}
public static void main(String args[])
{
DefaultConstructor obj=new DefaultConstructor();
}
}
115
Java Programming 116
Output: hai
Default constructor provides the default values to the object like 0, null etc. depending on the
typeExample of default constructor that displays the default values
class DefaultC
{
int stdid;
String name;
static void dispaly()
{
System.out.println("stdid"+"");
System.out.println("name"+"");
}
public static void main(String args[])
{
Output: dc=new DefaultC();
DefaultC
dc.display();
}0 null
}
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.
2. Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
116
Java Programming 117
class Paraconstructor
{
int stdid;
String name;
Paraconstructor(int x,String n)
{
stdid=x;
name=n;
}
void display()
{
System.out.println("stdid is"+""+stdid);
System.out.println("name is"+""+name);
}
public static void main(String args[])
{
Paraconstructor obj1=new Paraconstructor(5,"abc");
obj1.display();
Paraconstructor obj2=new Paraconstructor(7,"def");
obj2.display();
}
}
Output:
stdid is 5
name is abc
stdid is 7
name is def
117
Java Programming 118
Constructor Method
Constructor must not have return type. Method must have return type.
Constructor name must be same as the class Method name may or may not be same as class
name. name.
118
Java Programming 119
double vol;
// 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);
}
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking
object.
119
Java Programming 120
For example, if we have a class Human, then this class should have methods like eating(), walking(),
talking(), etc, which in a way describes the behaviour which the object of this class will have.
//body of method
Example of a Method:
String name="StudyTonight";
name=name+st;
return name;
120
Java Programming 121
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is declare in method
heading.
While talking about method, it is important to know the difference between two
terms parameter and argument.
Parameter is variable defined by a method that receives value when the method is called. Parameter are
always local to the method they dont have scope outside the method. While argument is a value that is
passed to a method when it is called.
Overloading:
Overloading:
121
Java Programming 122
i)Method Overloading
ii)Constructor Overloading
i)Method overloading:
In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, 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.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call.
class Methodoverload
{
void display()
{
System.out.println("display method without arguements");
}
void display(int a)
{
System.out.println("display method with integer"+""+a);
}
void display(int a,double b)
{
System.out.println("display method with integer"+a+"and double"+b);
}
public static void main(String args[])
{
Methodoverload obj=new Methodoverload();
obj.display();
obj.display(10);
obj.display(20,65.99);
}
}
Output:
122
Java Programming 123
Constructor Overloading:
In addition to overloading normal methods, you can also overload constructor methods
class Coverload
{
int a;double b;
Coverload()
{
System.out.println("constructor without parameters");
}
Coverload(int i)
{
a=i;
System.out.println("constructor with one parameter");
System.out.println("a value is"+a);
}
Coverload(int i,double d)
{
a=i;
b=d;
Output:
123
Java Programming 124
Recursion:
Recursion:
Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to
Java programming, recursion is the attribute that allows a method to call itself. Amethod that calls itself
is said to be recursive.
Example on Recursion:
class Recursion
{
int fact(int n)
{
int result;
if(n==0||n==1)
return 1;
else
result=n*fact(n-1);
return result;
}
public static void main(String args[])
{
int ans;
Recursion obj=new Recursion();
ans=obj.fact(5);
System.out.println("factorial of 5 is"+ans);
}
}
Output:factorial of 5 is 120.
124
Java Programming 125
1. call-by-value : In this approach copy of an argument value is pass to a method. Changes made to
the argument value inside the method will have no effect on the arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside
the method will affect the agrument value.
Example of call-by-value:
125
Java Programming 126
Example of call-by-Reference:
public class CBRTest {
int a;
CBRTest(int i)
{
a=i;
}
public void callByReference(CBRTest obj)
{
obj.a=obj.a+10;
}
public static void main(String[] args)
{
CBRTest obj = new CBRTest(10);
System.out.println("before calling a value is"+obj.a);
obj.callByReference(obj)//function call by passing object
System.out.println("after calling a value is"+obj.a);
}
}
Output:
NOTE: When a primitive type is passed to a method, it is done by use of call-by-value. Objects are
implicitly passed by use of call-by-reference.
126
Java Programming 127
Static Keyword:
The static keyword in Java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance
of the class.
The static variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
class Student{
int rollno;
String name;
String college="CMREC";
Suppose there are 500 students in my college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good
in such case. Here, "college" refers to the common property of all objects. If we make it static, this field
will get the memory only once.
127
Java Programming 128
class Student{
String name;
Note:As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value
class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
System.out.println(count);
//creating objects
Output:
128
Java Programming 129
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
Example:
class Demo{
System.out.println("Hello main");
129
Java Programming 130
Output:
Hello main
int a=10;
a=a+10;
System.out.println(a);
System.out.println(b);
130
Java Programming 131
Class Demo
System.out.println(“hello”);
System.out.println(“hello”);
fd. display( );
131
Java Programming 132
final class A
{
symbolic constants
Symbolic constants in Java are named constants. Constants may appear repeatedly in number of
places in the program. Constant values are assigned to some names at the beginning of the
program, then the subsequent use of these names in the program has the effect of caving their
defined values to be automatically substituted in appropriate points. The constant is declared as
follows:
Rules :-
1. Symbolic names take the some form as variable names. But they one written in capitals to
distance from variable names. This is only convention not a rule.
2.After declaration of symbolic constants they shouldn’t be assigned any other value within the
program by using an assignment statement.
132
Java Programming 133
3. They can’t be declared inside a method. They should be used only as class data members in the
beginning of the class.
class SymbolicDemo
int a=20,sum;
double r=30.49;
sum=A+a;
System.out.println("sum is "+sum);
double area=PI*r*r;
System.out.println("area is "+area);
133
Java Programming 134
We use nested classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable code.
Additionally, nested class can access all the members of outer class including private data members
and methods but viceverse is not possible
class Outer_class_Name
...
class Nested_class_Name
...
...
• Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
• Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
134
Java Programming 135
There are two types of nested classes non-static and static nested classes.
135
Java Programming 136
A class that is declared inside a class but outside a method is known as member inner
class.
In this example, we are invoking the method of member inner class from the display method of Outer
class.
class Outer
{
private int data=20;
class MemberInner
{
void message()
{
System.out.println("private data of outerclass is"+data);
}
}
void display()
{
MemberInner in=new MemberInner();
in.message();
}
public static void main(String args[])
{
Outer out=new Outer();
out.display();
}
}
Output:
private data of outerclass is 20
136
Java Programming 137
A class that is created inside a method is known as local inner class. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.
Example:
137
Java Programming 138
{
abstract void display();
}
class Annomynous
{
public static void main(String args[])
{
A static class that is created inside a class is known as static nested class. It cannot access the non-static
members outer class.
Output:data is 30
138
Java Programming 139
In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because nested class is
static and static properties, methods or classes can be accessed without object.
String is a sequence of characters. But in java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.
For example:
char[] ch={'j','a','v','a'};
is same as:
String s="java";
Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
i. By String Literal
ii. By new keyword
i) String Literal
String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
139
Java Programming 140
String s1="Welcome";
String s2="Welcome";//will not create new instance
String s= new String("Welcome"); //creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non
pool).
String objects are immutable, whenever you want to modify a String, you must
either copy it into a StringBuffer or StringBuilder, or use one of the following String methods,
which will construct a new copy of the string with your modifications complete.
The java.lang.String class provides many useful methods to perform operations on sequence of char
values
1 char charAt(int index) returns char value for the particular index
4 String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index
141
Java Programming 142
10 String replace(char old, char new) replaces all occurrences of specified char value
14 String[] split(String regex, int limit) returns splitted string matching regex and limit
16 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
18 int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index
142
Java Programming 143
Program on StringHandling :
String s1="hello";
String s2="hello";
String joinstring,stringlower,stringupper;
System.out.println(ch);
143
Java Programming 144
stringlower=name.toLowerCase( );
System.out.println(stringlower); // javaprogramming
stringupper= s1.toUpperCase();
System.out.println(stringupper); //HELLO
System.out.println(s1.trim()+"javaprogramming");//hellojavaprogramming
StringBuffer
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.
StringBuffer Constructors
Constructor Description
144
Java Programming 145
145
Java Programming 146
Command-Line Arguments
Sometimes you will want to pass information into a program when you run it. This is
the information that directly follows the program’s name on the command line when it is
executed.
they are stored as strings in a String array passed to the args parameter of main( ). The first
146
Java Programming 147
Example 1:
The following program displays all of the command-line arguments that it is called with:
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Running:
C:>\ java CommandLine have a nice time
output:
args[0]:have
args[1]: a
args[2]:nice
args[3]:time
REMEMBER All command-line arguments are passed as strings.
Example 2:
class CommandLine
{
public static void main(String args[])
{
int a,b,sum;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
sum=a+b;
System.out.println("addition of"+a+"and"+b+"is"+sum);
}
}
147
Java Programming 148
1.
Inherirance Concept
Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new
class is known as subclass. The subclass inherits all of its instances variables and methods defined by the
superclass and it also adds its own unique elements. Thus we can say that subclass are specialized version
of superclass.
1. Reusability of code
2. Code Sharing
3. Consistency in using an interface
1. Inherirance Basics
Defination:The process by which one class acquires the properties(data members) and functionalities
(methods) of another class is called inheritance.
(or)
Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.
Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent
class, super class or Base class.
148
Java Programming 149
The biggest advantage of Inheritance is that the code that is already present in base class need not be
rewritten in the child class.This means that the data members(instance variables) and methods of the
parent class can be used in the child class .Child class has to write only the unique features and rest of
the common properties and functionalities can be extended from the another class.
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and methods of ABC class.
Types of inheritance
1. Single Inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple Inheritance
1.Single Inheritance: refers to a child and parent class relationship where a class extends the another
class.
149
Java Programming 150
class A display
class B display
i value is 10
j value is 20
2.Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.
150
Java Programming 151
class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A");
}
}
class B extends A
{
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B");
}
void welcome()
{
System.out.println("class B-welcome method");
}
}
class C extends B
{
C()
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");
}
public static void main(String args[])
{
C oc=new C();
oc.Amethod();
oc.Bmethod();
oc.welcome();
151
Java Programming 152
}
}
Output:
A constructor
B constructor
C constructor
method of A
method of B
method of A
3.Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.
class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A class");
}
}
class B extends A
{
152
Java Programming 153
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B class");
}
}
class D extends A
{
D()
{
System.out.println("D constructor");
}
void Dmethod()
{
System.out.println(" method of D class");
}
public static void main(String args[])
{
D od=new D();
od.Amethod();
od.Dmethod();
B ob=new B();
ob.Amethod();
ob.Bmethod();
}
Output:
A constructor
D constructor
method of A class
method of D class
A constructor
B constructor
method of A class
method of B class
153
Java Programming 154
4.Multiple Inheritance: refers to the concept of one class extending more than one classes, which means
a child class has two parent classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritances.
5.Hybrid inheritance: Combination of more than one types of inheritance in a single program. For
example class A & B extends class C and another class D extends class A then this is a hybrid inheritance
example because it is a combination of single and hierarchical
154
Java Programming 155
inheritance.
1. Member Access
An instance variable of a class will be declared private to prevent its unauthorized use or tampering.
Inheriting a class does not overrule the private access restriction. Thus, even though a subclass includes
all of the members of its superclass, it cannot access those members of the superclass that have been
declared private. For example, if, as shown here, width and height are made private in TwoDShape,
then Triangle will not be able to access them:
Class PrivateAccess
155
Java Programming 156
int c;
void display()
c=a+b;
System.out.println(c);
Void sub()
156
Java Programming 157
157
Java Programming 158
class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A");
}
}
class B extends A
{
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B");
}
void welcome()
{
System.out.println("class B-welcome method");
158
Java Programming 159
}
}
class C extends B
{
C()
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");
}
public static void main(String args[])
{
C oc=new C();
oc.Amethod();
oc.Bmethod();
oc.welcome();
}
}
Output:
A constructor
B constructor
C constructor
method of A
method of B
method of A
159
Java Programming 160
Note: Multilevel inheritance is not multiple inheritances where one class can inherit more than one class
at a time. Java does not support multiple inheritances.
1. Super Uses
The super keyword in java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable
We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.
The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.
160
Java Programming 161
Example program to demonstrating invoking of parent class instance variable and parent class method
class A
{
int data=10;
void display()
{
System.out.println(" A class display");
}
}
class B extends A
{
int data=20;
void display()
{
System.out.println(" B class display");
}
void superdisplay()
{
System.out.println("data in A class is"+super.data);
super.display();
}
public static void main(String args[])
{
B obj=new B();
obj.display();
System.out.println(obj.data);
obj.superdisplay();
}
}
Output
B class display
20
data in A class is 10
A class display
161
Java Programming 162
The super keyword can also be used to invoke the parent class constructor.
class Parentclass
{
Parentclass()
{
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
//Compile implicitly adds super() here as the first statement of this
constructor.
System.out.println("Constructor of child class");
}
Subclass(int num)
{
// Even though it is a parameterized constructor The compiler still adds the super() here
System.out.println("arg constructor of child class");
}
void display()
{
System.out.println("Hello!");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
Subclass obj2= new Subclass(10);
obj2.display();
}
}
Output:
Constructor of parent class
162
Java Programming 163
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
variable
method
class
final class A
{
163
Java Programming 164
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
If you overload a static method in Java, it is the example of compile time polyymorphism.
164
Java Programming 165
The term ad hoc in this context is not intended to be pejorative; it refers simply to the fact that this type
of polymorphism is not a fundamental feature of the type system.
i)operator overloading:
Java also provide option to overload operators. For example, we can make the operator (‘+’) for string
class to concatenate two strings. We know that this is the addition operator whose task is to add two
operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed
between string operands, concatenates them.
class Operatoroverloading {
class Main {
public static void main(String[] args)
{
Operatoroverloading obj = new Operatoroverloading ();
obj.operator(2, 3);
obj.operator("CMR", "EC");
}
}
165
Java Programming 166
Output:
Sum = 5
ii)Method Overloading:
When there are multiple functions with same name but different parameters then these functions are said
to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type
of arguments. Overloaded methods are generally used when they conceptually execute the same task but
with a slightly different set of parameters.
class Main {
public static void main(String[] args)
{
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(2, 4,2));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
166
Java Programming 167
Output:
8
16
34.65
Note:
we overload static methods
we cannot overload methods that differ only by static keyword
we overload main() in Java
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
class A{}
167
Java Programming 168
A a=new B();//upcasting .
In this example, we are creating two classes A and B. B class extends A class and overrides its
display ()method. We are calling the display ()by the reference variable of Parent class. Since it refers to
the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
obj. display ();
}
}
Output:
B class display
Advantages of dynamic binding along with polymorphism with method overriding are.
168
Java Programming 169
1 When a class have same method Method overriding - Method of superclass is overridden in
name with different argument, subclass to provide more specific implementation.
than it is called method
overloading.
3 Both Static and instance method Only instance methods can be overridden in java.
can be overloaded in java.
Static methods can’t be overridden in java.
4 Main method can also be Main method can’t be overridden in java, because main is
overloaded in java static method and static methods can’t be overridden in java (as
mentioned in above point)
5 private methods can be private methods can’t be overridden in java, because private
overloaded in java. methods are not inherited in subClass in java.
6 final methods can be overloaded final methods can’t be overridden in java, because final
in java. methods are not inherited in subClass in java.
8 Method overloading concept is Method overriding concept is also known as runtime time
also known as compile time polymorphism or pure polymorphism or Dynamic binding
polymorphism or ad hoc in java.
169
Java Programming 170
1. Method Overriding
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.variable of the current object.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as upcasting
class A{}
A a=new B();//upcasting
class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
170
obj. display ();
}
}
Java Programming 171
Output:
B class display
1. Abstract Classes
A class that is declared with abstract keyword, is known as abstract class in java.
It can have abstract and non-abstract methods (method with body).
It needs to be extended and its method implemented.
It cannot be instantiated.
abstract class A
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
171
Java Programming 172
Output:hello
172
Java Programming 173
Object Class
The Object class is the parent class of all the classes in java by default.
Object is a superclass of all other classes. This means that a reference variable of type Object can refer to
an object of any other class.
The parent class reference variable can refer the child class object, know as upcasting.
173
Java Programming 174
Method Description
public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long causes the current thread to wait for the specified milliseconds,
timeout)throws until another thread notifies (invokes notify() or notifyAll()
InterruptedException method).
public final void wait(long causes the current thread to wait for the specified milliseconds
timeout,int nanos)throws and nanoseconds, until another thread notifies (invokes notify()
InterruptedException or notifyAll() method).
public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).
protected void finalize()throws is invoked by the garbage collector before object is being
Throwable garbage collected.
174
Java Programming 175
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. So we cannot override
this methods and rest of the methods can be overridden.
Forms of Inheritance-Specialization
Forms of Inheritance :
All objects eventually inherit from Object, which provides useful methods such as equals and toString.
Specification inheritance:
If the parent class is abstract, we often say that it is providing a specification for the child class,
and therefore it is specification inheritance (a variety of specialization inheritance).
Specialization inheritance:
The superclass just specifies which methods should be available but doesn't give code.
Construction inheritance
The superclass just specifies which methods should be available but doesn't give code.
Extension inheritance
The superclass is just used to provide behavior, but instances of the subclass don't really act like the
superclass. Violates substitutability. Exmample: defining Stack as a subclass of Vector. This is not clean
-- better to define Stack as having a field that holds a vector
If a child class generalizes or extends the parent class by providing more functionality, but does not
override any method, we call it inheritance for generalization.
175
Java Programming 176
The child class doesn't change anything inherited from the parent, it simply adds new features.
An example is Java Properties inheriting form Hashtable. subclass adds new methods, and perhaps
redefines inherited ones as well
• If a child class overrides a method inherited from the parent in a way that makes it unusable (for
example, issues an error message), then we call it inheritance for limitation.
• For example, you have an existing List data type that allows items to be inserted at either end, and
you override methods allowing insertion at one end in order to create a Stack.
• Generally not a good idea, since it breaks the idea of substitution. But again, it is sometimes found
in practice. the subclass restricts the inherited behavior. Violates substitutability. Example: defining
Queue as a subclass of Dequeue.
Combination
The child class inherits features from more than one parent class. This is multiple inheritance .
Specialization. The child class is a special case of the parent class; in other words, the child class is a
subtype of the parent class.
Specification. The parent class defines behavior that is implemented in the child class but not in the
parent class.
Construction. The child class makes use of the behavior provided by the parent class, but is not a
subtype of the parent class.
Generalization. The child class modifies or overrides some of the methods of the parent class.
Extension. The child class adds new functionality to the parent class, but does not change any inherited
behavior.
Limitation. The child class restricts the use of some of the behavior inherited from the parent class.
Variance. The child class and parent class are variants of each other, and the class-subclass relationship
is arbitrary.
176
Java Programming 177
Combination. The child class inherits features from more than one parent class. This is multiple
inheritance .
Benefits of Inheritance
Software Reuse
Code Sharing
Improved Reliability
Consistency of Interface
Rapid Prototyping
Polymorphism
Information Hiding
Cost of Inheritance
Execution speed
Program size
Message Passing Overhead
Program Complexity
This does not mean you should not use inheritance, but rather than you must understand the benefits, and
weigh the benefits against the costs.
177
Java Programming 178
UNIT-I
178
Java Programming 179
179
Java Programming 180
17.a) What are the drawbacks of procedural languages? Explain the need of object oriented
programming with suitable program.
b) Discuss the lexical issues of Java. [5+5]
18.a) What are the primitive data types in Java? Write about type conversions.
b) What is a constructor? What is its requirement in programming? Explain with program.
[5+5]
19.a) With suitable code segments illustrate various uses of ‘final’ keyword.
b) Discuss about anonymous inner classes. [5+5]
20.a) What feature of Java makes it platform independent and portable?
b) Program to find sum of given number
180