Java Programming
Java Programming
Introduction to Java
2. Class
A class is a set of objects with similar properties (attributes), common behavior
(operations), and common link to other objects. The complete set of data and code of an
object can be made a user defined data type with the help of class. The objects are variable of
type class. A class is a collection of objects of similar type. Classes are user defined data
types and work like the build in type of the programming language. Once the class has been
defined, we can make any number of objects belonging to that class. Each object is related
with the data of type class with which they are formed.
As we learned that, the classification of objects into various classes is based on its
properties (States) and behavior (methods). Classes are used to distinguish are type of object
mpm@cimdr.sangli Page 2
Java Programming
from another. The important thing about the class is to identify the properties and procedures
and applicability to its instances. The objects develop their distinctiveness from the
difference in their attribute value and relationships to other objects.
3. Data Abstraction
Data abstraction refers to the act of representing important description without
including the background details or explanations. Classes use the concept of abstraction and
are defined as a list of abstract attributes such as size, cost and functions operate on these
attributes. They summarize all the important properties of the objects that are to be created.
Classes use the concepts of data abstraction, and it is called as Abstract Data Type (ADT).
4. Data Encapsulation
Data Encapsulation means wrapping of data and functions into a single unit (i.e.
class). It is most useful feature of class. The data is not easy to get to the outside world and
only those functions which are enclosed in the class can access it. These functions provide
the boundary between Object ‘s data and program. This insulation of data from direct access
by the program is called as Data hiding.
5. Inheritance
Inheritance is the process by which objects of one class can get the properties of
objects of another class. Inheritance means one class of objects inherits the data and
behaviors from another class. Inheritance maintains the hierarchical classification in which a
class inherits from its parents. Inheritance provides the important feature of OOP that is
reusability. That means we can include additional characteristics to an existing class without
modification. This is possible deriving a new class from existing one. In other words, it is
property of object-oriented systems that allow objects to be built from other objects.
Inheritance allows openly taking help of the commonality of objects when constructing new
classes. Inheritance is a relationship between classes where one class is the parent class of
another (derived) class. The derived class holds the properties and behavior of base class in
addition to the properties and behavior of derived class.
Eg. The Santro is a part of the class Hyundai which is again part of the class car and car is
the part of the class vehicle. That means vehicle class is the parent class.
6. Polymorphism
(Poly means ―many and morph means ―form). Polymorphism means the ability to
take more than one form. Polymorphism plays a main role in allocate objects having
different internal structures to share the same external interface. This means that a general
class of operations may be accessed in the same manner even though specific activities
associated with each operation may differ. Polymorphism is broadly used in implementing
inheritance. It means objects that can take on or assume many different forms.
Polymorphism means that the same operations may behave differently on different classes.
Polymorphism as the relationship of objects towards many different classes by some
common super class. Polymorphism allows us to write generic, reusable code more easily,
because we can specify general instructions and delegate the implementation detail to the
objects involved.
mpm@cimdr.sangli Page 3
Java Programming
Eg: In a pay roll system, manager, office staff and production worker objects all will respond
to the compute payroll message, but the real operations performed are object.
7. Dynamic Binding
Dynamic Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code related with a given procedure
call is not known until the time of the call at run time. Dynamic binding is associated
polymorphism and inheritance.
Java History
Year Progress
1990 Sun decided to developed software that could be used for electronic devices.
And the project called as Green Project head by James Gosling.
1991 Announcement of a new language named ―Oak
1992 The team verified the application of their new language to manage a list of home
appliances using a hand held device.
1993 The World Wide Web appeared on the Internet and transformed the text-based
interface to a graphical rich environment.
1994 The team developed a new Web browser called ―Hot Java to locate and run Applets.
1995 Oak was renamed to Java, as it did not survive ―legal registration. Many companies
such as Netscape and Microsoft announced their support for Java.
1996 Java language is now famous for Internet programming as well as a general purpose
OO language.
1997 Sun releases Java Development Kit (JDK 1.1)
1998 Sun releases Software Development Kit (SDK 1.2)
1999 Sun releases Java 2 platform Standard Edition (J2SE) and Enterprise Edition(J2EE).
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released.
JAVA Features:
mpm@cimdr.sangli Page 4
Java Programming
3. Pure Object-oriented
Java is truly object-oriented language. In Java, almost everything is an Object. All
program code and data exist in objects and classes. Java comes with an extensive set of
classes; organize in packages that can be used in program by Inheritance. The object model
in Java is trouble-free and easy to enlarge.
5. Distributed
Java is called as Distributed language for construct applications on networks which
can contribute both data and programs. Java applications can open and access remote objects
on Internet easily. Multiple programmers from multiple remote locations can work together
on single task.
8. High performance
mpm@cimdr.sangli Page 5
Java Programming
Java performance is very extraordinary for an interpreted language, majorly due to the
use of intermediate byte code. Java architecture is also designed to reduce overheads during
runtime. The incorporation of multithreading improves the execution speed of program.
Java C++
Java is true Object-oriented language. C++ is Object-oriented extension of C.
Java does not support operator overloading. C++ supports operator overloading.
Java supports labels with loops and statement It supports go to statement.
blocks.
Java does not have template classes. C++ has template classes.
Java program is compiled into byte code for Source code can be written to be platform
the Java Virtual Machine, so this byte code is
dependent and written to take advantage of
independent on any operating system. platform C++ typically compiled into
machine code.
Java does not support multiple inheritances C++ supports multiple inheritance of classes.
of classes but it supports interface.
Java program runs in a protected C++ programs are exposes at low-level
environment i.e. JVM system facilities.
Java does not support global variable. Every C++ support global variable.
variable should declare in class.
Java does not use pointer. C++ uses pointer.
It strictly enforces an object-oriented It allows both procedural programming and
programming paradigm. object-oriented programming.
There are no header files in Java. We must use header file in C++.
As we know that all programming language compilers convert the source code to
machine code. Same job done by Java Compiler to run a Java program, but the difference is
that Java compiler convert the source code into Intermediate code is called as byte code. This
machine is called the Java Virtual machine and it exists only inside the computer memory.
Following figure shows the process of compilation.
Java Program-----Java Compiler ----- Virtual Machine
(Source Code ) (Byte Code)
mpm@cimdr.sangli Page 6
Java Programming
The Virtual machine code is not machine specific. The machine specific code is
generated by Java interpreter by acting as an intermediary between the virtual machine and
real machines shown below
Byte Code -----Java Interpreter ----- Machine Code
(Virtual Machine) (Real Machine)
JVM (Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the
one that 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.
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.
Java Object Framework act as the intermediary between the user programs and the
virtual machine which in turn act as the intermediary between the operating system and the
Java Object Framework.
mpm@cimdr.sangli Page 7
Java Programming
The fully qualified name of the loaded class and its immediate parent class.
Whether the “.class” file is related to Class or Interface or Enum.
Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file in
the heap memory. Please note that this object is of type Class predefined in java.lang
package. These Class object can be used by the programmer for getting class level
information like the name of the class, parent name, methods and variable information etc.
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 the class hierarchy. In general, there are three class loaders :
Bootstrap class loader: Every JVM implementation must have a bootstrap class
loader, capable of loading trusted classes. It loads core java API classes present in the
“JAVA_HOME/jre/lib” directory. This path is popularly known as the bootstrap path.
It is implemented in native languages like C, C++.
Extension class loader: It is a child of the bootstrap class loader. It loads the classes
present in the extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or
any other directory specified by the java.ext.dirs system property. It is implemented in
java by the sun.misc.Launcher$ExtClassLoader class.
System/Application class loader: It is a child of the extension class loader. It is
responsible to load classes from the application classpath. It internally uses
Environment Variable which mapped to java.class.path. It is also implemented in Java
by the sun.misc.Launcher$AppClassLoader class.
JVM follows the Delegation-Hierarchy principle to load classes. System class loader
delegate load request to extension class loader and extension class loader delegate request to
the bootstrap class loader. If a class found in the boot-strap path, the class is loaded
otherwise request again transfers to the extension class loader and then to the system class
mpm@cimdr.sangli Page 8
Java Programming
loader. At last, if the system class loader fails to load class, then we get run-time exception
java.lang.ClassNotFoundException.
All three JDK, JRE and JVM are interdependent and there is no common point so it is
not effective to state their difference in the tabular form however we will discuss these in
following paragraphs.
JVM: JVM is the abbreviation for Java virtual machine which is basically specification that
provides a runtime environment in which Java byte code can be executed i.e it is something
which is abstract, and its implementation is independent to choose the algorithm and has
been provided by Sun and other companies. It is JVM which is responsible for converting
Byte code to the machine specific code. It can also run those programs which are written in
other languages and compiled to Java bytecode. The JVM performs the mentioned tasks:
Loads code, Verifies code, Executes code, Provides runtime environment.
JRE: JRE is Java runtime environment which is the implementation of JVM i.e the
specifications which are defined in JVM are implemented and creates corresponding
environment for the execution of code. JRE comprises mainly java binaries and other classes
to execute the program alike of JVM it physically exists. Along with Java binaries JRE also
consist of various technologies of deployment, user interfaces to interact with code executed,
some base libraries for different functionalities and language and util based libraries.
JDK: JDK is abbreviation for Java Development Kit which includes all the tools, executable
and binaries required to compile, debug and execute a Java Program. JDK is platform
dependent i.e there is separate installers for Windows, Mac, and Unix systems. JDK includes
both JVM and JRE and is entirely responsible for code execution. It is the version of JDK
which represent version of Java.
Following are the important differences between JDK,JRE and JVM
mpm@cimdr.sangli Page 9
Java Programming
1. Method area: In the method area, all class level information like class name,
immediate parent class name, methods and variables information etc. are stored,
mpm@cimdr.sangli Page 10
Java Programming
including static variables. There is only one method area per JVM, and it is a shared
resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one
Heap Area per JVM. It is also a shared resource.
3. Stack area: For every thread, JVM creates one run-time stack which is stored here.
Every block of this stack is called activation record/stack frame which stores methods
calls. All local variables of that method are stored in their corresponding frame. After
a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared
resource.
4. PC Registers: Store address of current execution instruction of a thread. Obviously,
each thread has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores
native method information.
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into 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.
Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector,
refer Garbage Collector.
mpm@cimdr.sangli Page 11
Java Programming
class FirstProgram
{
public static void main(String[]args)
{
System.out.println(“This is my first program”);
}
}
The file must be named ―FirstProgram.java to equivalent the class name containing the
main method. Java is case sensitive. This program defines a class called ―FirstProgram. A
class is an object oriented term. It is designed to perform a specific task. A Java class is
defined by its class name, an open curly brace, a list of methods and fields, and a close curly
brace. The name of the class is made of alphabetical characters and digits without spaces, the
first character must be alphabetical. The line ―public static void main (String [] args ) shows
where the program will start running. The word main means that this is the main method –
The JVM starts running any program by executing this method first. The main method in
―FirstProgram.java consists of a single statement
For compiling and running the program we must use following commands:
a) javac (Java compiler)
In java, we can use any text editor for writing program and then save that program with
―.java extension. Java compiler converts the source code or program in bytecode and
interpreter convert ―.java file in ―.class file.
Syntax - C:\javac filename.java
If my filename is ―abc.java then the syntax will be
C:\javac abc.java
The path is required to be set for using tools such as javac, java etc. If you are saving
the java source file inside the jdk/bin directory, path is not required to be set because all the
tools will be available in the current directory. But if you are having your java file outside
the jdk/bin folder, it is necessary to set path of JDK. There are 2 ways to set java path:
temporary & permanent.
1) To set the temporary path of JDK, you need to follow following steps:
o Open command prompt
o copy the path of jdk/bin directory.
o write in command prompt: set path=copied_path
For Example: Set path=C:\Program Files\Java\jdk1.6.0_23\bin
2) For setting the permanent path of JDK, you need to follow these steps:
o Go to MyComputer properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok
Java tokens
In a Java program, all characters are grouped into symbols called tokens. Larger language
features are built from the first five categories of tokens (the sixth kind of token is
recognized, but is then discarded by the Java compiler from further processing). We must
learn how to identify all six kind of tokens that can appear in Java programs. In EBNF we
write one simple rule that captures this structure:
In a Java program, all characters are grouped into symbols called tokens. Tokens are the
various Java program elements which are identified by the compiler. A token is the smallest
element of a program that is meaningful to the compiler. When you compile a program, the
compiler scans the text in your source code and extracts individual tokens.
While tokenizing the source file, the compiler recognizes and subsequently removes white
spaces (spaces, tabs, newline and form feeds) and the text enclosed within comments. We
will examine each of these kinds of tokens in more detail below, again using EBNF.
mpm@cimdr.sangli Page 13
Java Programming
Finally, we will also examine the concept of white space which is crucial to understanding
how the Java compiler separates the characters in a program into a list of tokens; it
sometimes helps decide where one token ends and where the next token starts.
case - -A statement in the switch block can be labeled with one or more case or default
labels. The switch statement evaluates its expression, then executes all statements that follow
the matching case label; see switch.[3]
catch - Used in conjunction with a try block and an optional finally block. The statements in
the catch block specify what to do if a specific type of exception is thrown by the try block.
class - A type that defines the implementation of a particular kind of object. A class
definition defines instance and class fields, methods, and inner classes as well as specifying
the interfaces the class implements and the immediate super class of the class. If the super
class is not explicitly specified, the super class is implicitly Object. The class keyword can
also be used in the form Class.class to get a Class object without needing an instance of that
class. For example, String.class can be used instead of doing new String().getClass().
const - Although reserved as a keyword in Java, const is not used and has no function. [2][1]
For defining constants in java, see the 'final' reserved word.
continue - Used to resume program execution at the end of the current loop body. If
followed by a label, continue resumes execution at the end of the enclosing labeled loop
body.
default - The default keyword can optionally be used in a switch statement to label a block
of statements to be executed if no case matches the specified value; see switch. Alternatively,
the default keyword can also be used to declare default values in a Java annotation. From
Java 8 onwards, the default keyword is also used to specify that a method in an interface
provides the default implementation of an optional method.
mpm@cimdr.sangli Page 14
Java Programming
do - The do keyword is used in conjunction with while to create a do-while loop, which
executes a block of statements associated with the loop and then tests a boolean expression
associated with the while. If the expression evaluates to true, the block is executed again; this
continues until the expression evaluates too false.
double - The double keyword is used to declare a variable that can hold a 64-bit double
precision IEEE 754floating-point number. This keyword is also used to declare that a method
returns a value of the primitive type double.
else - The else keyword is used in conjunction with if to create an if-else statement, which
tests a boolean expression; if the expression evaluates to true, the block of statements
associated with the if are evaluated; if it evaluates to false, the block of statements associated
with the else are evaluated.[11][12]
enum (as of J2SE 5.0) - A Java keyword used to declare an enumerated type. Enumerations
extend the base class Enum.
Extends - Used in a class declaration to specify the super class; used in an interface
declaration to specify one or more super interfaces. Class X extends class Y to add
functionality, either by adding fields or methods to class Y, or by overriding methods of
class Y. An interface Z extends one or more interfaces by adding methods. Class X is said to
be a subclass of class Y; Interface Z is said to be a sub interface of the interfaces it extends.
Also used to specify an upper bound on a type parameter in Generics.
final - Define an entity once that cannot be changed nor derived from later. More
specifically: a final class cannot be sub classed, a final method cannot be overridden, and a
final variable can occur at most once as a left-hand expression. All methods in a final class
are implicitly final.
finally - Used to define a block of statements for a block defined previously by the try
keyword. The finally block is executed after execution exits the try block and any associated
catch clauses regardless of whether an exception was thrown or caught, or execution left
method in the middle of the try or catch blocks using the return keyword.
float - The float keyword is used to declare a variable that can hold a 32-bit single precision
IEEE 754 floating-point number. This keyword is also used to declare that a method returns
a value of the primitive type float.
for - The for keyword is used to create a for loop, which specifies a variable initialization, a
boolean expression, and an incrementation. The variable initialization is performed first, and
then the boolean expression is evaluated. If the expression evaluates to true, the block of
statements associated with the loop are executed, and then the incrementation is performed.
The boolean expression is then evaluated again; this continues until the expression evaluates
to false. As of J2SE 5.0, the for keyword can also be used to create a so-called "enhanced for
mpm@cimdr.sangli Page 15
Java Programming
loop", which specifies an array or Iterable object; each iteration of the loop executes the
associated block of statements using a different element in the array or Iterable.
goto - Although reserved as a keyword in Java, goto is not used and has no function.
if - The if keyword is used to create an if statement, which tests a boolean expression; if the
expression evaluates to true, the block of statements associated with the if statement is
executed. This keyword can also be used to create an if-else statement.
Implements - Included in a class declaration to specify one or more interfaces that are
implemented by the current class. A class inherits the types and abstract methods declared by
the interfaces.
Import - Used at the beginning of a source file to specify classes or entire Java packages to
be referred to later without including their package names in the reference. Since J2SE 5.0,
import statements can import static members of a class.
Instanceof - A binary operator that takes an object reference as its first operand and a class
or interface as its second operand and produces a boolean result. The instanceof operator
evaluates to true if and only if the runtime type of the object is assignment compatible with
the class or interface.
int - The int keyword is used to declare a variable that can hold a 32-bit signed two's
complement integer. This keyword is also used to declare that a method returns a value of
the primitive type int.
interface - Used to declare a special type of class that only contains abstract methods,
constant (static final) fields and static interfaces. It can later be implemented by classes that
declare the interface with the implements keyword.
long - The long keyword is used to declare a variable that can hold a 64-bit signed two's
complement integer. This keyword is also used to declare that a method returns a value of
the primitive type long.
native - Used in method declarations to specify that the method is not implemented in the
same Java source file, but rather in another language.
package - A group of types. Packages are declared with the package keyword.
private - The private keyword is used in the declaration of a method, field, or inner class;
private members can only be accessed by other members of their own class.
protected - The protected keyword is used in the declaration of a method, field, or inner
class; protected members can only be accessed by members of their own class, that class's
subclasses or classes from the same package.
mpm@cimdr.sangli Page 16
Java Programming
public - The public keyword is used in the declaration of a class, method, or field; public
classes, methods, and fields can be accessed by the members of any class.
return - Used to finish the execution of a method. It can be followed by a value required by
the method definition that is returned to the caller.
short - The short keyword is used to declare a field that can hold a 16-bit signed two's
complement integer. This keyword is also used to declare that a method returns a value of
the primitive type short.
static - Used to declare a field, method, or inner class as a class field. Classes maintain one
copy of class fields regardless of how many instances exist of that class. static also is used to
define a method as a class method. Class methods are bound to the class instead of to a
specific instance, and can only operate on class fields. (Classes and interfaces declared as
static members of another class or interface are top-level classes and are not inner classes.)
strictfp (as of J2SE 1.2) - A Java keyword used to restrict the precision and rounding of
floating point calculations to ensure portability.
super - Used to access members of a class inherited by the class in which it appears. Allows
a subclass to access overridden methods and hidden members of its superclass. The super
keyword is also used to forward a call from a constructor to a constructor in the superclass.
o Also used to specify a lower bound on a type parameter in Generics.
switch - The switch keyword is used in conjunction with case and default to create a switch
statement, which evaluates a variable, matches its value to a specific case, and executes the
block of statements associated with that case. If no case matches the value, the optional
block labelled by default is executed, if included.
synchronized - Used in the declaration of a method or code block to acquire the mutex lock
for an object while the current thread executes the code. For static methods, the object locked
is the class's Class. Guarantees that at most one thread at a time operating on the same object
executes that code. The mutex lock is automatically released when execution exits the
synchronized code. Fields, classes, and interfaces cannot be declared as synchronized.
this - Used to represent an instance of the class in which it appears. this can be used to access
class members and as a reference to the current instance. This keyword is also used to
forward a call from one constructor in a class to another constructor in the same class.
throw - Causes the declared exception instance to be thrown. This causes execution to
continue with the first enclosing exception handler declared by the catch keyword to handle
an assignment compatible exception type. If no such exception handler is found in the
current method, then the method returns, and the process is repeated in the calling method. If
no exception handler is found in any method call on the stack, then the exception is passed to
the thread's uncaught exception handler.
mpm@cimdr.sangli Page 17
Java Programming
throws - Used in method declarations to specify which exceptions are not handled within the
method but rather passed to the next higher level of the program. All uncaught exceptions in
a method that are not instances of RuntimeException must be declared using the throws
keyword.
transient - Declares that an instance field is not part of the default serialized form of an
object. When an object is serialized, only the values of its non-transient instance fields are
included in the default serial representation. When an object is deserialized, transient fields
are initialized only to their default value. If the default form is not used, e.g. when a
serialPersistentFields table is declared in the class hierarchy, all transient keywords are
ignored.
try - Defines a block of statements that have exception handling. If an exception is thrown
inside the try block, an optional catch block can handle declared exception types. Also, an
optional finally block can be declared that will be executed when execution exits the try
block and catch clauses, regardless of whether an exception is thrown or not. A try block
must have at least one catch clause or a finally block.
void - The void keyword is used to declare that a method does not return any value.
volatile - Used in field declarations to specify that the variable is modified asynchronously
by concurrently running threads. Methods, classes, and interfaces thus cannot be declared
volatile, nor can local variables or parameters.
while - The while keyword is used to create a while loop, which tests a boolean expression
and executes the block of statements associated with the loop if the expression evaluates to
true; this continues until the expression evaluates to false. This keyword can also be used to
create a do-while loop; see do.
Examples:
If you have variables that hold the name, height and weight of a person then choose
identifiers that make their purpose obvious:
String name = "Homer Jay Simpson";
int weight = 300;
double height = 6;
mpm@cimdr.sangli Page 18
Java Programming
Variables in Java
A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable. You must declare all variables before they can be used.
The basic form of a variable declaration is shown here:
datatype variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's data types and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three int , a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable is initialized with value 'a'
Local variables:
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
Local variables are implemented at stack level internally.
There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.
Instance variables:
Instance variables are declared in a class, but outside a method, constructor, or any block.
When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
mpm@cimdr.sangli Page 19
Java Programming
Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout the
class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors, and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods and different class (when instance variables are given
accessibility) should be called using the fully qualified name.
ObjectReference.VariableName.
Class/static variables:
Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final and static. Constant variables never change
from their initial value.
Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can be assigned in special static
initializer blocks.
Static variables can be accessed by calling with the class name. ClassName.VariableName.
When declaring class variables as public static final, then variables names (constants) are
all in upper case. If the static variables are not public and final the naming syntax is the same
as instance and local variables.
mpm@cimdr.sangli Page 20
Java Programming
short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there is a
concern about memory.
The default value is 0.
Example: int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
mpm@cimdr.sangli Page 21
Java Programming
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally
the default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly
in the code without any computation. Literals can be assigned to any primitive type variable.
For example: byte a = 68; char a = 'A’.
byte, int, long, and short can be expressed in decimal (base 10), hexadecimal (base 16) or
octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these
number systems for literals.
For example: int decimal = 100; int octal = 0144; int hexa = 0x64;
mpm@cimdr.sangli Page 22
Java Programming
String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes.
Examples: "Hello World" "two\nlines" "\"This is in quotes\""
String and char types of literals can contain any Unicode characters.
Example: char a = '\u0001'; String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well.
They are:
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\" Double quote
\' Single quote
\\ backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)
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
mpm@cimdr.sangli Page 23
Java Programming
Operator Description
Checks if the values of two operands are equal or not, if yes then condition
==
becomes true.
Checks if the values of two operands are equal or not, if values are not equal
!=
then condition becomes true.
Checks if the value of left operand is greater than the value of right operand, if
>
yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if yes
<
then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of right
>=
operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right
<=
operand, if yes then condition becomes true.
mpm@cimdr.sangli Page 24
Java Programming
Operator Description
Called Logical AND operator. If both the operands are non-zero, then the
&&
condition becomes true.
Called Logical OR Operator. If any of the two operands are non-zero, then the
||
condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its operand. If
!
a condition is true then Logical NOT operator will make false.
Operator Description
Simple assignment operator, Assigns values from right side operands to left side
=
operand
Add AND assignment operator, It adds right operand to the left operand and
+=
assign the result to left operand
Subtract AND assignment operator, It subtracts right operand from the left
-=
operand and assign the result to left operand
Multiply AND assignment operator, It multiplies right operand with the left
*=
operand and assign the result to left operand
Divide AND assignment operator, It divides left operand with the right operand
/=
and assign the result to left operand
Modulus AND assignment operator, It takes modulus using two operands and
%=
assign the result to left operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
mpm@cimdr.sangli Page 25
Java Programming
Misc Operators
There are few other operators supported by Java Language.
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:
variable x = (expression) ? value if true : value if false
Following is the example:
public classTest
{
public static void 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 );
}
}
This would produce the following result:
Value of b is : 30
Value of b is : 20
Instance of 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 wriiten
as:
( Object reference variable ) instanceof (class/interface type)
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
the example:
class Test
{
public static void main(String args[])
{
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
mpm@cimdr.sangli Page 26
Java Programming
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:
class Vehicle {}
public class Car extends Vehicle
{
public static void main(String args[])
{
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
This would produce the following result:true
mpm@cimdr.sangli Page 27
Java Programming
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will
be executed. If not the first set of code after the end of the if statement (after the closing
curly brace) will be executed.
Example:
class Test
{
public static void main(String args[])
{
int x = 10;
if( x < 20 )
{
System.out.print("This is if statement");
}
}
}
//Example:
class Test
{
mpm@cimdr.sangli Page 28
Java Programming
Syntax:
The syntax of an if...else is:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example:
class Test
{
public static void main(String args[])
{
int x = 30;
if( x == 10 )
{
mpm@cimdr.sangli Page 29
Java Programming
System.out.print("Value of X is 10");
}
else if( x == 20 )
{
System.out.print("Value of X is 20");
}
else if( x == 30 )
{
System.out.print("Value of X is 30");
}
Else
{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
Value of X is 30
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:
X = 30 and Y = 10
mpm@cimdr.sangli Page 30
Java Programming
case 'B' :
case 'C' :
mpm@cimdr.sangli Page 31
Java Programming
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
OUTPUT
$ java Test
Well done
Your grade is a C
$
There may be a situation when we need to execute a block of code several number of
times, and is often referred to as a loop. Java has very flexible three looping mechanisms.
You can use one of the following three loops:
while Loop
do...while Loop
for Loop
When executing, if the boolean_expression result is true, then the actions inside the
loop will be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Example:
class Test
{
public static void main(String args[])
mpm@cimdr.sangli Page 32
Java Programming
{
int x = 10;
while( x < 20 )
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
Notice that the Boolean expression appears at the end of the loop, so the statements in the
loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of
control jumps back up to do, and the statements in the loop execute again. This process
repeats until the Boolean expression is false.
Example:
class Test
{
public static void main(String args[])
{
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
mpm@cimdr.sangli Page 33
Java Programming
Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control jumps
to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the
update statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the Boolean
expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After
the Boolean expression is false, the for loop terminates.
Example:
class Test
{
public static void main(String args[])
{
for(int x = 10; x < 20; x = x+1)
{
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
mpm@cimdr.sangli Page 34
Java Programming
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names )
{
System.out.print( name );
System.out.print(",");
}
}
}
This would produce the following result:
10,20,30,40,50,
James,Larry,Tom,Lacy,
mpm@cimdr.sangli Page 35
Java Programming
The break Keyword: The break keyword is used to stop the entire loop. The break keyword
must be used inside any loop or a switch statement. The break keyword will stop the
execution of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
10
20
The continue Keyword: The continue keyword can be used in any of the loop control
structures. It causes the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{ continue;}
System.out.print( x );
System.out.print("\n");
}
mpm@cimdr.sangli Page 36
Java Programming
}
}
This would produce the following result:
10
20
40
50
Java is an Object-Oriented Language. As a language that has the Object Oriented feature,
Java supports the following fundamental concepts: Polymorphism, Inheritance,
Encapsulation, Abstraction, Classes, Objects, Instance, Method, Message Passing, etc. A
class is a blue print from which individual objects are created. A sample of a class is given
below:
class Dog
{
String breed;
int age;
String color;
void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}
A class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
Objects in Java:
An object is an instance of a class created using a new operator. The new operator
returns a reference to a new instance of a class. This reference can be assigned to a reference
variable of the class. The process of creating objects from a class is called instantiation. An
object encapsulates state and behavior. An object reference provides a handle to an object
mpm@cimdr.sangli Page 37
Java Programming
that is created and stored in memory. In Java, objects can only be manipulated via references,
which can be stored in variables. Creating variables of your class type is similar to creating
variables of primitive data types, such as integer or float. Each time you create an object, a
new set of instance variables comes into existence which defines the characteristics of that
object. If you want to create an object of the class and have the reference variable associated
with this object, you must also allocate memory for the object by using the new operator.
This process is called instantiating an object or creating an object instance. When you create
a new object, you use the new operator to instantiate the object. The new operator returns the
location of the object which you assign a reference type.
class Cube
{
int length = 10;
int breadth = 10;
int height = 10;
Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an
object is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
//Example of creating an object is given below:
class Puppy
{
public Puppy(String name)
{
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
mpm@cimdr.sangli Page 38
Java Programming
If we compile and run the above program, then it would produce the following result:
Passed Name is :tommy
Instance variables and methods are accessed via created objects. To access an instance
variable the fully qualified path should be as follows:
/* First create an object */
Object Reference = new Constructor();
Example:
This example explains how to access instance variables and methods of a class:
class Puppy
{
int puppyAge;
}
}
If we compile and run the above program, then it would produce the following result:
Passed Name is: Tommy
Puppy's age is: 2
Variable Value: 2
Constructors in Java
Constructor in java is a special type of method that is used to initialize the object. Java
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. When discussing about classes, one of
the most important subtopic would be constructors. Every class has a constructor. If we do
not explicitly write a constructor for a class, the Java compiler builds a default constructor
for that class.
mpm@cimdr.sangli Page 40
Java Programming
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n)
{
id = i;
name = n;
}
mpm@cimdr.sangli Page 41
Java Programming
Each time a new object is created, at least one constructor will be invoked. The main
rule of constructors is that they should have the same name as the class. A class can have
more than one constructor. Java also supports Singleton Classes where you would be able to
create only one instance of a class.
Java Copy Constructor: There is no copy constructor in java. But we can copy the values
of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
Java has its own garbage collection implementation, so it does not require any
destructor like C++. This makes Java developer lazy in implementing memory management.
Still we can have destructor along with garbage collector where developer can free resources
and which can save garbage collector's work.
The finalize() method is equivalent to a destructor of C++. When the job of an object
is over, or to say, the object is no more used in the program, the object is known as garbage.
The process of removing the object from a running program is known as garbage
collection. Garbage collection frees the memory and this memory can be used by other
mpm@cimdr.sangli Page 42
Java Programming
programs or the same program further in its execution. Before an object is garbage collected,
the JRE (Java Runtime Environment) calls the finalize() method. finalize() method can be
best utilized by the programmer to close the I/O streams, JDBC connections or socket
handles etc.
//Example of destructor
public class Thing
{
public static int number_of_things = 0;
public String what;
These rules are essential when declaring classes, import statements and package statements
in a source file.
There can be only one public class per source file.
A source file can have multiple non public classes.
The public class name should be the name of the source file as well which should be
appended by .java at the end. For example : The class name is . public class
Employee{} Then the source file should be as Employee.java.
mpm@cimdr.sangli Page 43
Java Programming
If the class is defined inside a package, then the package statement should be the first
statement in the source file.
If import statements are present then they must be written between the package
statement and the class declaration. If there are no package statements then the import
statement should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It
is not possible to declare different import and/or package statements to different
classes in the source file.
Classes have several access levels and there are different types of classes; abstract classes,
final classes, etc. Apart from the above mentioned types of classes, Java also has some
special classes called Inner classes and Anonymous classes.
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 a string object. The Java String is
immutable which means it cannot be changed. Whenever we change any string, a new
instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
Java String class provides a lot of methods to perform operations on strings such as
compare (), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
Creating a String
class StringExample
{
public static void main (String args[])
{
String s1="java";//creating string by Java string literal
char ch[]={'C','I','M','D','R'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
mpm@cimdr.sangli Page 44
Java Programming
String: It is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created.
StringBuffer is a peer class of String that provides much of the functionality of strings. The
string represents fixed-length, immutable character sequences while StringBuffer represents
growable and writable character sequences.
StringBuilder in Java represents a mutable sequence of characters. Since the String Class in
Java creates an immutable sequence of characters, the StringBuilder class provides an
alternative to String Class, as it creates a mutable sequence of characters.
Example:
mpm@cimdr.sangli Page 45
Java Programming
Java programming language comes up with a huge list of string manipulations functions we
can use as per our business requirements. We can manipulate a string in many ways. Given
below are the different ways for manipulating a string:
1. String concatenations: Suppose we have two strings in separate. We want these two
strings to be concatenated in one. For this, we can simply use the traditional one (the +
operator).
String str1= "Hello";
String str2 = "India";
String finalResult = str1+" "+str2;
2.Changing the given string’s case: We can change the case of the string whenever
required by using toLowerCase() and the toUpperCase() Java built-in functions.
3.Sub-string inside a string: we have a Contain() method in Java to deal with the checking
of the string inside a string. We can use this function to check with some sequence of
characters in a defined string. We can also use the substring() of Java.
4.Cleaning the string with the unwanted character: For this, we can use the Java trim()
function. This function can be used to remove the space from the beginning and the end of
the given string.
5. String reverse: String reverse is again the part of string manipulation. This is all about
getting the string from the last index to the first index. For example, we have “Hello world!”,
the reverse of this string will be “!dlroW olleH”.
Syntax:
1. toLowerCase(): public String toLowerCase();
mpm@cimdr.sangli Page 46
Java Programming
This function changes the case of the given string to the lower case. We can use this function
at the time of string to handle the ignore case with the compareTo() function itself.
Example #2: String concatenation – We will be using the + operator to handle this.
Code:
public class StrConcat {
public static void main(String[] args) {
String str1= "Hello";
String str2 = "World";
String result = str1+" "+str2;
System.out.print(result);
}
}
mpm@cimdr.sangli Page 47
Java Programming
Example #3 Get the length of the string and printing it character by character in
reverse order.
After having the length, we can read the string character by character from the string’s last position to the 0
position of the string. In other words, we will see the string reverse of the given string.
Code:
public class StrLenght {
public static void main(String[] args) {
String str1= "Hello World!";
System.out.println("The length of the string: "+ str1.length());
System.out.println("Actual String: "+str1);
System.out.print("String reverse: ");
for(int i = str1.length()-1; i>=0; i--){
System.out.print(str1.charAt(i));
}
}
}
Arrays in Java
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array. Array in
Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on. In Java, array is an object of a dynamically generated class.
Java array inherits the Object class, and implements the Serializable as well as Cloneable
interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can
also create single dimentional or multidimentional arrays in Java. Moreover, Java provides
the feature of anonymous arrays which is not available in C/C++.
mpm@cimdr.sangli Page 48
Java Programming
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java which
grows automatically.
Java cannot store heterogeneous data. It can only store a single type of primitives
Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of the
program. These are:
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row. For example:
In this example, we have an array of five elements. They are stored in a single line or
adjacent memory locations.
Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We use a for
loop to print the elements of the array. The output of this is as follows:
mpm@cimdr.sangli Page 49
Java Programming
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:
In this, the array has two rows and five columns. The index starts from 0,0 in the left-upper
corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three columns.
Brackets separate the rows, and the number of elements separates the columns. For this, we
use two for loops: one for rows and one for each element in the row. When we execute this
program, the result will be as follows:
3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more than
two rows and columns using the following code:
mpm@cimdr.sangli Page 50
Java Programming
Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will always
be two.
mpm@cimdr.sangli Page 51
Java Programming
Subclasses inherit public methods from the superclass that they extend, but they
cannot access the private instance variables of the superclass directly and must use the public
accessor and mutator methods. And subclasses do not inherit constructors from the
superclass.
A subclass inherits all members of its superclass not designated as private. As we will
discuss shortly, other levels of visibility affect which inherited members of the class can be
seen from outside of the class and its subclasses, but at a minimum, a subclass always has the
same set of visible members as its parent. For this reason, the type of a subclass can be
considered a subtype of its parent, and instances of the subtype can be used anywhere
instances of the supertype are allowed.
Concept of Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. The idea behind inheritance in java is that you can create new
classes that are built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance can be defined as the process where one object acquires the properties of
another. With the use of inheritance, the information is made manageable in a hierarchical
order. The most used keyword would be extends and implements. These words would
determine whether one object IS-A type of another. By using these keywords, we can make
one object acquire the properties of another object.
mpm@cimdr.sangli Page 52
Java Programming
Types of Inheritance:
1) Single Inheritance
Single inheritance is simple & easy to understand. When a class extends another
one class only then we call it a single inheritance. The below flow diagram shows
that class B extends only one class which is A. Here A is a parent class of B and B
would be a child class of A.
Single inheritance is easy to understand. When a class extends another one class only then
we call it a single inheritance. The below flow diagram shows that class B extends only one
class which is A. Here A is a parent class of B and B would be a child class of A.
Class B extends A
{
Public void methodB()
{
System.out.println("Child class method");
}
Public static void main(String args[])
{
B obj =new B();
obj.methodA();//calling super class method
obj.methodB();//calling local method
}
}
2) Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with “multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.
mpm@cimdr.sangli Page 53
Java Programming
3) Multilevel Inheritance
Class Y extends X
{
publicvoid methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
publicvoid methodZ()
{
System.out.println("class Z method");
}
Public static void main(String args[])
{
Z obj =new Z();
obj.methodX();//calling grand parent class method
obj.methodY();//calling parent class method
obj.methodZ();//calling local method
}
}
4) Hierarchical Inheritance
mpm@cimdr.sangli Page 54
Java Programming
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a
combination of Single and Multiple inheritances. A typical
flow diagram would look like below. A hybrid inheritance can
be achieved in the java in a same way as multiple inheritance
i.e. using interfaces. By using interfaces you can have multiple
as well as hybrid inheritance in Java.
Interfaces- definition
mpm@cimdr.sangli Page 55
Java Programming
The java compiler adds public and abstract keywords before the interface method and
public, static and final keywords before data members, i.e. Interface fields are public,
static and final by default, and methods are public and abstract.
interface printable
{
void print();
}
Output:Hello
mpm@cimdr.sangli Page 56
Java Programming
interface Printable
{
void print();
}
interface Showable
{
void show();
}
interface Printable
{
void print();
}
interface Showable
{
void print();
}
mpm@cimdr.sangli Page 57
Java Programming
As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class A, so there is no ambiguity.
Interface inheritance: A class implements interface but one interface extends another
interface .
interface Printable
{
void print();
}
mpm@cimdr.sangli Page 58
Java Programming
Nested Interface in Java: An interface can have another interface i.e. known as
nested interface. For example:
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}
Polymorphism in Java
Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to refer to a child
class object. Any Java object that can pass more than one IS-A test is considered to be
polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A
test for their own type and for the class Object. It is important to know that the only possible
way to access an object is through a reference variable. A reference variable can be of only
one type. Once declared, the type of a reference variable cannot be changed. The reference
variable can be reassigned to other objects provided that it is not declared final. The type of
the reference variable would determine the methods that it can invoke on the object. A
reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
Polymorphism in java is a concept by which we can perform a single action by
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. There
are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding. If you overload static method in java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
mpm@cimdr.sangli Page 59
Java Programming
class A{}
class B extends A{}
A a=new B();//upcasting
class Bike
{
void run(){System.out.println("running");}
}
Consider a scenario, BCA is a class that provides method to get the attendance of studentst.
But, attendance may differ according to respective classes, like BCAI, BCAII and BCAIII
banks could provide 80%, 70% and 90% attendance.
It is also given in method overriding but there was no upcasting.
class BCA
{
int getAttendance(){return 0;}
}
mpm@cimdr.sangli Page 60
Java Programming
class Test3
{
public static void main(String args[])
{
BCA b1=new BCAI();
BCA b2=new BCAII();
BCA b3=new BCAIII();
Output:
BCA I Attendance : 80
BCA II Attendance : 70
BCA III Attendance : 90
class Bike
{
int speedlimit=90;
}
mpm@cimdr.sangli Page 61
Java Programming
Output:90
Output: eating
eating fruits
drinking Milk
class Animal
{
void eat(){System.out.println("animal is eating...");}
}
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is
invoked.
Method Overloading is a feature that allows a class to have two or more methods
having same name, if their argument lists are different. If a class have multiple methods by
same name but different parameters, it is known as Method Overloading. If we have to
perform only one operation, having same name of the methods increases the readability of
the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So, we
perform method overloading to figure out the program quickly.
Advantage of method overloading is it increases the readability of the program.
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity. Let's see how ambiguity may occur:
class Calculation3
{int sum(int a, int b){System.out.println(a+b);}
double sum(int a, int b){System.out.println(a+b);}
public static void main(String args[])
{
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error
}
}
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java. In other words, If subclass provides the specific
implementation of the method that has been provided by one of its parent class, it is known
as method overriding.
Example :
class Vehicle
{ void run(){System.out.println("Vehicle is running");} }
mpm@cimdr.sangli Page 64
Java Programming
It occurs within same class. It occurs within different classes’ i.e. super
class & sub class.
Inheritance is not needed. It can be explained only with inheritance.
One method does not hide another. Child class method hides parent class
method.
Parameters should differ either in number or Parameters must be same in numbers & data
data types. types.
Return type may or may not be same. Return type must be same.
Polymorphism is not applicable. Polymorphism is applicable.
It is compile time concept. It is run time concept.
mpm@cimdr.sangli Page 65
Java Programming
Abstract Method: A method that is declared as abstract and does not have
implementation is known as abstract method
abstract void printStatus();//no body and abstract
class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of PNB will be inv
oked
int interest=b.getRateOfInterest();
System.out.println("Rate of Interest is: "+interest+" %");
}
}
mpm@cimdr.sangli Page 67
Java Programming
{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
O/p :
bike is created
running safely..
gear changed
interface A
{
void a();
void b();
void c();
void d();
}
class M extends B
{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5
{
public static void main(String args[])
{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
mpm@cimdr.sangli Page 68
Java Programming
}
Output:I am a
I am b
I am c
I am d
Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. Another way to think about
encapsulation is, that it is a protective shield that prevents the data from being accessed by
the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other
class and can be accessed only through any member function of its own class in which
it is declared.
As in encapsulation, the data in a class is hidden from other classes using the data
hiding concept which is achieved by making the members or methods of a class
private, and the class is exposed to the end-user or the world without providing any
details behind implementation using the abstraction concept, so it is also known as a
combination of data-hiding and abstraction.
Encapsulation can be achieved by Declaring all the variables in the class as private
and writing public methods in the class to set and get the values of variables.
It is more defined with the setter and getter method.
mpm@cimdr.sangli Page 69
Java Programming
Advantages of Encapsulation:
Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding. The user
will have no idea about the inner implementation of the class. It will not be visible to
the user how the class is storing values in the variables. The user will only know that
we are passing the values to a setter method and variables are getting initialized with
that value.
Increased Flexibility: We can make the variables of the class read-only or write-only
depending on our requirement. If we wish to make the variables read-only then we
have to omit the setter methods like setName(), setAge(), etc. from the above program
or if we wish to make the variables write-only then we have to omit the get methods
like getName(), getAge(), etc. from the above program
Reusability: Encapsulation also improves the re-usability and is easy to change with
new requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
int length;
int breadth;
class Encp
mpm@cimdr.sangli Page 70
Java Programming
{
public static void main(String[] args)
{
Area rectangle = new Area(2, 16);
rectangle.getArea();
}
}
For example:
Getter and Setter in Java are two conventional methods used to retrieve and update values
of a variable. They are mainly used to create, modify, delete and view the variable values.
The setter method is used for updating values and the getter method is used for reading or
retrieving the values. They are also known as an accessor and mutator. The following code is
an example of getter and setter methods:
class Account{
private int account_number;
private int account_balance;
// getter method
mpm@cimdr.sangli Page 71
Java Programming
mpm@cimdr.sangli Page 72
Java Programming
Packages in Java
Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
A Package can be defined as a grouping of related types(classes, interfaces,
enumerations and annotations ) providing access protection and name space management.
Programmers can define their own packages to bundle group of classes/interfaces, etc. It
is a good practice to group related classes implemented by you so that a programmer can
easily determine that the classes, interfaces, enumerations, annotations are related. Since the
package creates a new namespace there won't be any name conflicts with names in other
packages. Using packages, it is easier to provide access control and it is also easier to locate
the related classes.
Creating a package:
When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package. The package
statement should be the first line in the source file. There can be only one package statement
in each source file, and it applies to all types in the file. If a package statement is not used
then the class, interfaces, enumerations, and annotation types will be put into an unnamed
package.
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Java package provides access protection.
Java package removes naming collision.
Example:
Let us look at an example that creates a package called animals. It is common practice
to use lowercased names of packages to avoid any conflicts with the names of classes,
interfaces.
mpm@cimdr.sangli Page 73
Java Programming
interface Animal
{
public void eat();
public void travel();
}
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).
To run java package program, you need to use fully qualified name e.g. mypack.Simple
etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
To access package from another package, there are three ways to access the package from
outside the package.
import package.*;
import package.classname;
fully qualified name. i.e. Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages. The import keyword is used to make the classes and interface of
another package accessible to the current package.
mpm@cimdr.sangli Page 74
Java Programming
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible. Example of package by import package.classname
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
mpm@cimdr.sangli Page 75
Java Programming
have same class name e.g. java.util and java.sql packages contain Date class. Example of
package by import fully qualified name
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Subpackage in java
package com.javatpoint.core;
class Simple
{
public static void main(String args[])
mpm@cimdr.sangli Page 76
Java Programming
{
System.out.println("Hello subpackage");
}
}
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:e:\sources> javac -d c:\classes Simple.java
To Run:To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
Another way to run this program by -classpath switch of java:
There are two ways to load the class files temporary and permanent.
Temporary
By setting the classpath in the command prompt
By -classpath switch
Permanent
By setting the classpath in the environment variables
By creating the jar file, that contains all the class files, and copying the jar file in
the jre/lib/ext folder.
//save as A.java
package javatpoint;
public class A{}
//save as B.java
package javatpoint;
public class B{}
mpm@cimdr.sangli Page 77
Java Programming
Package class
The package class provides methods to get information about the specification and
implementation of a package. It provides methods such as getName(),
getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.
Example of Package class
class PackageInfo
{
public static void main(String args[])
{
Package p=Package.getPackage("java.lang");
System.out.println("package name: "+p.getName());
System.out.println("Specification Title: "+p.getSpecificationTitle());
System.out.println("Specification Vendor: "+p.getSpecificationVendor());
System.out.println("Specification Version: "+p.getSpecificationVersion());
System.out.println("Implementaion Title: "+p.getImplementationTitle());
System.out.println("Implementation Vendor: "+p.getImplementationVendor());
System.out.println("Implementation Version: "+p.getImplementationVersion());
System.out.println("Is sealed: "+p.isSealed());
}
}
Output:
package name: java.lang
Specification Title: Java Platform API Specification
Specification Vendor: Sun Microsystems, Inc.
Specification Version: 1.6
Implementation Title: Java Runtime Environment
Implementation Vendor: Sun Microsystems, Inc.
Implementation Version: 1.6.0_30
IS sealed: false
Multithreading in Java
Benefits of Threads
1. Threads are lightweight compared to processes; it takes less time and resource to create a
thread.
mpm@cimdr.sangli Page 78
Java Programming
A thread goes through various stages in its life cycle. For example, a thread is born,
started, runs, and then dies. Following diagram shows complete life cycle of a thread.
The thread scheduler's job is to move threads in and out of the running state. While the
thread scheduler can move a thread from the running state back to runnable, other factors can
cause a thread to move out of running, but notback to runnable. One of these is when the
thread's run()method completes, inwhich case the thread moves from the running state
directly to the dead state.
New/Start: This is the state the thread is in after the Thread instance has been created, but
the start() method has not been invoked on the thread. It is a live Thread object, but not yet a
thread of execution. At this point, the thread is considered not alive.
Runnable: This means that a thread can be run when the time-slicing mechanism has CPU
cycles available for the thread. Thus, the thread might or might not be running at any
moment, but there’s nothing to prevent it from being run if the scheduler can arrange it. That
is, it’s not dead or blocked.
Running: This state is important state where the action is. This is the state a thread is in
when the thread scheduler selects it (from the runnable pool) to be the currently executing
process. A thread can transition out of a running state for several reasons, including because
"the thread scheduler felt like it". There are several ways to get to the runnable state, but only
one way to get to the running state: the scheduler chooses a thread from the runnable pool of
thread.
mpm@cimdr.sangli Page 79
Java Programming
Waiting / Blocked: The thread can be run, but something prevents it. While a thread is in the
blocked state, the scheduler will simply skip it and not give it any CPU time. Until a thread
reenters the runnable state, it won’t perform any operations. Blocked state has some sub
states as below,
Blocked on I/O: The thread waits for completion of blocking operation. A thread can
enter on this state because of waiting I/O resource. In that case the thread sends back
to runnable state after availability of resources.
Blocked for join completion: The thread can come on this state because of waiting
the completion of another thread.
Blocked for lock acquisition: The thread can come on this state because of waiting to
acquire the lock of an object.
Dead: A thread in the dead or terminated state is no longer schedulable and will not receive
any CPU time. Its task is completed, and it is no longer runnable. One way for a task to die is
by returning from its run( ) method, but a task’s thread can also be interrupted, as you’ll see
shortly.
This example doesn't specify any code for the thread to execute. The thread will stop again
right away after it is started.
There are two ways to specify what code the thread should execute. The first is to create a
subclass of Thread and override the run() method. The second method is to pass an object
that implements Runnable
Thread class: Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements Runnable
interface. Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r, String name)
Blocking Tread
A thread may be blocked because
mpm@cimdr.sangli Page 80
Java Programming
2) It is suspended with a call to suspend() and will be blocked until a resume() message
3) The thread is suspended by call to wait(), and will become runnable on a notify or notify
all message.
Stopping a thread
Firstly, the thing you shouldn't do is call Thread.stop(). This method, now deprecated, was
intended to stop a given thread abruptly. But the problem with this is that the caller can't
generally determine whether or not the given thread is at a safe point to be stopped. (This
isn't just a Java phenomenon: in general, the underlying operating system calls
that Thread.stop() makes to abruptly stop the thread are also deprecated for this reason.)
mpm@cimdr.sangli Page 81
Java Programming
{
stopRequested = true;
}
Note that we must declare the stopRequested variable as volatile, because it is accessed by
different threads.
Tread Methods
We have various methods which can be called on Thread class object. These methods are
very useful when writing multithreaded application. Thread class have following important
methods. We will understand various thread states as well later in this tutorial.
Method Description
Signature
void start() This method will start new thread of execution by calling run()
method of Thread/runnable object.
void run() This method is entry point of thread. Execution of thread starts from
this method.
void sleep(int This method suspend thread for mentioned time duration in argument
sleeptime) (sleeptime in ms)
void yield() By invoking this method the current thread pause its execution
temporarily and allow other threads to execute.
void join() This method used to queue up thread in execution. Once called on
thread, current thread will wait till calling thread completes its
execution
mpm@cimdr.sangli Page 82
Java Programming
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses. 3 constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Exception Handling
An Exception can be anything which interrupts the normal flow of the program. When
an exception occurs program processing gets terminated and doesn’t continue further. In
such cases we get a system generated error message. The good thing about exceptions is that
they can be handled. Exception can occur at runtime (known as runtime exceptions) as well
as at compile-time (known Compile-time exceptions).
There can be several reasons for an exception. For example, following situations can
cause an exception – Opening a non-existing file, Network connection problem, Operands
mpm@cimdr.sangli Page 83
Java Programming
being manipulated are out of prescribed ranges, class file missing which was supposed to be
loaded and so on.
Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –
DivideByZeroException
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java try block is used to enclose the code that might throw an exception. It must be
used within the method. Java try block must be followed by either catch or finally block.
Syntax of java try-catch
Try
{
mpm@cimdr.sangli Page 84
Java Programming
catch (ArithmeticException e)
{System.out.println("ArithmeticException caught");}
finally
{System.out.println("Outer finally");}
}
}
The output is
Outer try block starts
Inner try block starts
Inner final
ArithmeticException caught
Outer finally Outer finally
mpm@cimdr.sangli Page 85
Java Programming
In this example, one try catch finally sequence has been nested within another try
catch finally sequence. The inner try block throws an ArithmeticException which it could not
handle. Hence, this exception is rethrown by the inner block which is handled in the outer
finally block. Note that all the finally blocks that come in the way of the program are excited.
Such nesting of try catch blocks can also occur in case of method calls.
Nesting may not be very explicit in such cases. Look at the following example which
contains two methods main() and meth(). Both the methods have exception handlers. meth()
is invoked from the method main(). The try block in meth() throws an ArithmeticException
which it could not handle. Hence, it is rethrown. This try catch sequence of meth() in nested
within the try catch sequence of main() by way of method call. Therefore, the exception is
processed by the finally block of the main() method.
Finally in meth
ArithmeticException caught
Outer finally
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
mpm@cimdr.sangli Page 87
Java Programming
Output:task1 completed
rest of the code...
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class TestMultipleCatchBlock1
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2
completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
finally block
The finally block always executes when the try block exits. This ensures that
the finally block is executed even if an unexpected exception occurs. But finally is useful for
more than just exception handling it allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block
is always a good practice, even when no exceptions are anticipated.
If the JVM exits while the try or catch code is being executed, then the finally block
may not execute. Likewise, if the thread executing the try or catch code is interrupted or
killed, the finally block may not execute even though the application as a whole continues.
The try block of the writeList method that you've been working with here opens
a PrintWriter. The program should close that stream before exiting the writeList method.
This poses a somewhat complicated problem because writeList's try block can exit in one of
three ways.
1. The new FileWriter statement fails and throws an IOException.
2. The list.get(i) statement fails and throws an IndexOutOfBoundsException.
3. Everything succeeds and the try block exits normally.
The runtime system always executes the statements within the finally block regardless of
what happens within the try block. So it's the perfect place to perform cleanup.
mpm@cimdr.sangli Page 88
Java Programming
The following finally block for the writeList method cleans up and then closes
the PrintWriter.
Finally
{
if (out! = null)
{
System.out.println("Closing PrintWriter");
out.close();
}
else
{
System.out.println("PrintWriter not open");
}
}
Important: The finally block is a key tool for preventing resource leaks. When closing a file
or otherwise recovering resources, place the code in a finally block to ensure that resource is
always recovered.
Throwable classes
The Throwable class is the superclass of all errors and exceptions in the Java
language. Only objects that are instances of this class (or one of its subclasses) are thrown by
the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this
class or one of its subclasses can be the argument type in a catch clause. For the purposes of
compile-time checking of exceptions, Throwable and any subclass of Throwable that is not
also a subclass of either RuntimeException or Error are regarded as checked exceptions.
Instances of two subclasses, Error and Exception, are conventionally used to indicate
that exceptional situations have occurred. Typically, these instances are freshly created in the
context of the exceptional situation so as to include relevant information (such as stack trace
data).
A second reason that a throwable may have a cause is that the method that throws it
must conform to a general-purpose interface that does not permit the method to throw the
cause directly. For example, suppose a persistent collection conforms to
the Collection interface, and that its persistence is implemented atop java.io. Suppose the
internals of the add method can throw an IOException. The implementation can
communicate the details of the IOException to its caller while conforming to
the Collection interface by wrapping the IOException in an appropriate unchecked
exception. (The specification for the persistent collection should indicate that it can throw
such exceptions.)
A cause can be associated with a throwable in two ways: via a constructor that takes
the cause as an argument, or via the initCause(Throwable) method. New throwable classes
that wish to allow causes to be associated with them should provide constructors that take a
cause and delegate (perhaps indirectly) to one of the Throwable constructors that takes a
cause. Because the initCause method is public, it allows a cause to be associated with any
mpm@cimdr.sangli Page 89
Java Programming
throwable, even a "legacy throwable" whose implementation predates the addition of the
exception chaining mechanism to Throwable.
By convention, class Throwable and its subclasses have two constructors, one that
takes no arguments and one that takes a String argument that can be used to produce a detail
message. Further, those subclasses that might likely have a cause associated with them
should have two more constructors, one that takes a Throwable (the cause), and one that
takes a String (the detail message) and a Throwable (the cause).
A Throwable class contains a snapshot of the execution stack of its thread at the time
it was created. It can also contain a message string that gives more information about the
error.
Here is one example of catching an exception:
try
{
int a[] = new int[2];
a[4];
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
}
throws keyword
mpm@cimdr.sangli Page 90
Java Programming
throw transfers control to caller throws suggest for information and compiler
checking.
throw keyword is used to throw an exception throws keyword is used to declare one or
explicitly. more exceptions, separated by commas.
Multiple exceptions can be thrown by using
throws.
Only single exception is thrown by using
e.g.
throw.
public void method()throws
IOException,SQLException.
throws keyword is used with the method
throw keyword is used within the method.
signature.
Syntax wise throw keyword is followed by Syntax wise throws keyword is followed by
the instance variable. exception class names.
Checked exception cannot be propagated For the propagation checked exception must
using throw only. Unchecked exception can use throws keyword followed by specific
be propagated using throw. exception class name.
this keyword
this keyword can be used to refer current class instance variable. this() can be used to
invoke current class constructor. this keyword can be used to invoke current class method
(implicitly) this can be passed as an argument in the method call. this can be passed as
argument in the constructor call. this keyword can also be used to return the current class
instance.
//example of this keyword
class Student11
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
mpm@cimdr.sangli Page 91
Java Programming
}
}
Final Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
mpm@cimdr.sangli Page 93
Java Programming
final parameter
class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}
The super keyword in java is a reference variable that is used to refer immediate
parent class object.Whenever you create the instance of subclass, an instance of parent class
is created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
int speed=50;
}
class Bike3 extends Vehicle
{
int speed=100;
void display()
{
System.out.println(speed);//will print speed of Bike
}
void display()
{
System.out.println(super.speed);//will print speed of Vehicle no
w
}
{
Bike5()
{
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement.If you are creating your own constructor and you don't
have either this() or super() as the first statement, compiler will provide super() as the first
statement of the constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
class Vehicle
{
Vehicle(){System.out.println("Vehicle is created");}
}
mpm@cimdr.sangli Page 96
Java Programming
void display()
{
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not
of Person class because priority is given to local. In case there is no method in subclass as
parent, there is no need to use super. In the example given below message() method is
invoked from Student class but Student class does not have message() method, so you can
directly call message() method
mpm@cimdr.sangli Page 97
Java Programming
Apart from being platform-dependent, there are several other features of AWT classes about
which I will be talking in the next section of this Java AWT Tutorial.
AWT UI Aspects
Any UI will be made of three entities:
UI elements: These refers to the core visual elements which are visible to the user and
used for interacting with the application. AWT in Java provides a comprehensive list
of widely used and common elements.
Layouts: These define how UI elements will be organized on the screen and provide
the final look and feel to the GUI.
Behavior: These define the events which should occur when a user interacts with UI
elements.
mpm@cimdr.sangli Page 98
Java Programming
Hierarchy of AWT
Component is the superclass of all the GUI controls. It is an abstract class which
encapsulates all the attributes of a visual component and represents an object with graphical
representation. A component class instance is basically responsible for the look and feel of
the current interface. A component is an object with a graphical representation that can be
displayed on the screen and is allowed to interact with the user. The Component class is the
abstract parent of the non-menu-related AWT components. The prime AWT Components
are:
AWT Components
1. Containers
Container in Java AWT is a component that is used to hold other components such as text
fields, buttons, etc. It is a subclass of java.awt.Component and is responsible for keeping a
track of components being added. There are four types of containers provided by AWT in
Java.
Types of Containers
1. Window: It is an instance of the Window class having neither border nor title. It is
used for creating a top-level window.
2. Frame: Frame is a subclass of Window and contains title, border and menu bars. It
comes with a resizing canvas and is the most widely used container for developing
AWT applications. It can hold various components such as buttons, text fields,
scrollbars, etc. You can create a Java AWT Frame in two ways:
i. By Instantiating Frame class
ii. By extending Frame class
mpm@cimdr.sangli Page 99
Java Programming
3. Dialog: Dialog class is also a subclass of Window and comes with the border as well
as the title. Dialog class’s instance always needs an associated Frame class instance to
exist.
4. Panel: Panel is the concrete subclass of Container and doesn’t contain any title bar,
menu bar or border. Panel class is a generic container for holding the GUI
components. You need the instance of the Panel class to add the components.
2. Button
The java.awt.Button class is used to create a labeled button. GUI component that triggers a
certain programmed action upon clicking it. The Button class has two constructors.
3. Text Field
The java.awt.TextField class creates a single-line text box for users to enter texts. The
TextField class has three constructors which are:
//Construct a TextField instance with the given initial text string with
the number of columns.
public TextField(String initialText, int columns);
//Construct a TextField instance with the given initial text string.
public TextField(String initialText);
//Construct a TextField instance with the number of columns.
public TextField(int columns);
4. Label
The java.awt.Label class provides a descriptive text string that is visible on GUI. An AWT
Label object is a component for placing text in a container. Label class has three constructors
which are:
// Construct a Label with the given text String, of the text alignment
public Label(String strLabel, int alignment);
//Construct a Label with the given text String
public Label(String strLabel);
//Construct an initially empty Label
public Label();
5. Canvas: A Canvas class represents the rectangular area where you can draw in an
application or receive inputs created by the user.
6. Choice: Choice class is used to represent a pop-up menu of choices. The selected choice is
shown on the top of the given menu.
7. Scroll Bar: The Scrollbar class object is used to add horizontal and vertical scrollbar in
the GUI. It enables a user to see the invisible number of rows and columns.
8. List: The object of List class represents a list of text items. Using the List class a user can
choose either one item or multiple items.
import java.awt.*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);
add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
AwtApp awt = new AwtApp();
Output:
SWING:
Swing is a lightweight Java graphical user interface (GUI) that is used to create various
applications. Swing has platform-independent components. It enables the user to create
buttons and scroll bars. Swing includes packages for creating desktop applications in Java.
Swing components are written in Java language. It is a part of Java Foundation
Classes(JFC).
1. ImageIcon: The ImageIcon component is used for creating an icon sized-image from
an image residing at the source URL.
2. JButton: JButton class is used for creating a push-button on the UI. The button can
contain some display text or images. It generates an event when clicked or double-
clicked.
3. JLabel: JLabel class is used for rendering a read-only text label or images on the UI.
It does not generate any events.
6. JCheckBox: JCheckBox renders a check-box with a label. The check-box has two
states – on/off. When selected, the state is on and a small tick is displayed in the box.
8. JList: JList component Renders a scrollable list of elements. A designer can select a
value or multiple values from the list. This select behaviour is defined in the code by
the developer.
12.JSlider: The JSlider component displays a slider which the designer can drag to
change its value. The constructor takes three arguments – minimum value, maximum
value, an initial value.
Components Hierarchy
Java Swing Example: In the following example, we have created a User form by using the
swing component classes provided by the javax.swing package. Consider the example.
import javax.swing.*;
public class SwingApp {
SwingApp(){
JFrame f = new JFrame();
f.add(firstName);
f.add(lastName);
f.add(dob);
f.add(firstNameTF);
f.add(lastNameTF);
f.add(dobTF);
f.add(sbmt);
f.add(reset);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
Output: