0% found this document useful (0 votes)
20 views106 pages

Java Programming

Java programming

Uploaded by

sdpatil3742
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
20 views106 pages

Java Programming

Java programming

Uploaded by

sdpatil3742
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 106

Java Programming

B.C.A. Part – III (Sem- V) Java Programming

Unit- 1- Introduction to Java


 Introduction to Java
 History and Features of Java
 C++ vs Java
 Simple Java Program with Internal path setting
 Difference between JDK, JRE, and JVM
 JVM Memory Management
 Data types, Unicode System, Operators, Keywords, Control Statements
 class, objects, constructor, Access modifiers
 Static keyword, final keyword
 STRING Manipulation, Array

Unit-2- Inheritance, Polymorphism and Encapsulation


 Inheritance in Java - Is-A Relationship & Aggregation and Composition(HAS-A)
 Types of inheritance
 this & super keyword
 Polymorphism in Java
 Types of polymorphism (Static and Dynamic Binding)
 Abstract class and method (using Interface)
 Encapsulation in Java (Getter and setter method in Java)

Unit-3- Packages, Multithreading and Exception Handling


 Defining & create packages – (system packages)
 Introduction of Exception - Pre -Defined Exceptions, Try-Catch-Finally, Throws,
throw, User Defined Exception examples
 Multithreading- Introduction, Thread Creations, Thread Life Cycle, Life Cycle
Methods, Synchronization, Wait() notify() notify all() methods

Unit- 4- AWT, SWING(JFC)


 Introduction and Components of AWT
 Event-Delegation Model
 Listeners, Layout
 Individual Components Label, Button, Check Box, Radio Button,
 Introduction Diff B/W AWT and SWING,
 Components hierarchy, Panes, Individual Swings Components J Label, JButton, JText
Field, JTextArea
mpm@cimdr.sangli Page 1
Java Programming

CHAPTER I: INTRODUCTION TO JAVA

Introduction to Java

Java is a programming language created by James Gosling from Sun Microsystems


(Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the
steermanship for Java. Over time new enhanced versions of Java have been released. The
current version of Java is Java 1.7 which is also known as Java 7. From the Java
programming language, the Java platform evolved. The Java platform allows software
developers to write program code in other languages than the Java programming language
which still runs on the Java virtual machine. The Java platform is usually associated with the
Java virtual machine and the Java core libraries.
Java is a high level, third generation programming language, like C, FORTRAN,
Smalltalk, Perl, and many others. You can use Java to write computer applications that play
games, store data or do any of the thousands of other things computer software can do.
Compared to other programming languages, Java is most like C. However, although Java
shares much of C's syntax, it is not C. Knowing how to program in C or, better yet, C++, will
certainly help you to learn Java more quickly, but you don't need to know C to learn Java. A
Java compiler won't compile C code, and most large C programs need to be changed
substantially before they can become Java programs. What's most special about Java in
relation to other programming languages is that it lets you write special programs called
applets that can be downloaded from the Internet and played safely within a web browser.
Java language is called as an Object Oriented Programming language and before beginning
for Java, we have to learn the concept of OOP’s.

Basics Concepts of OOP(Java)

There are some basic concepts of object-oriented programming as follows:


1. Object
Objects are important runtime entities in object-oriented method. They may
characterize a location, a bank account, and a table of data or any entry that the program
must handle. Each object holds data and code to operate the data. Object can interact without
having to identify the details of each other ‘s data or code. It is sufficient to identify the type
of message received and the type of reply returned by the objects.

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

Java is a general-purpose, object-oriented programming language developed by Sun


Microsystems of USA in 1991.Originally called Oak by James Gosling (one of the inventor
of the language). Java was invented for the development of software for consumer electronic
devices like TVs, toasters, etc. The main aim had to make java simple, portable and reliable.
Following table shows the year and beginning of Java.

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:

JAVA is an object-oriented programming language developed by Sun Microsystems


of USA in 1991. Java is first programming language which is not attached with any hardware
or operating system. Program developed in Java can be executed anywhere and on any
system. Features of Java are as follows:

1. Compiled and Interpreted

mpm@cimdr.sangli Page 4
Java Programming

Basically, a computer language is either compiled or interpreted. Java comes together


both this approach thus making Java a two-stage system. Java compiler translates Java code
to Byte code instructions and Java Interpreter generate machine code that can be directly
executed by machine that is running the Java program.

2. Platform Independent and portable


Java supports the feature portability. Java programs can be easily moved from one
computer system to another and anywhere. Changes and upgrades in operating systems,
processors and system resources will not force any alteration in Java programs. This is
reason why Java has become a trendy language for programming on Internet which
interconnects different kind of systems worldwide. Java certifies portability in two ways.
First way is Java compiler generates the byte code and that can be executed on any machine.
Second way is size of primitive data types are machine independent.

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.

4. Robust and secure


Java is a most strong language which provides many securities to make certain reliable
code. It is design as garbage –collected language, which helps the programmers virtually
from all memory management problems. Java also includes the concept of exception
handling, which detain serious errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java, and this is the strong reason that programmer use
this language for programming on Internet. The absence of pointers in Java ensures that
programs cannot get right of entry to memory location without proper approval.

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.

6. Simple and small


Java is very small and simple language. Java does not use pointer and header files, go
to statements, etc. It eliminates operator overloading and multiple inheritance.

7. Multithreaded and Interactive


Multithreaded means managing multiple tasks simultaneously. Java maintains
multithreaded programs. That means we need not wait for the application to complete one
task before starting next task. This feature is helpful for graphic applications.

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.

9. Dynamic and Extensible


Java is also dynamic language. Java is capable of dynamically linking in new class,
libraries, methods, and objects. Java can also establish the type of class through the query
building it possible to either dynamically link or abort the program, depending on the reply.
Java program is support functions written in other language such as C and C++, known as
native methods.

Comparison in Java and C++

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++.

Java Virtual Machine

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.

Class Loader Subsystem


It is mainly responsible for three activities.
 Loading
 Linking
 Initialization
Loading: The Class loader reads the “.class” file, generate the corresponding binary data
and save it in the method area. For each “.class” file, JVM stores the following information
in the method area.

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.

Linking: Performs verification, preparation, and (optionally) resolution.


 Verification: It ensures the correctness of the .class file i.e. it checks whether this file
is properly formatted and generated by a valid compiler or not. If verification fails, we
get run-time exception java.lang.VerifyError. This activity is done by the component
ByteCodeVerifier. Once this activity is completed then the class file is ready for
compilation.
 Preparation: JVM allocates memory for class variables and initializing the memory to
default values.
 Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.

Initialization: In this phase, all static variables are assigned with their values defined in the
code and static block(if any). This is executed from top to bottom in a class and from parent
to child in 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.

Difference between JDK, JRE and JVM

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

Key JDK JRE JVM


JDK (Java Development JRE (Java Runtime JVM (Java Virtual
Kit) is a software Environment) is the Machine) is an abstract
development kit to implementation of machine that is
develop applications in JVM and is defined platform-dependent and
Definition
Java. In addition to JRE, as a software package has three notions as a
JDK also contains that provides Java specification, a
number of development class libraries, along document that describes
tools (compilers, with Java Virtual requirement of JVM

mpm@cimdr.sangli Page 9
Java Programming

JavaDoc, Java Debugger Machine (JVM), and implementation,


etc.). other components to implementation, a
run applications computer program that
written in Java meets JVM
programming. requirements, and
instance, an
implementation that
executes Java byte code
provides a runtime
environment for
executing Java byte
code.
JVM on other hand
On other hand JRE is
JDK is primarily used specifies all the
majorly responsible
Prime for code execution and implementations and
for creating
functionality has prime functionality responsible to provide
environment for code
of development. these implementations
execution.
to JRE.
JDK is platform
Like of JDK JRE is
Platform dependent i.e for JVM is platform
also platform
Independence different platforms independent.
dependent.
different JDK required.
On other hand JRE
does not contain tools
As JDK is responsible
such as compiler or
for prime development
debugger etc. Rather JVM does not include
so it contains tools for
Tools it contains class software development
developing, debugging
libraries and other tools.
and monitoring java
supporting files that
application.
JVM requires to run
the program.
JRE = Java Virtual JVM = Only Runtime
JDK = Java Runtime
Machine (JVM) + environment for
Implementation Environment (JRE) +
Libraries to run the executing the Java byte
Development tools
application code.

JVM Memory Management

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.

Java Native Interface (JNI) :


It is an interface that interacts with the Native Method Libraries and provides the native
libraries (C, C++) required for the execution. It enables JVM to call C/C++ libraries and to
be called by C/C++ libraries which may be specific to hardware.

Native Method Libraries:


It is a collection of the Native Libraries (C, C++) which are required by the Execution
Engine.

Simple Java Program:

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

System.out.println("This is my first program");

The statement outputs the character between quotes to the console.


Above explanation is about how to write program and now we have to learn where to write
program and how to compile and run the program. For this reason, the next explanation is
showing the steps.
1. Edit the program by the use of Notepad.
2. Save the program to the hard disk.
3. Compile the program with the javac command. (Java compiler)
4. If there are syntax errors, go back to Notepad and edit the program.
5. Run the program with the java command. (Java Interpreter)
6. If it does not run correctly, go back to Notepad and edit the program.
7. When it shows result then stop.

Compilation and Execution of Java Program

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

b) java (Java Interpreter)


As we learn that, 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 byte code and
interpreter convert ―.java file in ―.class file.
mpm@cimdr.sangli Page 12
Java Programming

Syntax - C:\java filename


If my filename is abc.java then the syntax will be
C:\java abc

Set path in 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:

token <= identifier | keyword | separator | operator | literal | comment

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.

1. Identifiers: names the programmer chooses


2. Keywords: names already in the programming language
3. Separators (also known as punctuators): punctuation characters and paired-delimiters

mpm@cimdr.sangli Page 13
Java Programming

4. Operators: symbols that operate on arguments and produce results


5. Literals (specified by their type) – Numeric(int and double), Logical (boolean),
Textual (char and String), Reference (null)
6. Comments: Line & Block

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.

Keywords used in Java

The following is a list of Java keywords, along.

assert - Assert describes a predicate (a true–false statement) placed in a java-program to


indicate that the developer thinks that the predicate is always true at that place. If an
assertion evaluates to false at run-time, an assertion failure results, which typically causes
execution to abort. Optionally enable by ClassLoader method.

break - Used to terminate program execution in the current loop body.

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.

new - Used to create an instance of a class or array object.

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.

Identifiers used in Java

An identifier is a name given to a package, class, interface, method, or variable. It


allows a programmer to refer to the item from other places in the program. To make the most
out of the identifiers you choose make them meaningful and follow the standard Java naming
conventions.
Three things to remember when choosing an identifier:
 reserved words (keywords) cannot be used.
 they cannot start with a digit but digits can be used after the first character (e.g., name1,
n2ame are valid).
 the only symbols you can use are the underscore (i.e., "_") and dollar sign (i.e., "$").

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

System.out.printf("My name is %s, my height is %.0f foot and my weight


is %d pounds. D'oh!%n", name, height, weight);
Although you have great flexibility for identifiers, we're going to make more
restrictions for which identifiers we should use. But first, to look at some invalid identifiers.

Examples of Invalid Identifiers


It's easy to make a mistake and use a bad identifier.
 1ab (ERROR: first character starts with a digit)
 num-oranges (ERROR: dash is not permitted in identifiers)
 num oranges (ERROR: space is not permitted in identifiers)

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'

There are three kinds of variables in Java:

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.

Data types Used in Java

There are two data types available in Java:


 Primitive Data Types
 Reference/Object Data Types

mpm@cimdr.sangli Page 20
Java Programming

Primitive Data Types:


There are eight primitive data types supported by Java. Primitive data types are predefined
by the language and named by a keyword. Following are details about the eight primitive
data types.
byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int.
 Example: byte a = 100, byte b = -50

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'

Reference Data Types:


 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any
compatible type.
 Example: Animal animal = new Animal("giraffe");

Java Literals:

A literal is a source code representation of a fixed value. They are represented directly
in the code without any computation. Literals can be assigned to any primitive type variable.
For example: byte a = 68; char a = 'A’.

byte, int, long, and short can be expressed in decimal (base 10), hexadecimal (base 16) or
octal(base 8) number systems as well.

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)

Operators Used in Java

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

The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description
+ Addition - Adds values on either side of the operator
- Subtraction - Subtracts right hand operand from left hand operand
* Multiplication - Multiplies values on either side of the operator
/ Division - Divides left hand operand by right hand operand
Modulus - Divides left hand operand by right hand operand and returns
%
remainder

mpm@cimdr.sangli Page 23
Java Programming

++ Increment - Increases the value of operand by 1


-- Decrement - Decreases the value of operand by 1

The Relational Operators:


There are following relational operators supported by Java language

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.

The Bitwise Operators:


Java defines several bitwise operators, which can be applied to the integer types, long,
int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60; and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Operator Description Example
Binary AND Operator copies a bit to the (A & B) will give 12 which
&
result if it exists in both operands. is 0000 1100
Binary OR Operator copies a bit if it exists
(A | B) will give 61 which is
|
in either operand. 0011 1101
Binary XOR Operator copies the bit if it is
(A ^ B) will give 49 which is
^
set in one operand but not both. 0011 0001
(~A ) will give -61 which is
Binary Ones Complement Operator is unary 1100 0011 in 2's complement
~
and has the effect of 'flipping' bits. form due to a signed binary
number.

mpm@cimdr.sangli Page 24
Java Programming

Binary Left Shift Operator. The left


A << 2 will give 240 which
<< operands value is moved left by the number
is 1111 0000
of bits specified by the right operand.
Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 will give 15 which is
>>
number of bits specified by the right 1111
operand.
Shift right zero fill operator. The left
operands value is moved right by the A >>>2 will give 15 which is
>>>
number of bits specified by the right operand 0000 1111
and shifted values are filled up with zeros.

The Logical Operators:


The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:

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.

The Assignment Operators:


There are following assignment operators supported by Java language:

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

^= bitwise exclusive OR and assignment operator


|= bitwise inclusive OR and assignment operator

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 would produce the following result:


true

This operator will still return true if the object being compared is the assignment compatible
with the type on the right. Following is one more example:

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

Precedence of Java Operators:


Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator:
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associability


Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >>>>><< Left to right
Relational >>= <<= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

mpm@cimdr.sangli Page 27
Java Programming

Branching statements Used in Java.

There are two types of decision-making statements in Java. They are:


 if statements
 switch statements

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");
}
}
}

This would produce the following result:


This is if statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax:
The syntax of an if...else is:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
Else
{
//Executes when the Boolean expression is false
}

//Example:
class Test
{

mpm@cimdr.sangli Page 28
Java Programming

public static void main(String args[])


{
int x = 30;
if( x < 20 )
{
System.out.print("This is if statement");
}
Else
{
System.out.print("This is else statement");
}
}
}

This would produce the following result:


This is else statement

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.

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

Nested if...else Statement:


It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
//Example:
class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;

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

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:


 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
//Example:
class Test
{
public static void main(String args[])
{
//char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;

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
$

Looping statements used in Java.

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

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}

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");
}
}
}

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

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);

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

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

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. A for loop is useful when you know how many
times a task is to be repeated.

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

Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
 Declaration: The newly declared block variable, which is of a type compatible with
the elements of the array you are accessing. The variable will be available within the
for block and its value would be the same as the current array element.
 Expression: This evaluates to the array you need to loop through. The expression can
be an array variable or method call that returns an array.
//Example:
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};

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

Defining a class and objects

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;

public int getVolume()


{
return (length * breadth * height);
}
public static void main(String[] args) {
Cube cubeObj; // Creates a Cube Reference
cubeObj = new Cube(); // Creates an Object of Cube
System.out.println("Volume of Cube is : " + cubeObj.getVolume());
}
}

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 );
}

public static void main(String []args)


{
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

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

Accessing Instance Variables and Methods:

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();

/* Now call a variable as follows */


Object Reference.variableName;

/* Now you can call a class method as follows */


Object Reference.MethodName();

Example:
This example explains how to access instance variables and methods of a class:
class Puppy
{
int puppyAge;

public Puppy(String name)


{
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public void setAge( int age )


{
puppyAge = age;
}

public int getAge( )


{
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args)


{
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
mpm@cimdr.sangli Page 39
Java Programming

}
}

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.

 Rules for creating java constructor


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

 Types of java constructors


There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor: A constructor that has no parameter is known as default
constructor. It provides the default values to the object like 0, null etc. depending on the type.

Syntax of default constructor:<class_name>(){}


//Example of default constructor
class Bike1
{
Bike1()
{System.out.println("Bike is created");}

public static void main(String args[])


{
Bike1 b=new Bike1();
}
}

Java Parameterized Constructor: A constructor that has parameters is known as


parameterized constructor. It is used to provide different values to the distinct objects.
//Example of parameterised constructor
class Student4
{

mpm@cimdr.sangli Page 40
Java Programming

int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Constructor Overloading in Java: Constructor overloading is a technique in Java in which


a class can have any number of constructors that differ in parameter lists. The compiler
differentiates these constructors by considering the number of parameters in the list and their
type.
//Example of constructor overloading
class Student5
{
int id;
String name;
int age;

Student5(int i,String n)
{
id = i;
name = n;
}

Student5(int i,String n,int a)


{
id = i;
name = n;
age=a;
}

void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

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

//Example of copy constructor


class Student6
{
int id;
String name;

Student6(int i,String n)
{
id = i;
name = n;
}

Student6(Student6 s)
{
id = s.id;
name =s.name;
}

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Destructors in Java i.e. finalise () method

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;

public Thing (String what)


{
this.what = what;
number_of_things++;
}

protected void finalize ()


{
number_of_things--;
}
}
Some object-oriented languages require that you keep track of all the objects you
create and that you explicitly destroy them when they are no longer needed. Managing
memory explicitly is tedious and error-prone. The Java platform allows you to create as
many objects as you want (limited, of course, by what your system can handle), and you
don't have to worry about destroying them. The Java runtime environment deletes objects
when it determines that they are no longer being used. This process is called garbage
collection.
An object is eligible for garbage collection when there are no more references to that
object. References that are held in a variable are usually dropped when the variable goes out
of scope. Or, you can explicitly drop an object reference by setting the variable to the special
value null. Remember that a program can have multiple references to the same object; all
references to an object must be dropped before the object is eligible for garbage collection.
The Java runtime environment has a garbage collector that periodically frees the
memory used by objects that are no longer referenced. The garbage collector does its job
automatically when it determines that the time is right.

Source files declaration rules:

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 Manipulation in Java

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

There are two ways to create a string in Java:

Using String literal String s = “CIMDR”;

Using new keyword String s = new String (“CIMDR”);

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

Interfaces and Classes in Strings in Java


CharBuffer: This class implements the CharSequence interface. This class is used to allow
character buffers to be used in place of CharSequences. An example of such usage is the
regular-expression package java.util.regex.

String: It is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created.

String s = new String (“GeeksforGeeks”);

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.

Syntax: StringBuffer s = new StringBuffer("GeeksforGeeks");

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.

Syntax: StringBuilder str = new StringBuilder();


str.append("GFG");

StringTokenizer class in Java is used to break a string into tokens.

Example:

mpm@cimdr.sangli Page 45
Java Programming

A StringTokenizer object internally maintains a current position within the string to be


tokenized. Some operations advance this current position past the characters processed. A
token is returned by taking a substring of the string that was used to create the
StringTokenizer object.

StringJoiner is a class in java.util package which is used to construct a sequence of


characters(strings) separated by a delimiter and optionally starting with a supplied prefix and
ending with a supplied suffix. Though this can also be with the help of StringBuilder class to
append delimiter after each string, StringJoiner provides an easy way to do that without
much code to write.

Syntax: public StringJoiner(CharSequence delimiter)

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.

2. toUpperCase(): public String toLowerCase();


This function remains the same as toLowerCase(), but it changes the case to uppercase.

3. Substring(): String substring(int StartIndex, int LastIndex)


In the example code area, we will see the use of this function with the index as an input and
the output as well. For this, we need to have a string upon which we will be performing this
operation. We can use the position from where we want the string in place of the StartIndex,
and we can replace the LastIndex with the end index to where we want the string.

4. trim(): public String trim()


Again, this is a string manipulation function we can use to remove the unwanted space from
a given string.

Examples of String Manipulation in Java


Example #1 Using toLowerCase() and compareTo() together.
public class StrCompare {
public static void main(String[] args) {
String string1 = "Hello";
String string2 = "hello";
String string3 = string1.toLowerCase();
String string4 = string2.toLowerCase();
int i = string3.compareTo(string4);//0 for both are equal
if(i==0)
{System.out.println("Both strings are equal.");}
else{System.out.print("Strings are not equal.");}
}
}

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));
}
}
}

Example #4 Getting the substring from a given string.


Code:
public class SubString {
public static void main(String[] args) {
String str1= "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
System.out.println(str1.substring(0,10)); // this will give the string
from index 0 to 10
System.out.println(str1.substring(10)); // this will give the string
from index 10 to the end of the string
}
}

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

Unit II: Inheritance, Polymorphism & Encapsulation

Defining sub class, subclass constructor

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.

class Subclass-name extends Superclass-name


{
//methods and fields
}
Eg:
class Employee
{
float salary=40000;
}

class Programmer extends Employee


{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

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.

//Single Inheritance example program in Java


Class A
{
Public void method A()
{
System.out.println("Base class method");
}
}

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.

Multiple Inheritances is very rarely used in software projects. Using


Multiple inheritances often leads to problems in the hierarchy. This
results in unwanted complexity when further extending the class. Most
of the new OOP languages like Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritances is supported in C++.

mpm@cimdr.sangli Page 53
Java Programming

3) Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can


inherit from a derived class, thereby making this derived class the base class for
the new class. As you can see in below flow diagram C is subclass or child class
of B and B is a child class of A.

Multilevel Inheritance example program in Java


Class X
{
Public void methodX()
{
System.out.println("Class X method");
}
}

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

In such kind of inheritance one class is inherited by many sub classes.


In below example class B, C and D inherits the same class A. A is
parent class (or base class) of B, C & D.

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

An interface is a collection of abstract methods. A class implements an interface,


thereby inheriting the abstract methods of the interface. An interface is not a class. Writing
an interface is similar to writing a class, but they are two different concepts. A class
describes the attributes and behaviors of an object. An interface contains behaviors that a
class implements. Unless the class that implements the interface is abstract, all the methods
of the interface need to be defined in the class.

An interface is similar to a class in the following ways:


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding byte code file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including:


 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
 It cannot be instantiated just like abstract class.

Importance of Interface in JAVA


There are some reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 We can support the functionality of multiple inheritances by using interface.
 It can be used to achieve loose coupling.

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.

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Simple example of Java interface


In this example, Printable interface have only one method, its implementation is provided
in the A class

interface printable
{
void print();
}

class A6 implements printable


{
public void print(){System.out.println("Hello");
}

public static void main(String args[])


{
A6 obj = new A6();
obj.print();
}
}

Output:Hello

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.


known as multiple inheritance.

mpm@cimdr.sangli Page 56
Java Programming

interface Printable
{
void print();
}

interface Showable
{
void show();
}

class A7 implements Printable,Showable


{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[])
{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello
Welcome

Multiple inheritance is not supported through class in java but it is possible by


interface

As we have explained in the inheritance chapter, multiple inheritance is not supported in


case of class. But it is supported in case of interface because there is no ambiguity as
implementation is provided by the implementation class. For exampl

interface Printable
{
void print();
}

interface Showable
{
void print();
}

mpm@cimdr.sangli Page 57
Java Programming

class testinterface1 implements Printable,Showable


{
public void print(){System.out.println("Hello");}

public static void main(String args[])


{
testinterface1 obj = new testinterface1();
obj.print();
}
}
Hello

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();
}

interface Showable extends Printable


{
void show();
}

class Testinterface2 implements Showable


{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[])


{
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Hello
Welcome

Marker or tagged interface: An interface that has no member is known as marker or


tagged interface. They are used to provide some essential information to the JVM so that
JVM may perform some useful operation.

public interface Serializable


{
}

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.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to


an overridden method is resolved at runtime rather than compile-time. In this process, an
overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the
reference variable. Let's first understand the upcasting before Runtime Polymorphism.

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

Example of Java Runtime Polymorphism


In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable
of Parent class. Since it refers to the subclass object and subclass method overrides the
Parent class method, subclass method is invoked at runtime. Since method invocation is
determined by the JVM not compiler, it is known as runtime polymorphism.

class Bike
{
void run(){System.out.println("running");}
}

class Splendar extends Bike


{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[])


{
Bike b = new Splendar();//upcasting
b.run();
}
}
Output: running safely with 60km.

Real example of Java Runtime Polymorphism

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;}
}

class BCAI extends BCA


{
int getAttendance(){return 8;}
}

mpm@cimdr.sangli Page 60
Java Programming

class BCAII extends BCA


{
int getAttendance(){return 7;}
}

class BCAIII extends BCA


{
int getAttendance(){return 9;}
}

class Test3
{
public static void main(String args[])
{
BCA b1=new BCAI();
BCA b2=new BCAII();
BCA b3=new BCAIII();

System.out.println("BCA I Attendance: "+b1.getAttendance());


System.out.println("BCA II Attendance: "+b2.getAttendance());
System.out.println("BCA III Attendance: "+b3.getAttendance());
}
}

Output:
BCA I Attendance : 80
BCA II Attendance : 70
BCA III Attendance : 90

Java Runtime Polymorphism with data member


Method is overridden not the data members, so runtime polymorphism can't be achieved by
data members. In the example given below, both the classes have a data member speed limit,
we are accessing the data member by the reference variable of Parent class which refers to
the subclass object. Since we are accessing the data member which is not overridden, hence
it will access the data member of Parent class always
Rule: Runtime polymorphism can't be achieved by data members.

class Bike
{
int speedlimit=90;
}

class Honda3 extends Bike


{
int speedlimit=150;

public static void main(String args[])


{
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
}

mpm@cimdr.sangli Page 61
Java Programming

Output:90

/*Java Runtime Polymorphism with Multilevel Inheritance*/


class Animal
{
void eat(){System.out.println("eating");}
}

class Dog extends Animal


{
void eat(){System.out.println("eating fruits");}
}

class BabyDog extends Dog


{
void eat(){System.out.println("drinking milk");}

public static void main(String args[])


{
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}

Output: eating
eating fruits
drinking Milk

/*Try for Output*/

class Animal
{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal


{
void eat(){System.out.println("dog is eating...");}
}

class BabyDog1 extends Dog


{
public static void main(String args[])
{
Animal a=new BabyDog1();
a.eat();
}
}
Output: Dog is eating
mpm@cimdr.sangli Page 62
Java Programming

Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is
invoked.

Method overloading in JAVA

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

Method Overloading by changing the no. of arguments


In this example, we have created two overloaded methods, first sum method performs
addition of two numbers and second sum method performs addition of three numbers.
class Calculation
{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[])


{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}

Method Overloading by changing data type of argument


In this example, we have created two overloaded methods that differs in data type. The first
sum method receives two integer arguments and second sum method receives two double
arguments.
class Calculation2
{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);
}

public static void main(String args[])


{
mpm@cimdr.sangli Page 63
Java Programming

Calculation2 obj=new Calculation2();


obj.sum(10.5,10.5);
obj.sum(20,20);
}
}

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
}
}

Method Overriding in JAVA

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.

Usage of Method Overriding


 Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
 Method overriding is used for runtime polymorphism

Rules for Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A (inheritance) relationship.

Example :
class Vehicle
{ void run(){System.out.println("Vehicle is running");} }

class Bike2 extends Vehicle


{ void run(){System.out.println("Bike is running safely");}

public static void main(String args[])


{
Bike2 obj = new Bike2();
obj.run();
}

mpm@cimdr.sangli Page 64
Java Programming

Overriding vs. Overloading in Java

Method Overloading Method Overriding


Overloading occurs when two or more Overriding means having two methods with
methods in one class have the same method the same method name and parameters (i.e.,
name but different parameters. method signature).

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.

Abstraction (Abstract classes) In Java

Abstraction is a process of hiding the implementation details and showing only


functionality to the user. It shows only important things to the user and hides the internal
details. Abstraction lets you focus on what the object does instead of how it does it. There
are two ways to achieve abstraction in java, Abstract class (0 to 100%) & Interface (100%).
Java Abstract classes are used to declare common characteristics of subclasses. An
abstract class cannot be instantiated. It can only be used as a super class for other classes that
extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract
classes are used to provide a template or design for concrete subclasses down the inheritance
tree. Like any other class, an abstract class can contain fields that describe the characteristics
and methods that describe the actions that a class can perform. An abstract class can include
methods that contain no implementation. These are called abstract methods. The abstract
method declaration must then end with a semicolon rather than a block. If a class has any
abstract methods, whether declared or inherited, the entire class must be declared abstract.
Abstract methods are used to provide a template for the classes that inherit the abstract
methods.
Abstract classes cannot be instantiated; they must be subclassed, and actual
implementations must be provided for the abstract methods. Any implementation specified
can be overridden by additional subclasses. An object must have an implementation for all of
its methods. You need to create a subclass that provides an implementation for the abstract
method. A class that is declared with abstract keyword is known as abstract class in java. It
can have abstract and non-abstract methods (method with body).
abstract class A{}

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

/*Example of abstract class that has abstract method*/


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}

class Honda4 extends Bike


{
void run(){System.out.println("running safely..");}

public static void main(String args[])


{
Bike obj = new Honda4();
obj.run();
}
}

OUTPUT: running safely..

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e.
hidden to the end user) and object of the implementation class is provided by the factory
method.
A factory method is the method that returns the instance of the class. We will learn about
the factory method later. In this example, if you create the instance of Rectangle class,
draw() method of Rectangle class will be invoked.

abstract class Shape


{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown
by end user

class Rectangle extends Shape


{
void draw(){System.out.println("drawing rectangle");}
}

class Circle1 extends Shape


{
void draw(){System.out.println("drawing circle");}
}
mpm@cimdr.sangli Page 66
Java Programming

//In real scenario, method is called by programmer or user


class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();//In real scenario, object is provided throug
h method e.g. getShape() method
s.draw();
}
}

OUTPUT : drawing circle

/*Another example of abstract class in java*/


File: TestBank.java
abstract class Bank
{
abstract int getRateOfInterest();
}

class SBI extends Bank


{
int getRateOfInterest(){return 7;}
}

class PNB extends Bank


{
int getRateOfInterest(){return 7;}
}

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+" %");
}
}

O/p : Rate of Interest is: 7 %

//example of abstract class that have method body


abstract class Bike
{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}

class Honda extends Bike

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

Another real scenario of abstract class


The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.

interface A
{
void a();
void b();
void c();
void d();
}

abstract class B implements A


{
public void c(){System.out.println("I am C");}
}

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.

Disadvantage of Encapsulation in Java


The major disadvantage of encapsulation in Java is it increases the length of the code and
slows shutdown execution.

// fields to calculate area


class Area
{

int length;
int breadth;

// constructor to initialize values


Area(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}

// method to calculate area


public void getArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
}

class Encp

mpm@cimdr.sangli Page 70
Java Programming

{
public static void main(String[] args)
{
Area rectangle = new Area(2, 16);
rectangle.getArea();
}
}

Tightly Encapsulated Class in Java


If each variable is declared as private in the class, it is called tightly encapsulated class in
Java. For a tightly encapsulated class, we are not required to check whether the class
contains getter and setter method or not and whether these methods are declared as public or
not.

For example:

public class Account


{
private double balance;
public double getbalance()
{
return balance;
}
}

Abstraction vs. Encapsulation


Often encapsulation is misunderstood with Abstraction.
 Encapsulation is more about “How” to achieve a functionality
 Abstraction is more about “What” a class can do.
A simple example to understand this difference is a mobile phone. Where the complex logic
in the circuit board is encapsulated in a touch screen, and the interface is provided to abstract
it out.

Getter and setter method in Java

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

public int getBalance() {


return this.account_balance;
}
// setter method
public void setNumber(int num) {
this.account_number = num;
}
}

mpm@cimdr.sangli Page 72
Java Programming

UNIT III: Package, Multithreading and Exception Handling

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.

Some of the existing packages in Java are


 java.lang - bundles the fundamental classes
 java.io - classes for input , output functions are bundled in this package

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.

Advantage of Java Package

 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

Put an interface in the package animals:


/* File name : Animal.java */
package animals;

interface Animal
{
public void eat();
public void travel();
}

Simple example of java package


The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename

For example javac -d . Simple.java

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

Example of package that import the packagename.*


//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java

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

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time
when you are accessing the class or interface. It is generally used when two packages

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

Note: If you import a package, subpackages will not be imported.


If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage.


It should be created to categorize the package further. Let's take an example, Sun
Microsystems has defined a package named java that contains many classes like System,
String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader
and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on. So, Sun has subcategorized the java package into subpackages
such as lang, net, io etc. and put the Input/Output related classes in io package, Server and
ServerSocket classes in net packages and so on. The standard of defining package is
domain.company.package e.g. com.javatpoint.bean or org.sssit.dao.
Example of Subpackage

package com.javatpoint.core;
class Simple
{
public static void main(String args[])

mpm@cimdr.sangli Page 76
Java Programming

{
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output: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.

How to put two public classes in a package?


If you want to put two public classes in a package, have two java source files containing one
public class, but keep the package name same. For example

//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

Java is a multi-threaded programming language which means we can develop multi-


threaded program using Java. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle different task at the same time making optimal
use of the available resources especially when your computer has multiple CPUs.
Multitasking is when multiple processes share common processing resources such as a
CPU. Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of the
threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application. Multi-threading enables you
to write in a way where multiple activities can proceed concurrently in the same program.

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

2. Threads share their parent process data and code


3. Context switching between threads is usually less expensive than between processes.
4. Thread intercommunication is relatively easy than process communication.

Life Cycle of a Thread:

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.

Creating a thread in Java is done like this:


Thread thread = new Thread();
To start the Java thread you will call its start() method, like this:
thread.start();

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

Java provides two ways to create a thread programmatically.


1. Implementing the java.lang.Runnable interface.
2. Extending the java.lang.Thread class.

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

1) It has been put to sleep for a set amount of time


The sleep method is static and pauses execution for a set number of milliseconds. There is a
version that is supposed to pause for a set number of nanoseconds.

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.

public class TSleep extends Thread


{
public static void main(String argv[])
{
TSleep t = new TSleep();
t.start();
}

public void run()


{
try{
while(true)
{
this.sleep(1000);
System.out.println("looping while");
}
}catch(InterruptedException ie){}
}
}

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.)

Use a "stop request" variable


A common solution is to use an explicit "stop request" variable, which we check on each
pass through the loop. This technique is suitable provided that we can check the variable
frequently enough:

private volatile boolean stopRequested = false;

public void run()


{
while (!stopRequested)
{
...
}
}
public void requestStop()

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

String Retrieves the name of running thread in current context in String


getName() format

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

boolean This method will check if thread is alive or dead


isAlive()

mpm@cimdr.sangli Page 82
Java Programming

Priority of a Thread (Thread Priority)

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

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10
//Example of priority of a Thread:
class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getN
ame());
System.out.println("running thread priority is:"+Thread.currentThread().
getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

Output: running thread name is:Thread-0


Running thread priority is:10
Running thread name is:Thread-1
Running thread priority is:1

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.

Difference between error and exception

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

Advantages of Exception Handling


 Exception handling allows us to control the normal flow of the program by using
exception handling in program.
 It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
 It also gives us the scope of organizing and differentiating between different errors types
using a separate block of codes. This is done with the help of try-catch blocks.

Difference between checked and unchecked exceptions


1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.

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

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

//code that may throw exception


}catch(Exception_class_Name ref){}

Syntax of try-finally block


Try
{
//code that may throw exception
}
finally{}

Nested try blocks


Exception handlers can be nested within one another. A try, catch or a finally block
can in turn contains another set of try catch finally sequence. In such a scenario, when a
particular catch block is unable to handle an Exception, this exception is rethrown. This
exception would be handled by the outer set of try catch handler.
//Example of nested try catch block
import java.util.InputMismatchException;
public class Nested
{
public static void main(String[] args)
{
try
{
System.out.println("Outer try block starts");
try
{

System.out.println("Inner try block starts");


int res = 5 / 0;
}
catch (InputMismatchException e)
{
System.out.println("InputMismatchException caught");
}
finally {System.out.println("Inner final");}
}

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.

public class Nested


{
public static void main(String[] args)
{
try
{
meth();
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException caught");
}
finally {System.out.println("Outer finally");}
}
public static void main()
{
try
{
int res = 3 / 0;
}
finally {System.out.println("Finally in meth");}
}
}

Finally in meth
ArithmeticException caught
Outer finally

Java catch block

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.

//Problem without exception handling (understand the problem if we don't


use try-catch block)

public class Testtrycatch1


{
public static void main(String args[])
mpm@cimdr.sangli Page 86
Java Programming

{
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero

//Solution of problem by exception handling using java try-catch


block.
public class Testtrycatch2
{
public static void main(String args[])
{
try
{
int data=50/0;
}
catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Multiple catch blocks

If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.

public class TestMultipleCatchBlock


{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=30/0;
}

catch(ArithmeticException e){System.out.println("task1 is comple


ted");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task
2 completed");}
catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code...");


}
}

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(Exception e){System.out.println("common task completed");}

catch(ArithmeticException e){System.out.println("task1 is completed


");}

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

The Java throws keyword is used to declare an exception. It gives an information to


the programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained. Exception
Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing
check up before the code being used.
throw and throws are two Java keyword related to Exception feature of Java
programming language. Exception handling is an important part of Java
programming language which enables you to write robust programs. There are five keywords
related to Exception handling in Java e.g. try, catch, finally, throw and throws. Difference
listed here will help you to understand concept behind throw and throws better.

Difference between throw and throws


throw throws
throw keyword is used to throw Exception throws keyword, used in method declaration,
from any method or static block in Java. denoted which Exception can possible be
thrown by this method.
throw keyword can be used in switch case in throws keyword cannot be used anywhere
program. except on method declaration line.

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;

Student11(int id,String name)


{
this.id = id;
this.name = name;
}

void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();

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.

Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}

public static void main(String args[])


{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Java final method


class Bike
{
final void run(){System.out.println("running");}
}

class Honda extends Bike


{
void run(){System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
mpm@cimdr.sangli Page 92
Java Programming

Java final class


final class Bike{}

class Honda1 extends Bike


{
void run(){System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda= new Honda();
honda.run();
}
}

final method inherited


class Bike
{
final void run(){System.out.println("running...");}
}

class Honda2 extends Bike


{
public static void main(String args[])
{
new Honda2().run();
}
}

Blank or uninitialized final variable


A final variable that is not initialized at the time of declaration is known as blank final
variable. If you want to create a variable that is initialized at the time of creating object and
once initialized may not be changed, it is useful. For example PAN CARD number of an
employee. It can be initialized only in constructor.
Example of blank final variable
class Student
{
int id;
String name;
final String PAN_CARD_NUMBER;
}

Blank final variable


class Bike10
{
final int speedlimit;//blank final variable
Bike10()
{
speedlimit=70;
System.out.println(speedlimit);

mpm@cimdr.sangli Page 93
Java Programming

public static void main(String args[])


{
new Bike10();
}
}

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank
final variable. It can be initialized only in static block.
class A
{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[])
{
System.out.println(A.data);
}
}

final parameter
class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}

public static void main(String args[])


{
Bike11 b=new Bike11();
b.cube(5);
}
}

Super keyword in java

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.

super is used to refer immediate parent class instance variable.


Problem without super keyword
class Vehicle
{
mpm@cimdr.sangli Page 94
Java Programming

int speed=50;
}
class Bike3 extends Vehicle
{
int speed=100;
void display()
{
System.out.println(speed);//will print speed of Bike
}

public static void main(String args[])


{
Bike3 b=new Bike3();
b.display();
}
}
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class
instance variable that is why we use super keyword to distinguish between parent class
instance variable and current class instance variable.

//example of super keyword


class Vehicle
{
int speed=50;
}

class Bike4 extends Vehicle


{
int speed=100;

void display()
{
System.out.println(super.speed);//will print speed of Vehicle no
w
}

public static void main(String args[])


{
Bike4 b=new Bike4();
b.display();
}
}
Output:50

super is used to invoke parent class constructor.


class Vehicle
{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike5 extends Vehicle


mpm@cimdr.sangli Page 95
Java Programming

{
Bike5()
{
super();//will invoke parent class constructor
System.out.println("Bike is created");
}

public static void main(String args[])


{
Bike5 b=new Bike5();
}
}
Output:Vehicle is created
Bike is created
Note: super() is added in each class constructor automatically by compiler.

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");}
}

class Bike6 extends Vehicle


{
int speed;
Bike6(int speed)
{
this.speed=speed;
System.out.println(speed);
}

public static void main(String args[])


{
Bike6 b=new Bike6(10);
}
}
Output:Vehicle is created
10

Super can be used to invoke parent class method


class Person
{
void message(){System.out.println("welcome");}
}

class Student16 extends Person


{

mpm@cimdr.sangli Page 96
Java Programming

void message(){System.out.println("welcome to java");}

void display()
{
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}

public static void main(String args[])


{
Student16 s=new Student16();
s.display();
}
}
Output:welcome to java
welcome

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

//Program in case super is not required


class Person
{
void message(){System.out.println("welcome");}
}

class Student17 extends Person


{
void display()
{
message();//will invoke parent class message() method
}

public static void main(String args[])


{
Student17 s=new Student17();
s.display();
}
}

mpm@cimdr.sangli Page 97
Java Programming

Unit 4: AWT SWING (JFC)

AWT (Abstract Window Toolkit)

Abstract Window Toolkit (AWT) is a toolkit of classes in Java which helps a


programmer to develop Graphics and Graphical User Interface components. It is a part of
JFC (Java Foundation Classes) developed by Sun Microsystems. The AWT API in Java
primarily consists of a comprehensive set of classes and methods that are required for
creating and managing the Graphical User Interface (GUI) in a simplified manner. It was
developed for providing a common set of tools for designing the cross-platform GUIs. One
of the important features of AWT is that it is platform dependent. This means that the AWT
tools use the native toolkits of the platforms they are being implemented. This approach
helps in preserving the look and feel of each platform. There is a major drawback of this
approach. When executed on various platforms because of platform dependency it will look
different on each platform. This hampers the consistency and aesthetics of an application.

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.

Features of AWT in Java


 AWT is a set of native user interface components
 It is based upon a robust event-handling model
 It provides Graphics and imaging tools, such as shape, color, and font classes
 AWT also avails layout managers which helps in increasing the flexibility of the
window layouts
 Data transfer classes are also a part of AWT that helps in cut-and-paste through the
native platform clipboard
 Supports a wide range of libraries that are necessary for creating graphics for gaming
products, banking services, educational purposes, etc.

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);

A few of the methods provided by TextField class are:


// Get the current text on this TextField instance
public String getText();
// Set the display text on this TextField instance
public void setText(String strText);
//Set this TextField to editable (read/write) or non-editable (read-
only)
public void setEditable(boolean editable);

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();

This class also provides 3 constants which are:


mpm@cimdr.sangli Page 100
Java Programming

public static final LEFT; // Label.LEFT


public static final RIGHT; // Label.RIGHT
public static final CENTER; // Label.CENTER

Below listed down the public methods provided by this class:


public String getText();
public void setText(String strLabel);
public int getAlignment();
//Label.LEFT, Label.RIGHT, Label.CENTER
public void setAlignment(int alignment);

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.

9. CheckBox: The Checkbox is a class is a graphical component that is used to create a


checkbox. It has two state options; true and false. At any point in time, it can have either of
the two.

Java AWT Example


To understand the differences between Awt and Swing, we have created the same example in
awt as well. Consider the following example.

import java.awt.*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);

Label lastName = new Label("Last Name");


lastName.setBounds(20, 80, 80, 20);

Label dob = new Label("Date of Birth");


dob.setBounds(20, 110, 80, 20);

mpm@cimdr.sangli Page 101


Java Programming

TextField firstNameTF = new TextField();


firstNameTF.setBounds(120, 50, 100, 20);

TextField lastNameTF = new TextField();


lastNameTF.setBounds(120, 80, 100, 20);

TextField dobTF = new TextField();


dobTF.setBounds(120, 110, 100, 20);

Button sbmt = new Button("Submit");


sbmt.setBounds(20, 160, 100, 30);

Button reset = new Button("Reset");


reset.setBounds(120,160,100,30);

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:

mpm@cimdr.sangli Page 102


Java Programming

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).

Components of Swing: The prime 12 AWT Components are

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.

4. JTextField: JTextField renders an editable single-line text box. A user is allowed to


input non-formatted text in the box.

5. JPasswordField: JPasswordField is a subclass of JTextField class. It renders a text


box that masks the user input text with bullet points. This is used for inserting
passwords into the application.

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.

7. JRadioButton: JRadioButton is used to render a group of radio buttons in the UI. A


designer can select one choice from the group.

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.

9. JComboBox: JComboBox class is used to render a dropdown of the list of options.

10.JFileChooser: JFileChooser class renders a file selection utility. This component


allows a designer to select a file from the local system.

11.JTabbedPane: JTabbedPane is another essential component that allows the designer


to switch between tabs in an application. This is a highly useful UI component as it
allows the designer to browse more content without navigating to different pages.

mpm@cimdr.sangli Page 103


Java Programming

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();

JLabel firstName = new JLabel("First Name");


firstName.setBounds(20, 50, 80, 20);

JLabel lastName = new JLabel("Last Name");


lastName.setBounds(20, 80, 80, 20);

mpm@cimdr.sangli Page 104


Java Programming

JLabel dob = new JLabel("Date of Birth");


dob.setBounds(20, 110, 80, 20);

JTextField firstNameTF = new JTextField();


firstNameTF.setBounds(120, 50, 100, 20);

JTextField lastNameTF = new JTextField();


lastNameTF.setBounds(120, 80, 100, 20);

JTextField dobTF = new JTextField();


dobTF.setBounds(120, 110, 100, 20);

JButton sbmt = new JButton("Submit");


sbmt.setBounds(20, 160, 100, 30);

JButton reset = new JButton("Reset");


reset.setBounds(120,160,100,30);

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);
}

public static void main(String[] args) {


// TODO Auto-generated method stub
SwingApp s = new SwingApp();
}
}

Output:

mpm@cimdr.sangli Page 105


Java Programming

Difference between AWT and SWING

Context AWT Swing


The AWT Component classes are
The Swing component classes are
API Package provided by the java.awt package.
provided by the javax.swing package.
The Components used in Swing are
The Components used in AWT
Operating not dependent on the operating
are mainly dependent on the
System system. It is completely scripted in
operating system.
Java.
The Swing is mostly lightweight since
The AWT is heavyweight since it it doesn't need any Operating system
Weightiness uses the resources of the operating object for processing. The Swing
system. Components are built on the top of
AWT.
The Appearance of AWT
Components is mainly not The Swing Components are
Appearance configurable. It generally depends configurable and mainly support
on the operating system's look and pluggable look and feel.
feels.
Java Swing provides a greater number
The Java AWT provides a smaller
Number of of components than AWT, such as list,
number of components in
Components scroll panes, tables, colour choosers,
comparison to Swing.
etc.
Java AWT stands for Abstract Java Swing is mainly referred to as
Full-Form
Window Toolkit. Java Foundation Classes (JFC).
Java Swing has only one peer in the
Java AWT has 21 peers. There is
form of OS's window object, which
one peer for each control and one
provides the drawing surface used to
Peers peer for the dialogue. Peers are
draw the Swing's widgets (label,
provided by the operating system
button, entry fields, etc.) developed
in the form of widgets themselves.
directly by Java Swing Package.
Java AWT many features that are
Swing components provide the higher-
Functionality completely developed by the
level inbuilt functions for the
and developer. It serves as a thin layer
developer that facilitates the coder to
Implementation of development on the top of the
write less code.
OS.
Java AWT needs a higher amount Java Swing needs less memory space
Memory
of memory for the execution. as compared to Java AWT.
Java AWT is slower than swing in
Speed Java Swing is faster than the AWT.
terms of performance.

mpm@cimdr.sangli Page 106

You might also like