0% found this document useful (0 votes)
2 views

java_Notes1

The document provides a comprehensive overview of the history and features of the Java programming language, detailing its development by Sun Microsystems in 1991 and its evolution from the Oak language. It outlines key characteristics such as simplicity, security, portability, object-oriented design, robustness, multithreading, and dynamic capabilities. Additionally, the document explains Java tokens, identifiers, keywords, literals, operators, and includes a simple Java program example.

Uploaded by

futurtech2024
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java_Notes1

The document provides a comprehensive overview of the history and features of the Java programming language, detailing its development by Sun Microsystems in 1991 and its evolution from the Oak language. It outlines key characteristics such as simplicity, security, portability, object-oriented design, robustness, multithreading, and dynamic capabilities. Additionally, the document explains Java tokens, identifiers, keywords, literals, operators, and includes a simple Java program example.

Uploaded by

futurtech2024
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 148

Java Brilliant

HISTORY OF JAVA
In 1991, Sun Microsystems was attempting to develop a nework technology for
programming next generation smart appliances.

The original plan was for the star7 operating

system to be developed in C++ but rejected the idea for several reasons. As a
result we have new language that was better for the purposes of the Green
project than C++ developed by Gosling. He called the language Oak in honor of a
tree that could be seen from his office window.

James Gosling was part of Green, an isolated research project at Sun that was
studying how to put computers into everyday household items like thoughtful
toasters, sagacious Salad Shooters and lucid lamps. The group also wanted these
devices to communicate with each other.

So The Greens built a prototype device called Star7. This gadget was a handheld
remote control operated by touching animated objects on the screen. The
universe featured Duke-immortalized later as Java's mascot

Sun found that Oak could not be trademarked because of a product already using
the name.

After sessions in January 1995, The meeting, arranged by Kim Polese (marketing
person) where about a dozen people got together to brainstorm with James
Gosling, a vice president and fellow of Sun, and the author of Oak, the final
suggest names were Silk, DNA, Ruby, WRL and Java by the team in meeting But
the other names could not trademark. So finally JAVA was the name chosen
because it sounded the coolest and decided to go ahead with it and name was
first suggested by Chris Warth.

Features of Java:
1) Simple and Powerful

If the user already understands the basic concepts of object-oriented


programming, learning Java with be much easier, Because Java inherits the
C/C++ syntax and many of the object-oriented features of C++. so we can say
that Java was designed to be easy to learn and use.

java provides a small number of clear ways to achieve a given task.

Unlike other programming systems that they provide dozens of complicated ways
to perform a simple task.

2) Secure

Using Java Compatible Browser, anyone can safely download Java applets
without the fear of viral infection or malicious intent because of its key design

1
Java Brilliant

principle. So anyone can download applets with confidence that no harm will be
done and no security will be violated.

Java achieves this protection by confining a Java program to the Java


execution environment and by making it inaccessible to other parts of the
computer.

3) Portable

Many types of computers and operating systems are in use throughout the
world—and many are connected to the Internet. Java makes it possible to
have the assurance that any result on one computer with Java can be
replicated on another. So the code is run in the different platform has a
same result.

4) Object-oriented

Java support the all the features of object oriented programming language
such as Abstraction, Encapsulation, Inheritance, Polymorphism and
Dynamic binding etc….

So with the help of these features user can reduce the complexity of the
program develops in JAVA.

Java gave a clean, usable, realistic approach to objects so we can say that
the object model in Java is simple and easy to extend.

5) Robust

Most programs in use today fail for one of the two reasons:

(i) memory management mistakes

For example, in C/C++, the programmer must manually allocate and free
all dynamic memory. This sometimes leads to problems, because
programmers will either forget to free memory that has been previously
allocated or, sometimes try to free some memory that another part of their
code is still using. Java virtually eliminates these problems by managing
memory allocation (with the help of new operator) and deallocation.
(deallocation is completely automatic, because Java provides garbage
collection for unused objects.)

(ii) mishandled exceptional conditions

With the help of Exception Handling (try……….catch block), the programmer can
easily handle an error or exception so user can prevent the program by
automatically stop the execution when an exception found.

Thus, the ability to create robust programs was given a high priority in the
design of Java.

6) Multithreaded

Java supports programming, which allows the user to write programs that
perform many functions simultaneously.

2
Java Brilliant

The two or more part of the program can run concurrently then each part of such
a program is called a Thread and this type of programming is called
multithreaded programming.

Each thread defines a separate path of execution. Thus, multithreading is a


specialized form of multitasking.

7) Architecture-neutral

The Java designers worked hard in achieving their goal “write once; run
anywhere, anytime, forever” and as a result the Java Virtual Machine was
developed.

Java is Architecture-neutral it generates bytecode that resembles machine code,


and are not specific to any processor.

8) Interpreted and High performance

The source code is first compile and generates the code into an intermediate
representation called Java bytecode which is a highly optimized set of instruction
code.

This code can be interpreted on any system that has a Java Virtual Machine and
generates the machine code.

Java bytecode was carefully designed by using a just-in-time compiler so that it


can be easily translated into native machine code for very high performance.

Most of the earlier cross-platform solutions are run at the expense of


performance.

9) Distributed

Java allows the object can access the information across the network with the
help of RMI (Remote Method Invocation) means this allowed objects on two
different computers to execute procedures remotely. So this feature supports the
client/server programming.

10) Dynamic

Java programs carry with them substantial amounts of run-time type information
that is used to verify and resolve accesses to objects at run time. This makes it
possible to dynamically link code in a safe and perfect manner.

Token :
A token is the smallest element of a program that is meaningful to the compiler.
(Actually, this definition is true for all compilers, not just the Java compiler.)
These tokens define the structure of the Java language. When you submit a Java
program to the Java compiler, the compiler parses the text and extracts
individual tokens.

3
Java Brilliant

Java tokens can be broken into five categories: identifiers, keywords, literals,
operators, and separators. The Java compiler also recognizes and subsequently
removes comments and whitespaces.

Identifiers :
“Identifiers means a sequence of uppercase(A,B,C,……,Y,Z) and
lowercase(a,b,c,…..,y,z) letters, numbers(0,1 ,2,……,9), or the underscore(_) and
dollar-sign($) characters and must not begin with a number.” Identifiers are
tokens that represent names. These names can be assigned to variables,
methods, and classes to uniquely identify them to the compiler.

Valid and invalid Java identifiers.

Valid Invalid
HelloWorld Hello World (uses a space)
Hi_JAVA Hi JAVA! (uses a space and punctuation mark)
value3 3value(begins with a number)
Tall short (this is a Java keyword)
#age (does not begin with any other symbol
$age
except _ $ )

NOTE : For Java identifiers, you should follow a few stylistic rules to make Java
programming easier and more consistent. It is standard Java practice to name
multiple-word identifiers in lowercase except for the beginning letter of words in
the middle of the name. For example, the variable firstValue is in correct Java
style; the variables firstvalue, FirstValue, and FIRSTVALUE are all in violation of
this style rule.

Another more critical naming issue regards the use of underscore and dollar-sign
characters at the beginning of identifier names. Using either of these characters
at the beginning of identifier names is a little risky because many C libraries use
the same naming convention for libraries, which can be imported into your Java
code. A good use of the underscore character is to use it to separate words
where you normally would use a space (Hi_JAVA).

Keywords :
“It is a special type of reserved word for a specific purpose which can not be use
as a identifier means cannot be used as names for a variable, class, or method.”

There are 49 reserved keywords currently defined in the Java language (see the
following table).

abstract Double int Switch


assert Else interface Synchronized
boolean Extends long This
Break False native Throw
Byte Final new Transient
Case Finally package True
Catch Float private Try
Char For protected Void
4
Java Brilliant

Class Goto public Volatile


const If return While
continue Implements short
default Import static
do Instanceof super

The keywords const and goto are reserved but not used. In the early days of
Java,several other keywords were reserved for possible future use.

In addition to the keywords, Java reserves the following: true, false, and null.

These are values defined by Java. You may not use these words for the names
of variables, classes, and so on.

Separators :
Separators are used to inform the Java compiler of how things are grouped in the
code. For example, items in a list are separated by commas much like lists of
items in a sentence. The most commonly used separator in Java is the semicolon.
As you have seen, it is used to terminate statements.

Symbol Name Purpose


; Semicolon Terminates statements.
Separates consecutive identifiers in a variable

, Comma declaration.

Also used to chain statements together inside a for statement.


Used to contain the values of automatically initialized arrays.
{} Braces
Also used to define a block of code, for classes, methods, and local
scopes.
Used to contain lists of parameters in method definition and
invocation.

() Parentheses Also used for defining precedence in expressions, containing


expressions in control statements.

Also used for surrounding cast types.


Used to declare array types.
[] Brackets
Also used when dereferencing array values.
Used to separate package names from subpackages and classes Also
. Period
used to separate a variable or method from a reference variable.

Literals :
We describe this topic in next chapter named Literals.

5
Java Brilliant

Comments and Whitespaces :


The comments and whitespaces are removed by the Java compiler during the
tokenization of the source code. White space consists of spaces, tabs, and
linefeeds. All occurrences of spaces, tabs, or linefeeds are removed by the Java
compiler, as are comments. Comments can be defined in three different ways, as
shown in Table.

Types of comments supported by Java.

Type Syntax Usage Example


//This is a
// All characters after the // up to the
Single-line Single-line style
comment end of the line are ignored.
comment.
/* /* This is a
All characters between /* and */
Multiline comment Multiline style
are ignored.
*/ comment.
Same as /* */, except that the
/** /** This is a
comment can be used with the
Documentation comment javadoc style
javadoc tool to create automatic
*/ comment. */
documentation.

Operators :
Operators means specify an evaluation to be performed on a data (Operands).
The operators supported by Java is as under :

+ - * / % & |
^ ~ && || ! < >
<= >= << >> >>> = ?
++ -- == += -= *= /=
%= &= |= ^= != <<= >>=
>>>= . [ ] ( )

Just seeing these operators probably doesn't help you a lot in determining how
to use them. Don't worry-you'll learn a lot more about operators and how they
are used in the next chapter “Operators”.

Literals :
A constant value in Java is created by using a literal representation of it.

For example, Here are some literals :

integer literal value : 100

floating-point literal value : 98.6

character literal value : ‘X’

6
Java Brilliant

string literal value : “This is a test”

A literal can be used anywhere a value of its type is allowed.

Integer Literals :
Integer literals are the primary literals used in Java programming. They come in
a few different formats: decimal, hexadecimal, and octal. These formats
correspond to the base of the number system used by the literal.

Decimal (base 10) literals appear as ordinary numbers with no special notation.
Hexadecimal numbers (base 16) appear with a leading 0x or 0X. Octal (base 8)
numbers appear with a leading 0 in front of the digits.

For example, an integer literal for the decimal number 12 is represented in Java
as 12 in decimal, 0xC in hexadecimal, and 014 in octal.

Integer literals default to being stored in the int type, which is a signed 32-bit
value. If you are working with very large numbers, you can force an integer
literal to be stored in the long type by appending an l or L to the end of the
number, as in 79L. The long type is a signed 64-bit value.

Floating-Point Literals :
Floating-point literals represent decimal numbers with fractional parts, such
as 3.1415. They can be expressed in either standard or scientific notation,
meaning that the number 143.85 also can be expressed as 1.4385e2.

Unlike integer literals, floating-point literals default to the double type, which is a
64-bit value. You have the option of using the smaller 32-bit float type if you
know the full 64 bits are not required. You do this by appending an f or F to the
end of the number, as in 5.6384e2f.

If you are a stickler for details, you also can explicitly state that you want
a double type as the storage unit for your literal, as in 3.142d. But because the
default storage for floating-point numbers is double already, this addition isn't
necessary.

Boolean Literals :
Boolean literals are certainly welcome if you are coming from the world of
C/C++. In C, there is no boolean type, and therefore no boolean literals. The
boolean values true and false are represented by the integer values 1 and 0.

Java fixes this problem by providing a boolean type with two possible
states: true and false. Not surprisingly, these states are represented in the Java
language by the keywords true and false.

Boolean literals are used in Java programming about as often as integer literals
because they are present in almost every type of control structure. Any time you
need to represent a condition or state with two possible values, a boolean is what
you need. The two boolean literal values: true and false.

7
Java Brilliant

Character Literals :
Character literals represent a single Unicode character and appear within a pair
of single quotation marks. Special characters (control characters and characters
that cannot be printed) are represented by a backslash (\) followed by the
character code.

A good example of a special character is \n, which forces the output to a new line
when printed. Table shows the special characters supported by Java.

Description Representation
Backslash \\
Continuation \
Backspace \b
Carriage return \r
Form feed \f
Horizontal tab \t
Newline \n
Single quote \'
Double quote \"
Unicode character \udddd
Octal character \ddd

An example of a Unicode character literal is \u0048, which is a hexadecimal


representation of the character H. This same character is represented in octal
as \110.

String Literals :
String literals represent multiple characters and appear within a pair of double
quotation marks. Unlike all the other literals discussed in this chapter, string
literals are implemented in Java by the String class. This arrangement is very
different from the C/C++ representation of strings as an array of characters.

When Java encounters a string literal, it creates an instance of the String class
and sets its state to the characters appearing within the double quotes.

Looking at First Java program :

This is demonstrating simple example program that displays the text,” My First
JAVA program...............” on the console.

public class FirstProg


{ //This is a first simple java program.
public static void main(String[] args)
{
System.out.println("My First JAVA program...............");
}

8
Java Brilliant

Explanation :

public :

A keyword of the Java language that indicates that the element that follows
should be made available to other Java elements.

As a result, this keyword indicates that the FirstProg class is a


public class, which means other classes can use it.

class :

Another Java keyword that indicates that the element being defined here is a
class. All Java programs are made up of one or more classes.

A class definition contains code that defines the behavior of the objects created
and used by the program.

FirstProg :

An identifier that provides the name for the class being defined here. While
keywords, such as public and class, are words that are defined by the Java
programming language, identifiers are words that you create to provide names
for various elements you use in your program.

In this case, the identifier FirstProg provides a name for the public class being
defined here.

{ :

The opening brace on line 2 marks the beginning of the body of the class. The
end of the body is marked by the closing brace on line 7.

Everything that appears within these braces belongs to the class. As you work
with Java, you’ll find that it uses these braces a lot.

//This is a first simple java program. :

This is a comment. Like most other programming languages, Java lets you enter
a remark into a program’s source file.

The contents of a comment are ignored by the compiler. Instead, a comment


describes or explains the operation of the program to anyone who is reading its
source code.

In this case, the comment describes the program and reminds you that the
source file should be called FirstProg.java. Of course, in real applications,
comments generally explain how some part of the program works or what a
specific feature does.

Java supports three styles of comments. The one shown at this program is called
a single-line comment. This type of comment must begin with // as shown in the
program.
9
Java Brilliant

The second style of the comment is multiline comment. This type of comment
must begin with /* and end with */. Anything between these two comment
symbols is ignored by the compiler. As the name suggests, a multiline comment
may be several lines long.

For example :

/*This is a first

simple java program. */

The third style of the comment is documentation comment. This type of comment
is used to produce an HTML file that documents your program.

The documentation comment begins with a /** and ends with a */.
Documentation comments are explained in next chapter.

public :

The public keyword is used again, this time to indicate that a method being
declared here should have public access.

That means classes other than the FirstProg class can use it. All Java programs
must have at least one class that declares a public method named main.

The main method contains the statements that are executed when you run the
program.

static :

If you are want to execute any elements (properties) without an object means
before the object creating then it must declare a static so compiler directly
execute those static elements.

Here the main method is executed before the any object is creating so it must
declare a static. The keyword static allows main( ) to be called without having to
instantiate a particular instance of the class.

This is necessary since main( ) is called by the Java interpreter before any
objects are made.

You find all about the static keyword in next Chapter.

For now, just take my word that the Java language requires that you specify
static when you declare the main method.

void :

In Java, a method is a unit of code that can calculate and return a value.

For example :

you could create a method that adds two numbers. Then, the addition would be
the return value of the method.

10
Java Brilliant

If a method doesn’t need to return a value, you must use the void keyword to
indicate that no value is returned. Because Java requires that the main method
not return a value, you must specify void when you declare the main method.

main :

Finally, the identifier that provides the name for this method.

Java requires that this method be named main because main( ) is the method
called when a Java application begins.

Besides the main method, you can also create additional methods with whatever
names you want to use.

(String[] args) :

It’s called a parameter list, and it’s used to pass data to a method.

Java requires that the main method must receive a single parameter that’s an
array of String objects.

By convention, this parameter is named args. If you don’t know what a


parameter, a String, or an array is, don’t worry about it You can find out what a
String, parameters and arrays are in the next chapter.

You have to write (String[] args) on the declaration for the main methods in all
your programs. In this case, args receives any command-line arguments present
when the program is executed.

This program does not make use of this information, but other programs shown
later in further chapter for command-line argument.

Another { :

Another set of braces begins at line 4 and ends at line 6. These mark the body of
the main method.

Notice that the closing brace in line 6 is paired with the opening brace in line 4,
while the closing brace in line 7 is paired with the one in line 2.

This type of pairing is commonplace in Java. In short, whenever you come to a


closing brace, it is paired with the most recent opening brace that hasn’t already
been closed — that is, that hasn’t already been paired with a closing brace.

System.out.println(“My First JAVA program...............”); :

This is the only statement in the entire program. It calls a method named println
that belongs to the System.out object.

System is a predefined class, it is automatically included in your programs that


provides access to the system and out is the output stream that is connected to
the console.

11
Java Brilliant

The println method displays a line of text on the console. The text to be displayed
is passed to the println method as a parameter in parentheses following the word
println.

In this case, the text is the string literal My First JAVA program...............
enclosed in a set of double quotation marks. As a result, this statement displays
the text My First JAVA program............... on the console.

Note: In Java, statements end with a semicolon. Because this is the only
statement in the program, this line is the only one that requires a semicolon.

Java is case-sensitive. Thus, Main is different from main.

}:

Line 6 contains the closing brace that marks the end of the main method body
that was begun by the brace on line 4.

Another } :

Line 7 contains the closing brace that marks the end of the FirstProg class body
that was begun by the brace on line 2. Because this program consists of just one
class, this line also marks the end of the program.

To run this program, first of all save a text file named FirstProg.java .
Then, compile it by running this command at a command prompt:

javac FirstProg.java

This command creates a class file named FirstProg.class that contains

the Java bytecodes compiled for the FirstProg class.

Now run the program by entering this command:

java FirstProg

Output :

My First JAVA program...............

12
Java Brilliant

Data types introduction in java:


You people now know the basic introduction and features of java. Here in this
chapter now we move to data types supported by java. If you have knowlege of C
language than you might be know about data types. The use and need of data
types in programming language is to declare a variables which can store the
differnent kind of value as per the data types.

Example:

int a;

char c;

float b;

Here "int" is a data type and "a" is variable which can store any natural nuber.

Here "char" is a data type and "c" is variable which can store any character
value.

Here "float" is a data type and "b" is variable which can store any floating point
value.

13
Java Brilliant

In next chapter you will get data types and variables in detail.

Data type in java:


We all know the data and its type. For storing different type of data we have data
types.

Java defines eight types of data: byte, short, int, long, float, double, char and
boolean.

These can be put in four groups.

Integers:This group includes byte, short, int, and long, which are for signed
and unsigned number including zero.

Floating-point numbers:This group includes float and double, which can store
numbers with fractional precision.

Characters:This group includes char, which represents symbols in a


characterset, like letters and numbers.

Boolean:This group includes boolean, which is a special type for representing


true/false values.

Now we elaborate each data type in detail.

NOTE: The data types mentioned above are primitive data types. Java also
support reference data types like Array, Class and Interface. We will study those
things in further chapter when needed.

1. Integers:
Java defines four integer types: byte, short, int, and long. All of these can have
signed unsigned or zero value. Java does not support unsigned, positive-only
integers.

Name Width (in bits) Range

long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

int 32 –2,147,483,648 to 2,147,483,647

short 16 –32,768 to 32,767

byte 08 –128 to 127

Note: Divide width with 8 to get size in Bytes;

the table mentioned above is providing width and range of the integer data type.
Width is the size the data type will occupy in the program if you write int a,b;
than a and b both will occupy 32 bits (4 bytes) in memory.

14
Java Brilliant

1.1 byte
The smallest integer type is byte. This is a signed 8-bit type that has a range
from –128 to 127

Ex. byte b1;

Variables of type byte are especially useful when you’re working with a stream

of data from a network or file.

1.2 short
Short is a signed 16-bit type. It has a range from –32,768 to 32,767

so if you are sure that your value will not more than the range of Short data type
than and only we recommended to use this.

Ex short s1,s2;

1.3 int
The most commonly used integer type is int. It is a signed 32-bit type that has a
range

from –2,147,483,648 to 2,147,483,647.

Ex. int a, b;

1.4 long
long is a signed 64-bit type and is useful for those occasions where an int type is
not

large eno ugh to hold the desired value. The range of a long is quite large. This
makes

it useful when big, whole numbers are needed.

public class IDemo


{
public static void main(String[] args)
{
byte b1=50,b2=0; //declare and define the byte variable
short s1=10,s2=20; //declare and define the short variable
int i1=-555,i2=123; //declare and define the int variable
long l1=100000,l2=2033; //declare and define the long variable
System.out.print("The value of different variables");
System.out.println(" of type integers is.........");
System.out.println("byte integers : " + "b1 = " +b1 +" and b2 = " +b2);
System.out.println("short integers : " + "s1 = " +s1 +" and s2 = " +s2);
System.out.println("int integers : " + "i1 = " +i1 +" and i2 = " +i2);
System.out.println("long integers : " + "l1 = " +l1 +" and l2 = " +l2);
}
15
Java Brilliant

Output :
The value of different variables of type integers is.........
byte integers : b1 = 50 and b2 = 0
short integers : s1 = 10 and s2 = 20
int integers : i1 = -555 and i2 = 123
long integers : l1 = 100000 and l2 = 2033

2. Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating

expressions that require fractional precision. For example, calculations such as


square

root, or transcendental such as sine and cosine, result in a value whose precision

requires a floating-point type.

Name Width in Bits Approximate Range

double 64 4.9e–324 to 1.8e+308

float 32 1.4e-045 to 3.4e+038

2.1 float
The type float specifies a single-precision value that uses 32 bits of storage.
Single

precision is faster on some processors and takes half as much space as double

precision, but will become imprecise when the values are either very large or
very small.

When you require to store floating point value use float and double.

Ex. float r, pi;

2.2 double
Double precision, as denoted by the double keyword, uses 64 bits to store a
value. Double

precision is actually faster than single precision on some modern processors that
have

been optimized for high-speed mathematical calculations.

//Demonstrate floating point data type.


public class FDemo
{
public static void main(String[] args)

16
Java Brilliant

{
float f1=1.2f,f2=123.2f; //declare and define the float variable
double d1=1.234,d2=23.4512; //declare and define the double variable
System.out.print("The value of different variables");
System.out.println(" of type floating point is........");
System.out.println("float value : " + "f1 = " +f1 +" and f2 = " +f2);
System.out.println("double value : " + "d1 = " +d1 +" and d2 =
" +d2);
}
}

Output :
The value of different variables of type floating point is........
float value : f1 = 1.2 and f2 = 123.2
double value : d1 = 1.234 and d2 = 23.4512

3. Characters:
In Java, the data type used to store characters is char.

NOTE: However, C/C++ programmers beware: char in Java is not the same as
char in C or

C++. In C/C++, char is an integer type that is 8 bits wide. This is not the case in
Java.

Instead, Java uses Unicode to represent characters.

Unicode defines a fully international character set that can represent all of the
characters

found in all human languages.

In Java char require 16-bit. The range of a char is 0 to 65,536. There are no
negative chars.

The standard set of characters known as ASCII still ranges from 0 to 127. The
extended 8-

bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to
allow

applets to be written for worldwide use, it makes sense that it would use Unicode
to

represent characters.

//Demonstrate char data type.


public class CharDemo
{
public static void main(String[] args)

17
Java Brilliant

{
char ch1, ch2; // declare the char variable
ch1 = 88; // code for X
ch2 = 'Y'; // define the char variable
System.out.print("The value of type");
System.out.println(" character variable is........");
System.out.print("char data type : ch1 = "+ ch1 +" and ch2 =
"+ch2);
}
}

Output :
The value of type character variable is........
char data type : ch1 = X and ch2 = Y

4. Boolean:
Java has a simple type, called boolean, for logical values. It can have only one of
two

possible values, true or false. This is the type returned by all relational operators,
such as

a < b.

Ex. boolean b;

//Demonstrate boolean data type.


public class BoolTest
{
public static void main(String[] args)
{
boolean b; //declare the boolean variable
b = false; //define the boolean variable
System.out.print("The value of type");
System.out.println(" boolean variable is........");
System.out.println("boolean data type : b is " + b);
b = true; //define the boolean variable
System.out.println("boolean data type : b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
//never execute
// outcome of a relational operator is a boolean value
System.out.println("100 > 9 is " + (100 > 9));
}
}

Output :
The value of type boolean variable is........
boolean data type : b is false
boolean data type : b is true
This is executed.
100 > 9 is true

18
Java Brilliant

Variables:
The variable is the basic unit of storage in a Java program. A variable is defined
by
the combination of a type, an identifier and an optional initializer.

type is a data type or the name of a class or interface (class and interface will
discussed further).for identify the type of variable identifier is a variable
name.and optional initializer means users directly initialize the value to the
variable if they want.

Declare Variable
Now how we can declare a variable in java?

Syntax for declaring a variable is...

type identifier1=val , identifier2;

Ex.

int a=100, b; //initialize a and declare b.

byte z = 22; // initialize z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization

Java allows variables to be initialized dynamically. Take a look following


example.

public class VariableDemo


{
public static void main(String[] args)
{
int l = 10;
int b = 20;
int a;

a = l * b;
System.out.println("normal initaialization : area is = "+a);

int area = l * b; // its a dynamic initialization of variable name


area
System.out.println("dynamic initaialization : area is = "+area);
}
}

Output :
Normal initaialization : area is = 200
Dynamic initaialization : area is = 200

19
Java Brilliant

The Scope and Lifetime of Variables


Every variable have scope and life time throughout the program. Here we study
when the new scope will be create for how long time (Life time).

A block is begun with an opening curly brace and ended by a closing curly brace.
A block defines a scope.

We use so many variables in our program and declared these variables at the at
the start of the main( ) method.

Most other computer languages define two general categories of scopes: global
and local. However, these traditional scopes do not fit well with Java’s strict,
object oriented model.

Take a look below example.

// Demonstrate variable scope.


class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
}
y = x+10; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

Here we initialize variable x in main block but the varible y is initialized in if


block so scope of variable y is limited to if block.

So we will get error on line no. 14 because we are trying to access variable y
which is out side of its scope.

NOTE: we will study about scope and lifetime in further chapter.

Array : It is a bunch or you can say group of variables with same data types.

We already discussed primitive data types of java. Java has three reference data
types.

Data Type Description


Array A collection of several items of the same data type. For

20
Java Brilliant

example names of student.


Class A collection of variables and methods.
An abstract class created to implement multiple inheritance in
Interface
JAVA.

NOTE : Class and interface we discuss later in further chapter.

We have one dimensional and multidimensional array in java. It works


differently compare to C and C++ language.

Arrays can be declared in three ways:

Way Description Syntax Example


Only char ch[ ]; declares a
Just declares the
data type identifier[] character array
array.
Declaration named ch.
Declares and
char ch[] = new
allocates memory for data type identifier[]
Declaration and char[10]; declares an
the array elements =new data
creation array ch to store 10
using the reserved type[size];
characters.
word ‘new’.
char ch[]
Declares the array,
data type ={‘A’,’B’,’C’,’D’};
allocates memory for
Declaration, creation identifier[] = declares an array ch
it and assigns initial
and initialization {value1, value2, to store 4 pre-as
values to its
….ValueN}; signed character
elements.
values.

From the above table let me tell you one thing here we declare one char type
array and size of that array is 10. So we have 10 different char type variables like
ch[0] to ch[9]. Value in the square bracket is called index of the array and index
value of any array always start from 0.

Syntax :

One dimensional array :

Declaration syntax : type var-name[ ];

EX.

int month[ ];

Here we just declare month variable of type int array. But actually or physically
no array exist. To link this array into actual physical array of integers we have to
use new keyword.

Syntax : array-var = new type[size];

EX.

month = new month[12];

21
Java Brilliant

So obtaining an array is a two-step process. First, you must declare a variable of


the desired array type. Second, you must allocate the memory that will hold the
array, using new, and assign it to the array variable. Thus, in Java all arrays
are dynamically allocated.

So now we have 12 different int type variable month[0] to month[11].

It is possible to combine the declaration of the array variable with the allocation
of the array itself like...
int month[] = new int[12];

Multidimensional array :

Declaration syntax : type var-name[ ][ ];

EX.

int mat[ ][ ] = new int[4][5];

In Java, multidimensional arrays are actually arrays of arrays. To declare a


multidimensional array variable, specify each additional index using another set
of square brackets.

This allocates a 4 by 5 array and assigns it to mat. Internally this matrix is


implemented as an array of arrays of int. Conceptually, this array will look like
the one shown in figure.

From the above image we can easily understand the indexing of multi
dimensional array.

22
Java Brilliant

Introduction to java operator:


Operator: It is a symbol that tells the computer to perform mathematical and
logical calculation.

Java supports basically 6 types of operators.

1. Arithmatic operator

2. Bitwise operator

3. Relational operator

4. Boolean Logical operator

5. Assignment operator

6. Condetional operator

In next topic we describe all operators in detail.

Arithmetic operators in java:

public class ArithmeticDemo


{
public static void main(String[] args)
{
System.out.println("..............Arithmetic
operators.................");
System.out.println();
int a = 10;
int b = 3;
int c = 20;
int d = 30;
int e = 40;
int f = 50;
int i = 10;
int j = 5;
int m = 30;
int l = 3;
int o = 25;
int v = 6;
int z = 27;
int r = 8;
int add = a + b;
int sub = a - b;
int mul = a * b;
int div = a / b;
int mod = a % b;

System.out.println("<-------Basic Arithmetic operators------->");


System.out.println("Addition of a and b : a + b = 10 + 3 = "+add);

23
Java Brilliant

System.out.println("Subtraction of a and b : a - b = 10 - 3 =
"+sub);
System.out.println("Multiplication of a and b : a * b = 10 * 3 =
"+mul);
System.out.println("Division of a and b : a / b = 10 / 3 = "+div);
System.out.println("Modulus of a and b : a % b = 10 % 3 = "+mod);

System.out.println();
System.out.println("<-------Increment Operator------->");

// c = 20, d = 30
// post_incr = c++ => post_incr = c then c = c + 1 => post_incr = 20
and c = 20 + 1 = 21
// pree_incr = ++d => d = d + 1 then pree_incr = d => d = 30 + 1 =
31 and pree_incr = 31

System.out.println("Before Post-Increment of c = "+c);


int post_incr = c++;
System.out.println("Post-Increment of c : c++ = 20++ = "+post_incr);
System.out.println("After Post-Increment of c = "+c);
System.out.println("Before Pree-Increment of d = "+d);
int pree_incr = ++d;
System.out.println("Pree-Increment of d : ++d = ++30 = "+pree_incr);
System.out.println("After Pree-Increment of d = "+d);

System.out.println();
System.out.println("<-------Decrement Operator------->");

/* e = 40, f = 50
* post_decr = e-- => post_decr = e then e = e - 1 => post_decr = 40
and c = 40 - 1 = 39
* pree_decr = --f => f = f - 1 then pree_decr = f => f = 50 - 1 =
49 and pree_decr = 49
*/

System.out.println("Before Post-Decrement of c = "+e);


int post_decr = e--;
System.out.println("Post-Decrement of e : e-- = 40-- = "+post_decr);
System.out.println("After Post-Decrement of e = "+e);
System.out.println("Before Pree-Decrement of f = "+f);
int pree_decr = --f;
System.out.println("Pree-Decrement of f : --f = --50 = "+pree_decr);
System.out.println("After Pree-Decrement of f = "+f);

System.out.println();
System.out.println("<-------Assignment Operators------->");
System.out.println("Addition Assignment of a and b : a += b means
10+=3 => a = a + b => a = 10 + 3 = "+(a+=b));
System.out.println("Subtraction Assignment of i and j : i -= j means
10-=5 => i = i - j => i = 10 - 5 = "+(i-=j));
System.out.println("Multiplication Assignment of m and l : m *=l
means 30*=3 => m = m * l => m = 30 * 3 = "+(m*=l));
System.out.println("Division Assignment of o and v : o /= v means
25/=6 => o = o / v => o = 25 / 6 = "+(o/=v));
System.out.println("Modulus Assignment of z and r : z %= r means
27%=8 => z = z % r => z = 27 % 8 = "+(z%=r));
}
}
Output :

24
Java Brilliant

..............Arithmetic operators.................

<-------Basic Arithmetic operators------->


Addition of a and b : a + b = 10 + 3 = 13
Subtraction of a and b : a - b = 10 - 3 = 7
Multiplication of a and b : a * b = 10 * 3 = 30
Division of a and b : a / b = 10 / 3 = 3
Modulus of a and b : a % b = 10 % 3 = 1

<-------Increment Operator------->
Before Post-Increment of c = 20
Post-Increment of c : c++ = 20++ = 20
After Post-Increment of c = 21
Before Pree-Increment of d = 30
Pree-Increment of d : ++d = ++30 = 31
After Pree-Increment of d = 31

<-------Decrement Operator------->
Before Post-Decrement of c = 40
Post-Decrement of e : e-- = 40-- = 40
After Post-Decrement of e = 39
Before Pree-Decrement of f = 50
Pree-Decrement of f : --f = --50 = 49
After Pree-Decrement of f = 49

<-------Assignment Operators------->
Addition Assignment of a and b : a += b means 10+=3 => a = a + b => a = 10 +
3 = 13
Subtraction Assignment of i and j : i -= j means 10-=5 => i = i - j => i = 10 - 5 =
5
Multiplication Assignment of m and l : m *=l means 30*=3 => m = m * l => m =
30 * 3 = 90
Division Assignment of o and v : o /= v means 25/=6 => o = o / v => o = 25 / 6
=4
Modulus Assignment of z and r : z %= r means 27%=8 => z = z % r => z = 27
%8=3

OPERATOR MEANING EXPLANATION EXAMPLE RESULT


This sign is used
Bitwise
~ for inverts all the ~42 213
unary NOT
bits
Produce a 1 bit if
Bitwise
& both operands are 2&7 2
AND
also 1 otherwise 0
either of the bits
in the operands is
a 1,
| Bitwise OR 2|7 7
then the resultant
bit is a 1
otherwise 0
if exactly one
Bitwise operand is 1, then
^ exclusive 2^7 5
the result
OR

25
Java Brilliant

is 1. Otherwise,
the result is zero
The right shift
operator, >>,
shifts all of the
bits in a value to
>> Shift right 7 >> 2 1
the right a
specified number

of times.
shift a zero into
the high-order bit
Shift right no matter -1 >>>
>>> 3
zero fill 30
what its initial
value was
The left shift
operator, <<,
shifts all of the
bits in a value to
<< Shift left 2 << 2 8
the left a specified
number

of times.
This is a short
Bitwise a=2
sign of AND
&= AND a=2
operation on same
assignment a& = 2
variable
This is a short
a=2
Bitwise OR sign of OR
|= a=7
assignment operation on same
variable a| = 7
Bitwise This is a short
a=2
exclusive sign of XOR
^= a=5
OR operation on same
a^ = 7
assignment variable
This is a short
a=7
Shift right sign of shift right
>>= a=1
assignment operation on same
a>> = 2
variable
This is a short a = -1
Shift right
sign of shift right
>>>= zero fill a=3
zero fill operation a>>> =
assignment
on same variable 30
This is a short
a=2
Shift left sign of shift left
<<= a=8
assignment operation on same
a<< = 2
variable

EX.

public class BitewiseDemo


{
public static void main(String[] args)
{

26
Java Brilliant

System.out.println("..............Bitewise
operators.................");
System.out.println("<-------Bitewise Logical Operators------->");
String binary[] =
{"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "
1110", "1111"};
int a = 2; // 0 + 0 + 2 + 0 or 0010 in binary
int b = 7; // 0 + 4 + 2 + 1 or 0111 in binary
int c = a | b; //Bitwise AND operator
int d = a & b; //Bitwise OR operator
int e = a ^ b; //Bitwise XOR(exclusive OR) operator
int f = ~a & a ; //Bitwise unary NOT operator, a = 0010 so ~a =
1101 hence f = ~a & a = 1101 & 0010 = 0000
int g = (~a & b) | (a & ~b);
System.out.println("The binary value of a = " + binary[a]);
System.out.println("The binary value of b = " + binary[b]);
System.out.println("The Bitwise OR : a | b = " + binary[c] + " and
Decimal value = "+c);
System.out.println("The Bitwise AND : a & b = " + binary[d] + " and
Decimal value = "+d);
System.out.println("The Bitwise XOR(exclusive OR) : a ^ b = " +
binary[e] + " and Decimal value = "+e);
System.out.println("The Bitwise unary NOT : ~a & a = " + binary[f]
+ " and Decimal value = "+f);
System.out.println("~a&b|a&~b = " + binary[g]+ " and Decimal value =
"+g);

System.out.println();
System.out.println("<-------Bitewise Shift Operators------->");

System.out.println("The original binary value of a = " +binary[a] + "


and Decimal value of a = "+a);
a = a << 2; //Bitwise Left shift operator
System.out.println("The Left shift : a = a << 2 means a = 0010 << 2
hence a = "+binary[a] + " and Decimal value of a = "+a);

System.out.println("The original binary value of b = " +binary[b] + "


and Decimal value of b = "+b);
b = b >> 2; //Bitwise Right shift operator
System.out.println("The Right shift : b = b >> 2 means b = 0111 >>
2 hence b = "+binary[b] + " and Decimal value of b = "+b);

int u = -1;
System.out.println("The original decimal value of u = " +u);
u = u >>> 30; //Bitwise Unsigned Right shift operator
System.out.println("The Unsigned Right shift : u = u >>> 30 means u
= 11111111 11111111 11111111 11111111 >>> 30 hence u = "+binary[u] + " and
Decimal value of u = "+u);

System.out.println();
System.out.println("<-------Bitewise Assignment Operators------->");
int p = 5;
System.out.println("The original binary value of p = " +binary[p] + "
and Decimal value of p = "+p);
p >>= 2; //Bitewise shift Right Assignment Operator
System.out.println("The Bitewise Shift Right Assignment Operators :
p >>= 2 means p = p >> 2 hence p = 0101 >> 2 so p = "+binary[p] + " and
Decimal value of p = "+p);
27
Java Brilliant

/*Same as you can check Bitwise AND assignment,Bitwise OR


assignment,Bitwise exclusive OR assignment,
Shift right zero fill assignment,Shift left assignment */
}
}

Output :

..............Bitewise operators.................
<-------Bitewise Logical Operators------->
The binary value of a = 0010
The binary value of b = 0111
The Bitwise OR : a | b = 0111 and Decimal value = 7
The Bitwise AND : a & b = 0010 and Decimal value = 2
The Bitwise XOR(exclusive OR) : a ^ b = 0101 and Decimal value = 5
The Bitwise unary NOT : ~a & a = 0000 and Decimal value = 0
~a&b|a&~b = 0101 and Decimal value = 5

<-------Bitewise Shift Operators------->


The original binary value of a = 0010 and Decimal value of a = 2
The Left shift : a = a << 2 means a = 0010 << 2 hence a = 1000 and Decimal
value of a = 8
The original binary value of b = 0111 and Decimal value of b = 7
The Right shift : b = b >> 2 means b = 0111 >> 2 hence b = 0001 and Decimal
value of b = 1
The original decimal value of u = -1
The Unsigned Right shift : u = u >>> 30 means u = 11111111 11111111
11111111 11111111 >>> 30 hence u = 0011 and Decimal value of u = 3

<-------Bitewise Assignment Operators------->


The original binary value of p = 0101 and Decimal value of p = 5
The Bitewise Shift Right Assignment Operators : p >>= 2 means p = p >> 2
hence p = 0101 >> 2 so p = 0001 and Decimal value of p = 1

OPERATOR MEANING EXPLANATION EXAMPLE RESULT


This sign is
== Equal to for check 10==10 true
equality
This sign is
Not equal
!= for check 10!=10 false
to
Inequality
This sign is
Greater
> for check 10>10 false
than
greater value
This sign is
< Less than for check 10<10 false
lesser value
This sign is
Greater for check
>= than or greater as 10>=10 true
equal to well as
equality
This sign is
Less than
for check
<= or equal 10<=10 true
lesser as well
to
as equality

28
Java Brilliant

public class RelationalDemo


{
public static void main(String[] args)
{
System.out.println("..............Relational
operators.................");
int mark = 70;
if(mark != 0) // != Not equal to
{
if(mark == 65 | mark > 65) // == Equal to, > Greater than
System.out.println("Congratulation ,You got a distinction and
you got " + mark + " marks........");
else if (mark < 65 & 60 <= mark) // < Less than, <= Less than or
equal to
System.out.println("Congratulation ,You got a First class and
you got " + mark + " marks........");
else if (mark < 60 & mark >= 50)
System.out.println("You got a Second class and you got " + mark
+ " marks........");
else if (50 > mark & mark >= 40) // > Greater than, >= Greater than
or equal to
System.out.println("You got a Third class and you got " + mark
+ " marks........");
else
System.out.println("You are failed and you got " + mark + "
marks........");
}
else
System.out.println("Please give the valid mark...............");
}
}

OPERATOR MEANING EXPLANATION EXAMPLE RESULT


Produce true if
Logical both operands are True &
& false
AND also true otherwise false
false
Produce true if one
of them operand is
| Logical OR true, True | false true

otherwise false
if exactly one
Logical operand is true,
XOR then the result True ^
^ true
(exclusive false
OR) is true. Otherwise,
the result is false
Check
Short- Check below
|| below -
circuit OR program
program
It will not check
Check
Short- the second
&& below -
circuit AND condition if the
program
first one is false

29
Java Brilliant

This sign is used


Logical
! for invert the !true false
unary NOT
result
This is a short sign
of Produce true if
Check
AND both operands are
&= below -
assignment also true otherwise
program
false on the same
operand
This is a short sign
of Produce true if
Check
OR one of the operand
|= below -
assignment is true otherwise
program
false on the same
operand
This is a short sign
of produce true if
exactly one Check
XOR
^= operand is true, below -
assignment
otherwise, the program
result is false on
the same operand

EX.

public class Boolean_LogicalDemo


{
public static void main(String[] args)
{
System.out.println("..............Boolean Logical
Operators.................");
System.out.println("<---------Basic Boolean Logical Operators-------
-->");
boolean a = false;
boolean b = true;
boolean c = a | b; //Logical AND operator
boolean d = a & b; //Logical OR operator
boolean e = a ^ b; //Logical XOR(exclusive OR) operator
boolean f = (!a & b) | (a & !b);
boolean g = !a; //Logical unary NOT operator
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println("Boolean Logical OR : a | b = " + c);
System.out.println("Boolean Logical AND : a & b = " + d);
System.out.println("Boolean Logical XOR(exclusive OR) : a ^ b = " +
e);
System.out.println("(!a & b) | (a & !b) = " + f);
System.out.println("!a = " + g);

System.out.println();
System.out.println("<---------Boolean Logical Assignment Operators--
------->");
System.out.println("Before apply assignment operator, the value of a
= "+a);
a &= b; //

30
Java Brilliant

System.out.println("After apply assignment operator : a &= b means a


= a & b hence now the value of a : "+a);
/*Same as you can check Boolean OR assignment,Boolean exclusive OR
assignment,
Boolean Equal to and Boolean Not equal to */
}
}

Output :

..............Boolean Logical Operators.................


<---------Basic Boolean Logical Operators--------->
a = false
b = true
Boolean Logical OR : a | b = true
Boolean Logical AND : a & b = false
Boolean Logical XOR(exclusive OR) : a ^ b = true
(!a & b) | (a & !b) = true
!a = true

<---------Boolean Logical Assignment Operators--------->


Before apply assignment operator, the value of a = false
After apply assignment operator : a &= b means a = a & b hence now the value
of a : false

public class Boolean_ShortCircuitDemo


{
public static void main(String[] args)
{
System.out.println("<---------Boolean Short-Circuit Operators-------
-->");
int i = 10;
int j = 20;

if (i != 10 && ++j/i>0)
{
System.out.println("i = "+i);
System.out.println("j = "+j);
}
System.out.println("In Short-circuit AND operator(&&): ");
System.out.println("Not checked the second condition in IF-BLECK if
first condition is false.........");
System.out.println("So,the value of j = "+j);
//Same as you can check Short-circuit OR operator(||)
}
}

Output :
<---------Boolean Short-Circuit Operators--------->
In Short-circuit AND operator(&&):
Not checked the second condition in IF-BLECK if first condition is false.........
So,the value of j = 20

var = expression;

int x, y, z;

x = y = z = 50; // set x, y, and z to 50


31
Java Brilliant

EX

public class Assignment_OperatorDemo


{
public static void main(String[] args)
{
System.out.println("<------------Assignment Operator-------------
>");
int x,y,z,sum;
x = y = z = 50; //The Assignment Operator which assign the value
to a varible
sum = x + y + z;
System.out.println("x + y + z = "+sum);
}
}

Output :

<------------Assignment Operator------------->
x + y + z = 150

It is also known as ternary operator or conditional operator.

expression1 ? expression2 : expression3

b = a < 0 ? -a : a;

EX.

public class TernaryDemo


{
public static void main(String[] args)
{
int a, b;
a = 50;
b = a < 0 ? -a : a; // get absolute value of a
System.out.println("The Absolute value of "+ a + " is " + b);
a = -10;
b = a < 0 ? -a : a; // get absolute value of a
System.out.println("The Absolute value of "+ a + " is " + b);
}
}

Output :

The Absolute value of 50 is 50


The Absolute value of -10 is 10

32
Java Brilliant

Java’s Selection Statements:


Java supports two selection statements: if and switch.

These statements allow you to control the flow of your program’s execution
based upon conditions known only during run time.

We will discuss these topics in detail in next two topics.

Before going further let us know something about Scanner class of java.

Scanner :

Let us start with one simple program for Scanner class.

import java.util.Scanner;
public class ScannerDemo
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in); // Here we initialize
object s for Scanner class.
System.out.print("Enter the first value a : ");
int a = s.nextInt(); // Scan int type value
System.out.print("Enter the second value b : ");
int b = s.nextInt(); // Scan int type value
int sum = a + b;
System.out.println("The addition of a and b : a + b = "+sum);
}
}

Output :

Enter the first value a : 5

33
Java Brilliant

Enter the second value b : 6

The addition of a and b : a + b = 11

Here we import java.uti.Scanner because the Scanner class is inside util package
of java library.

Than we create reference (object) of class Scanner named s.

"System.in" This is the predefine library which allow user to enter value in any
variable at run time through keyboard. We can say same as scanf() in c and cin
>> in c++.

Now in Scanner class there are so many different different methods for scaning
different type of values.

For Ex. in our program we use nextInt() method for scanning int type value.

Here are some in-built methods of Scanner class for scanning different types of
values.

1. nextByte() for scanning byte type value.

2. nextShort() for scanning short type value.

3. nextInt() for scanning int type value.

4. nextLong() for scanning long type value.

5. nextFloat() for scanning floting point value.

6. nextDouble() for scanning double type value.

7. next() for scanning a string.

if else if in java:
The if statement is Java’s conditional branch statement. It can be used to route
program
execution through two different paths.

Syntax :
if (condition)
{
statement1;
}

When the condition is true the Statement within the if is executed. After that
execution continues with the next statement after the if statement.

If the condition is false then the statement within the if is not executed and the
execution continues with the statement after the if statement.

34
Java Brilliant

EX.
?
import java.util.Scanner;
class larger1
{
public static void main(String args[])
{
int x1,x2,x3;
int large;
Scanner s = new Scanner(System.in);
System.out.println("Enter value for x1 : ");
x1=s.nextInt();
System.out.println("Enter value for x2 : ");
x2=s.nextInt();
System.out.println("Enter value for x3 : ");
x3=s.nextInt();
large = x1;
if (x2 > large)
large = x2;
if (x3 > large)
large = x3;
System.out.println("\n\n\tLargest number = " + large);
}
}

Output :
Largest number = 20

NOTE : The number of statement in if block is only one than parentheses are
optional but if its more than one than parentheses are compulsury. And if we
enter the same value in x1, x2 and x3 in above program than largest number is
x1 because our both condition will be false because here we checked only > not
>=.

EX.

if (condition)
{
Statement 1;
Statement 2;
}

Same as above, except that here multiple statements are executed if the
condition Is true.

if else :
Syntax :

if (condition)
{
statement1;
}
else
{
statement2;
}

35
Java Brilliant

The if else work like this: If the condition is true, then statement1 is executed.
Otherwise,
statement2 is executed. In no case will both statements be executed.

import java.util.Scanner;
class result
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter marks : ");
int marks = s.nextInt();
if (marks<40)
System.out.println("\nThe student has failed .. ");
else
System.out.println("\nThe student has Passed .. ");
}
}

Output :
The student has passed ..

NOTE : As above here also we can put multiple statements in if and else block.

if-else-if Ladder :
Syntax :

if(condition)
statements;
else if(condition)
statemenst;
else if(condition)
statements;
...
...
else
statements;

The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed.

If none of the conditions is true, then the final else statement will be executed.
The final else acts as a default condition; that is, if all other conditional tests fail,
then the last else statement is performed.

If there is no final else and all other conditions are false, then no action will take
place.

EX.
import java.util.Scanner;
class Day
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enet day between 1 to 7 Day = ");
36
Java Brilliant

int day = s.nextInt();


if (day == 7)
{
System.out.println("\n Sunday");
}
else if (day == 1)
{
System.out.println("\n Monday");
}
else if (day == 2)
{
System.out.println("\n Tuesday");
}
else if (day == 3)
{
System.out.println("\n Wednesday");
}
else if (day == 4)
{
System.out.println("\n Thursday");
}
else if (day == 5)
{
System.out.println("\n Friday");
}
else
{
System.out.println("\n Saturday");
}
}
}

Output :

Tuesday

Nested if :
A nested if is an if statement that is the target of another if or else.

Nested ifs are very common in programming.

Syntax :

if(condition)
{
if(condition)
statements....
else
statements....
}
else
{
if(condition)
statements....
else
statements....
}

EX.

37
Java Brilliant

import java.util.Scanner;
class MaxValue
{
public static void main(String args[])
{
int a,b,c;
int max=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter value for a : ");
a=s.nextInt();
System.out.println("Enter value for b : ");
b=s.nextInt();
System.out.println("Enter value for c : ");
c=s.nextInt();
if (a>b)
{
if(a>c)
max=a;
else //This else is associate with this if(a>c)
max=c;
}
else //This else is associate with this if(a>b)
{
if(b>c)
max=b;
else //This else is associate with this if(b>c)
max=c;
}
System.out.println("\n max value = " +max);
}
}

Output :
max value = 15

switch :
The switch statement is Java’s multiway branch statement. It provides an easy
way to dispatch execution to different parts of your code based on the value of
an expression.

It is difficult to understand large number of if else..if statements. So we have


switch statement.

Syntax :

switch (expression)
{
case value 1 :
statement 1 ; break;
case value 2 :
statement 2 ; break;
...
...
case value N :
statement N ; break;
default :
statements ; break;

38
Java Brilliant

The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the
expression.

Each case value must be a unique literal (constant, not a variable).


Duplicate case values are not allowed.

The value of the expression is compared with each ‘case’ values. If a match is
found, the corresponding statement or statements are executed.

If no match is found, statement or statements in the default case are executed.


Default statement is optional.

If default statement is absent, then if no matches are found, then the switch
statement completes without doing anything.

The break statement is used inside the switch to terminate a statement


sequence.

NOTE : We will study break statement in further chapter.

Ex.
import java.util.Scanner;
public class Calci
{
public static void main(String[] args)
{
int a,b,ch;
double ans;
Scanner s = new Scanner(System.in);
System.out.print("Enter a : ");
a=s.nextInt();
System.out.print("Enter b : ");
b=s.nextInt();
System.out.println("Enter 1 for addition");
System.out.println("Enter 2 for subtraction");
System.out.println("Enter 3 for multiplication");
System.out.println("Enter 4 for division");
System.out.print("Enter your choice : ");
ch=s.nextInt();
switch(ch)
{
case 1:
ans=a+b;
System.out.println("a + b = " + ans);
break;

case 2:
ans=a-b;
System.out.println("a - b = " + ans);
break;

case 3:
ans=a*b;
System.out.println("a * b = " + ans);
break;

case 4:
ans=a/b;
39
Java Brilliant

System.out.println("a / b = " + ans);


break;

default:
System.out.println("Enter correct choice");
}

}
}

Output :

Enter a : 5
Enter b : 6
Enter 1 for addition
Enter 2 for subtraction
Enter 3 for multiplication
Enter 4 for division
Enter your choice : 3
a * b = 30.0

Java’s repetition (iteration) statements are for, while, and do-while. These
statements create what we commonly call loops.

As you probably know, a loop repeatedly executes the same set of instructions
until a termination condition is met.

1. for :
 The for loop repeats a set of statements a certain number of times until a
condition is matched.
 It is commonly used for simple iteration. The for loop appears as shown
below.

Syntax :

for (initialization; condition; expression)


{
Set of statements;
}

 In the first part a variable is initialized to a value.


 The second part consists of a test condition that returns only a Boolean
value. The last part is an expression, evaluated every time the loop is
executed.
 The following example depicts the usage of the for loop.

class for1
{
public static void main(String args[])
{
int i;
for (i=0;i<10;i++)
{
System.out.println("\nExample of for loop ");
}
}
40
Java Brilliant

Output :
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop
Example of for loop

2. while :
 The while loop executes a set of code repeatedly until the condition
returns false.
 The syntax for the while loop is given below:

Syntax :

while (condition)
{
body(statements) of the loop
}

 Where <condition> is the condition to be tested. If the condition returns


true then the statements inside the <body of the loop> are executed.
 Else, the loop is not executed.

class while1
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println("\n" + i);
i++;
}
}
}

Output :
1
2
3
4
5
6
7
8
9
10

41
Java Brilliant

3. do while :
 The do while loop is similar to the while loop except that the condition to
be evaluated is given at the end.
 Hence the loop is executed at least once even when the condition is false.
 The syntax for the do while loop is as follows:

Syntax :

do
{
body of the loop
} while (condition);

In do while loop semicolon(;) is compulsory after while.

NOTE : for and while loops are entry control loop because here conditions are
checked at entry time of loop but do while loop is exit control loop because the
condition is checked at exit time.
class dowhile1
{
public static void main(String args[])
{
int i = 1;
int sum = 0;
do
{
sum = sum + i;
i++;
}while (i<=10);
System.out.println("\n\n\tThe sum of 1 to 10 is .. " + sum);
}
}

Output :
The sum of 1 to 10 is .. 55

Now we are going to learn something more about loop, especially about for loop.

=> ?We can declaring Loop Control Variables Inside the for Loop like below.
class ForTick
{
public static void main(String args[])
{
for(int n=10; n>0; n--) // here, n is declared
inside of the for loop
System.out.println("tick " + n);
}
}

Output :
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
42
Java Brilliant

tick 2
tick 1

NOTE : When you declare a variable inside a for loop, there is one important
point to remember: the scope of that variable ends when the for statement does.

=> We can use comma operator inside for loop to declare more than one variable
inside loop.
class Sample
{
public static void main(String args[])
{
int a, b;

for(a=1,b = 4;a < b;a++,b--)


{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

Output :

a = 1
b = 4
a = 2
b = 3

As you can see we declare two variables in for loop with the help of comma
operator and use those variables inside loop as we did in above program.

NOTE : The actual syntax of for loop is " for( ; ; ) ". It means we can use or
access every for loop which contain two semicolon (;) inside round braces of for
loop.

EX.

for( ; ; )
{
// ...
}

Nested loops :
Like all other programming languages, Java allows loops to be nested. That is,
one loop may be inside another.

It can help you to scan and print multi dimensional array as well as in so many
other application or program.

EX.
class Nested
{
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++)

43
Java Brilliant

{
for(j=i; j<10; j++)
{
System.out.print(".");
}
System.out.println();
}
}
}

Output :

..........
.........
........
.......
......
.....
....
...
..
.

Java supports three jump statements: break, continue, and return. These
statements transfer control to another part of your program.

1. break.
2. continue.
3. return.

1 The break statement


 This statement is used to jump out of a loop.
 Break statement was previously used in switch – case statements.
 On encountering a break statement within a loop, the execution continues
with the next statement outside the loop.
 The remaining statements which are after the break and within the loop
are skipped.
 Break statement can also be used with the label of a statement.
 A statement can be labeled as follows.

statementName : SomeJavaStatement

 When we use break statement along with label as

break statementName;

The execution continues with the statement having the label. This is equivalent
to a goto statement of c and c++..

An example of break statement

class break1
{
public static void main(String args[])

44
Java Brilliant

{
int i = 1;
while (i<=10)
{
System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
}
}
}

Output :
1
2
3
4
5

An example of break to a label


class break3
{
public static void main (String args[])
{
boolean t=true;
a:
{
b:
{
c:
{
System.out.println("Before the
break");
if(t)
break b;
System.out.println("This will not
execute");
}
System.out.println("This will not execute");
}
System.out.println("This is after b");
}
}
}

Output :
Before the break
This is after b

2 Continue statement
 This statement is used only within looping statements.
 When the continue statement is encountered, the next iteration starts.
 The remaining statements in the loop are skipped. The execution starts
from the top of loop again.

The program below shows the use of continue statement.

45
Java Brilliant

class continue1
{
public static void main(String args[])
{
for (int i=1; i<1=0; i++)
{
if (i%2 == 0)
continue;

System.out.println("\n" + i);
}
}
}

Output :
1
3
5
7
9

3 The return statement


 The last control statement is return. The return statement is used to
explicitly return from a method.
 That is, it causes program control to transfer back to the caller of the
method.
 the return statement immediately terminates the method in which it is
executed.

The program below shows the use of return statement.

class Return1
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}

Output :
Before the return.

NOTE : the if(t) statement is necessary. Without it, the Java compiler would flag
an “unreachable code” error, because the compiler would know that the last
println( ) statement would never be executed. To prevent this error, the if
statement is used here to trick the compiler for the sake of this demonstration.

46
Java Brilliant

Introduction to Class
What is class?

Class is a collection of data members and member functions.

Now what are data members?

Data members are nothing but simply variables that we declare inside the class
so it called data member of that particular class.

Now what are member functions?

Member functions are the function or you can say methods which we declare
inside the class so it called member function of that particular class.

47
Java Brilliant

The most important thing to understand about a class is that it defines a new
data type. Once defined, this new type can be used to create objects of that type.

Thus, a class is a template for an object, and an object is an instance of a class.


Because an object is an instance of a class, you will often see the two words
object and instance used interchangeably.

Syntax of class:

class classname
{
type instance-variable1;
type instance-variable2;
//....
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}

type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}

When you define a class, you declare its exact form and nature. You do this by
specifying the data that it contains and the code that operates on that data.

The data, or variables, defined within a class are called instance variables. The
code is contained within methods.

NOTE : C++ programmers will notice that the class declaration and the
implementation of the methods are stored in the same place and not defined
separately.

EX.

public class MyPoint


{
int x = 0;
int y = 0;

void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}

48
Java Brilliant

public static void main(String args[])


{
MyPoint obj; // declaration
obj = new MyPoint(); // allocation of memory to an object
obj.x=10; //access data member using object.
obj.y=20;
obj.displayPoint(); // calling a member method
}
}

Output :

Printing the coordinates


10 20

Here x and y are data members of class MyPoint and displayPoint() is a member
function of the same class.

In above program we can take as many objects as we want.

From the above program one thing we should keep in mind that when we want to
access data member or methods of class we have to write objectname.member
name

Syntax:

accessing data member of the class: objectname.datamember name;

accessing methods of the class: objectname.method name();

So for accessing data of the class: we have to use (.) dot operator.

NOTE: we can use or access data of any particular class without using (.) dot
operator from inside that particular class only.

How to declare object of class in java?

The program we gave in previous topic from that we can easily learn that how
object is going to declare and define for any class.

Syntax of object:

classname objectname; \\ declaration of object.

objectname = new classname(); \\ allocate memory to object (define object).

or we can directly define object like this

classname objectname = new classname();

Now let us look one class which has two different object.

class Box
{
double width;
double height;

49
Java Brilliant

double depth;
}
class BoxDemo2
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}

Output :

Volume is 3000.0
Volume is 162.0

From the above program we can understand that each object has its own copies
of the instance variables.

This means that if you have two Box objects, each has its own copy
of depth, width, and height. It is important to understand that changes to the
instance variables of one object have no effect on the instance variables of
another.

Assigning Object Reference Variables :

Suppose

Box b1 = new Box();


Box b2 = b1;

Here b1 is the object of class Box. And we assign b1 to b2 by b2=b1.

Here we did not use new keyword for b2 so b1 and b2 will both refer to the same
object.

The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object. It simply makes b2 refer to the same object as does b1.

Thus, any changes made to the object through b2 will affect the object to which
b1 is referring, since they are the same object.

50
Java Brilliant

NOTE: When you assign one object reference variable to another object reference
variable, you are not creating a copy of the object, you are only making a copy of
the reference.

Introduction to method

As we all know that, classes usually consist of two things instance variables and
methods.

Here we are going to explain some fundamentals about methods.

So we can begin to add methods to our classes.

Methods are defined as follows

§ Return type

§ Name of the method

§ A list of parameters

§ Body of the method.

Syntax:

return type method name (list of parameters)


{
Body of the method
}

return type specifies the type of data returned by the method. This can be any
valid data type including class types that you create.

If the method does not return a value, its return type must be void, Means you
can say that void means no return.

Methods that have a return type other than void return a value to the calling
routine using the following form of the return statement:

return value;

Here, value is the value returned.

The method name is any legal identifier.

The list of parameter is a sequence of type and identifier pairs separated by


commas. Parameters are essentially variables that receive the value of
the arguments passed to the method when it is called.

If the method has no parameters, then the parameter list will be empty.

Let us look at one example of class which have methods and data members both.

51
Java Brilliant

import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
void volume() // display volume of a box
{
System.out.print("Volume is : ");
System.out.println(width * height * depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(“Enter Box Width : ”);
box1.width = s.nextDouble();
System.out.print(“Enter Box Height : ”);
box1.height = s.nextDouble();
System.out.print(“Enter Box Depth : ”);
box1.depth = s.nextDouble();
// display volume of box1
box1.volume(); // calling the method volume
}
}

Output:

Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here width, height and depth are data members of class Box and void volume()
is method of class Box.

Here method has no parameter and no return value.

Now let us look at same program but in different way.

import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
52
Java Brilliant

{
double vol;
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(“Enter Box Width : ”);
box1.width = s.nextDouble();
System.out.print(“Enter Box Height : ”);
box1.height = s.nextDouble();
System.out.print(“Enter Box Depth : ”);
box1.depth = s.nextDouble();
// display volume of box1
vol = box1.volume(); // calling the method volume
System.out.println("Volume is : " +vol);
}
}

Output:

Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here in above program volume() method has return type double so we took one
vol variable. It is a local variable of class BoxDemo and it catch the returned
value by volume method of class Box.

One thing must keep in mind that the data type of vol and return type of
volume() method always be same.

import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
double volume(double w, double h, double d)
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
double vo,wth,ht,dth;
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(“Enter Box Width : ”);
wth = s.nextDouble();
System.out.print(“Enter Box Height : ”);
ht = s.nextDouble();
System.out.print(“Enter Box Depth : ”);
dth = s.nextDouble();
// display volume of box1
vol = box1.volume(wth,ht,dth); // calling the method volume
53
Java Brilliant

System.out.println("Volume is : " +vol);


}
}

Output:

Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here in above program volume() method has three parameters as well as double
return type.

Here we took three extra local variables in class BoxDemo and pass them in
function calling.

One thing must keep in mind that in defining and calling of method, the sequence
of data type of parameter must be same in both.

Constructor

Java supports a special type of methods, called constructor that enables an


object to initialize itself when it is created.

Constructors have the same name as the class it-self.

Constructors do not specify a return type, not even void. This is because they
return the instance of the class itself.

A constructor is automatically called when an object is created.

Syntax:

Constructor_name([arguments])

// body

Constructors are generally of two types.

1. Non-Parameterized

2. Parameterized

54
Java Brilliant

1. Non-Parameterized:

// Non - parameterised constructor


class Point1
{
int x;
int y;
Point1() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----
");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
Point1 p1 = new Point1(); // constructor will be call
automatically from here
p1.display();
}
}

Output:

-----Printing the coordinates-----


10 20

2. Parameterized:
// parameterised constructor
import java.util.Scanner;
class Point2
{
int x;
int y;
Point2(int a, int b)
{
x = a;
y = b;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----
");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
int i,k;
Scanner s = new Scanner(System.in);
System.out.print("Enter int value for i : ");
i = s.nextInt();

55
Java Brilliant

System.out.print("Enter int value for k : ");


k = s.nextInt();
Point2 p1 = new Point2(i,k);
p1.display();
}
}

Output:

Enter int value for i : 10


Enter int value for k : 20
-----Printing the coordinates-----
10 20

Keywords

We have already seen one keywords table in our first chapter.

But here we are going to learn few regularly used keywords.

1. new

2. this

3. static

4. super

5. final

The super and final keywords will demonstrate in further chapter.

new:
The new keyword dynamically allocates memory for an object.

Syntax:

claas_name object _name = new class_name();

EX.

Box b1 = new Box();


Box b2 = new Box();

We have already seen so many programs in which we used new keyword for
creating objects.

this:
This keyword is the name of a reference that refers to a calling object itself.

one common use of the this keyword is to reference a class` hidden data fields.

56
Java Brilliant

You can have local variables, including formal parameters to methods which
overlap with the names of the class` instance variables.

The local variable hides the instance variable so we use this keyword.

Another common use of this keyword is to enable a constructor to invoke another


constructor of the same class.

java requires that the this(arg-list) statement appear first in the constructor
before any other statements.

EX :

public class This_demo


{
public static void main(String[] args)
{
abc a1 = new abc(); //call non parameterize constructor

class abc
{
int x,y;
abc()
{
this(10,20); //this will call another constructor
}
abc(int x,int y)
{
this.x=x+5; //it will set class` member x
this.y=y+5; //it will set class` member y
System.out.println("local method`s x = " +x);
System.out.println("local method`s y = " +y);
Print_data();
}
public void Print_data()
{
System.out.println("x = " +x);
System.out.println("y = " +y);
}
}

Output :

local method`s x = 10
local method`s y = 20
x = 15
y = 25

static :
A class member must be accessed with the use of an object of its class but
sometimes we want to define a class member that will be used independently
without creating any object of that class.

57
Java Brilliant

It is possible in java to create a member that can be used by itself, without


reference to a specific instance.

To create such a member, precede its declaration with the keyword static.

When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object.

one can declare both methods and variables to be static.

The most common example of a static member is main().

main() is declared as static because it must be called before any object exist.

Instance variables declared as static are actually, global variables.

When objects of its class are declared, no copy of a static variable is made.

Instead, all instances of the class share the same static variable.

Method declared as static have several restrictions:

1. Can call only other static methods.

2. Only access static data.

3. Can not refer to this or super in any way.

One can also declare a static block which gets executed exactly once, when the
class is first loaded.

EX :

public class Static_Demo


{
public static void main(String[] args)
{
display(40); //call static method
}
static int i = 5;
static int j;
int k = 10;
static void display(int a)
{
System.out.println("a = "+a); // here a = 40
System.out.println("i = "+i); // here i = 5
System.out.println("j = "+j); // here j = 50( because of static
block j = i * 10 = 5 * 10 =50 )
//System.out.println("k = "+k); //can,t make a static reference to
the non-static field k
}
static
{
System.out.println("Static block initialized..........");
j = i * 10;
}
}

58
Java Brilliant

Output :

Static block initialized..........


a = 40
i=5
j = 50

Access Control
One can control what parts of a program can access the member of a class. By
controlling access, one can prevent misuse.

For Example, allowing access to data only through a well-defined set of methods,
one can prevent misuse of that data. Thus,

when correctly implemented, a class creates “black box”.

How a member can be accessed is determined by the access specifier that


modifies its declaration.

Java provides a set to access specifiers. Some aspects of access control are
related to inheritance or packages.

Java’s access specifiers are:

public:

o When a member of a class is specified by the public specifier, then


that member can be accessed by any other code.

o The public modifier makes a method or variable completely available


to all classes.

o Also when the class is defined as public, it can be accessed by any


other class.

private:

o To hide a method or variable from other classes, private modifier is


used.

o A private variable can be used by methods in it’s own class but not
by objects of any other class.

o Neither private variables nor private methods are inherited by


subclass.

o The only place these variables and methods can be seen is from
within their own class.

protected:

59
Java Brilliant

o protected applies only when inheritance is involved.

o If you want to allow an element to be seen outside your current


package, but only to classes that are inherited from your class directly,
then declare that element as protected.

default:

o We have seen that when no access control modifier is specified, it is


called as default access.

o Classes written like this are not accessible in other package.

o Any variable declared without a modifier can be read or changed by


any other class in the same package.

o Any method declared the same way can be called by any other class
in the same package.

o When a member does not have an explicit access specification,

o it is visible to subclasses as well as to other classes in the same


package.

The following table summarizes the levels of access control.

Access Public Protected Default Private


From the same
Yes Yes Yes Yes
class
From any class
in the same Yes Yes Yes No
package
From any class
outside the Yes No No No
package
From a sub -
class in the Yes Yes Yes No
same package
From a sub -
class outside the Yes Yes Yes No
same package

Classes and Methods

Method overloading in java:


Method overloading:
60
Java Brilliant

A class can contain any number of methods. Methods can be with parameter and
without parameter.

The parameter in a method are called type signature.

It is possible in java to define two or more methods within the same class that
share the same name, but with different parameter declarations (type
signatures).

When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.

Overloading methods demonstrate the concept of polymorphism.

When an overloaded method is invoked, java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
call.

Thus, overloaded methods must differ in the type and/or number of their
parameters.

Overloaded methods may have different return types.

When java encounters a call to an overloaded method, it simply executes the


version of the method whose parameters match the arguments used in the call.

EX :

public class MethodOver


{
int n1;
int n2;
MethodOver()
{
n1 = 10;
n2 = 20;
}
void square()
{
System.out.println("The Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("The Square is " + n1 * n2);
}
void square(int p1, int p2)
{
n1 = p1;
n2 = p2;
System.out.println("The Square is " + n1 * n2);
}
public static void main(String args[])
{
MethodOver obj1 = new MethodOver();
obj1.square(); //call non parameterise method
obj1.square(4); //call method which has 1 argument
obj1.square(7,8); //call method which has 2 argument
61
Java Brilliant

}
}

Output :

The Square is 200


The Square is 80
The Square is 56

You can see that here we have 3 square methods with different argument.

Its called method overloading.

Constructor overloading in java:


Along with method overloading, we can also overload constructors. Constructors
having the same name with different parameter list is called constructor
overloading.

EX :

?
class Point
{
int x;
int y;
Point(int a, int b)
{
x = a;
y = b;
}

class Circle
{
int originX;
int originY;
int radius;

//Default Constructor

Circle()
{
originX = 5;
originY = 5;
radius = 3;

// Constructor initializing the coordinates of origin and the radius.

Circle(int x1, int y1, int r)

62
Java Brilliant

{
originX = x1;
originY = y1;
radius = r;

Circle(Point p, int r)
{
originX = p.x;
originY = p.y;
radius = r;
}

void display()
{
System.out.println("--Center at " + originX + " and " + originY);
System.out.println("Radius = " + radius);
}

public static void main(String args[])


{

Circle c1 = new Circle();


Circle c2 = new Circle(10,20,5);
Circle c3 = new Circle(new Point(15,25),10);

c1.display();
c2.display();
c3.display();
}
}

Output :

--Center at 5 and 5
Radius = 3
--Center at 10 and 20
Radius = 5
--Center at 15 and 25
Radius = 10

Above program is quite complicated here i am giving you perfect flow of


program.

First of all note one thing that new ClassName() this is a short syntax of creating
object of any class.

And we all know that when we create object the constructor of that class will be
called automatically.

So in our program first of all due to syntax Circle c1 = new Circle(); non
parameterize constructor will be called for object c1 so we get output like Center
at 5 and 5 Radius = 3 in c1.display().

63
Java Brilliant

Next due to syntax Circle c2 = new Circle(10,20,5); constructor which has 3


arguments will be called for object c2 so we get output like Center at 10 and 20
Radius = 5 in c2.display().

Now when we define object c3 our syntax is like Circle c3 = new Circle(new
Point(15,25),10); so first of all it will create object for Point class so constructor
of point class will be called and it will set parameter x and y.

Then constructor of circle class which has Point class object as an argument
along with one int argument will be called and set all parameter as per program
and we get output like Center at 15 and 25 Radius = 10 in c3.display().

We can also write

Point p1 = new Point(15,25);


Circle c3 = new Circle(p1,10);

This is how we can pass object as an argument in constructor.

We have already seen Call by reference in which we pass object as a method


argument.

Now in next topic we will discuss about how you can return an object.

More about method


1. Passing Objects as a Parameter to Method.

We have seen that methods can take parameters as input and process them.

It is also common to pass objects as a parameter to methods.

class PassObj
{
int n1;
int n2;
// constructor
PassObj()
{
n1 = 0;
n2 = 0;
}

PassObj(int p1, int p2)


{
n1 = p1;
n2 = p2;
}

void multiply(PassObj p1)


{
int temp;
temp = p1.n1 * p1.n2;
System.out.println("Multiplication is " + temp);
}
public static void main(String args[])
{
PassObj obj1 = new PassObj(5,6);

64
Java Brilliant

PassObj obj2 = new PassObj();


obj2.multiply(obj1);
}
}

Output :

Multiplication is 30

2. Constructor overloading with object as a parameter.


class MetObjOv
{
int n1;
int n2;

// constructor
MetObjOv()
{
n1 = 0;
n2 = 0;
}
MetObjOv(int x, int y)
{
n1 = x;
n2 = y;
}
void multiply(MetObjOv p1)
{
n1 = p1.n1;
n2 = p1.n2;
System.out.println("There is nothing to multiply ");
System.out.println("n1 = "+n1+"\tn2 = " +n2);
}
void multiply(MetObjOv p1, MetObjOv p2)
{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;

System.out.println("Multiplication of two objects ");


System.out.println("n1 = " + n1 + "\tn2 = " + n2 );
}

public static void main(String args[])


{
MetObjOv obj1 = new MetObjOv(5,6);
MetObjOv obj2 = new MetObjOv(6,5);
MetObjOv obj3 = new MetObjOv();
obj3.multiply(obj1);
obj3.multiply(obj1, obj2);
}
}

Output :

There is nothing to multiply


n1 = 5 n2 = 6
Multiplication of two objects
n1 = 30 n2 = 30

65
Java Brilliant

3. Return an Object.

A method can return any type of data, including class type (object) that you
create.
class RetObj
{
int n1;
int n2;

// constructor
RetObj()
{
n1 = 0;
n2 = 0;
}
RetObj(int x, int y)
{
n1 = x;
n2 = y;
}
RetObj multiply(RetObj p1, RetObj p2)
{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;
return (this);
}

void display()
{
System.out.println("An Example of returning an Object ");
System.out.println("n1 = "+n1+"\tn2 = " +n2);
}

public static void main(String args[])


{
RetObj obj1 = new RetObj(5,6);
RetObj obj2 = new RetObj(6,5);
RetObj obj3 = new RetObj();
obj3 = obj3.multiply(obj1, obj2);
obj3.display();
}
}

Output :

An Example of returning an Object


n1 = 30 n2 = 30

RetObj multiply(RetObj p1, RetObj p2) This is the syntax in our program which
has return type object.

obj3 = obj3.multiply(obj1, obj2); this is the syntax which calls method multiply
and return object, it will store in obj3.

Call by value
Now we all know that how to define and call the methods.

66
Java Brilliant

There are two types of calling method and those are

1. call by value

2. call by reference

Here we illustrate call by value and in next topic we will look at call by
reference.

In call by value when we call any method we pass value as method parameter so
changing in local variables of the method doesn't`t affect the original variables
of class.

This method copies the value of an argument into the formal parameter of the
subroutine.

Therefore, changes made to the parameter of the subroutine have no effect on


the argument.

In java, when we pass a primitive type to a method, it is passed by value.

Thus, what occurs to the parameter that receives the argument has no effect
outside the method.

EX :

?
public class CallBy_Value
{
public static void main(String[] args)
{
Value v = new Value(10,20);
System.out.println("a and b before call............");
System.out.println("a = "+v.a);
System.out.println("b = "+v.b);
v.call(v.a,v.b); // CALL BY VALUE
System.out.println("a and b after call............");
System.out.println("a = "+v.a);
System.out.println("b = "+v.b);
}
}

class Value
{
int a,b;
Value(int i,int j)
{
a = i ;
b = j;
}
void call(int a, int b)
{
a = a * 2;
b = b * 2;
}
}

67
Java Brilliant

Output :

a and b before call............


a = 10
b = 20
a and b after call............
a = 10
b = 20

You can see that after calling method we change value of a and b but it will not
afect the original value of class` members because of call by value.

We pass value v.a and v.b as parameter and it will change local method`s a and
b variables.

Call by reference
Call by reference :

Here we pass reference as parameter in function calling.

We all know that reference means object so we pass object as parameter.

A reference to an argument (not value of argument) is passed to the parameter.

Inside the subroutine, this reference is used to access the actual argument
specified in the call.

This means that changes made to the parameters will affect the argument used
to call the subroutine.

When we pass an object to a method, the situation changes, because objects are
passed by call-by-reference.

When we create a variable of a class type, we are only creating a reference to an


object. Thus,

When you pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument.

This effectively means that objects are passed to method do affect the object
used as an argument.

EX :

?
public class CallBy_Reference
{
public static void main(String[] args)
{
Reference r = new Reference(10,20);
System.out.println("a and b before call............");
System.out.println("a = "+r.a);
System.out.println("b = "+r.b);
r.call(r); // CALL BY REFERENCE
68
Java Brilliant

System.out.println("a and b after call.............");


System.out.println("a = "+r.a);
System.out.println("b = "+r.b);
}
}

class Reference
{
int a,b;
Reference(int i,int j)
{
a = i ;
b = j;
}
void call(Reference r)
{
r.a = a * 2;
r.b = b * 2;
}

Output :

a and b before call............


a = 10
b = 20
a and b after call.............
a = 20
b = 40

You can see that after calling method value of original a and b is changed
because of call by reference.

Here we pass "r" reference (Object) as parameter in method calling. So changes


inside method will affect original variable of class.

Recursion

Recursion is the process of defining something in terms of itself.

When function call it self is called recursion.

A method that calls itself is said to be recursive.

EX :

import java.util.Scanner;

class Factorial

69
Java Brilliant

{
// this is a recursive function
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n; //From here function call it self
(fact(n-1))
return result;
}
}

public class Recursion


{
public static void main(String args[])
{
int x;
Scanner s = new Scanner(System.in);
System.out.print("Enter int no = ");
x = s.nextInt();
Factorial f = new Factorial();
System.out.println("Factorial of" + x + " is " + f.fact(x));
}
}

Output :

Enter int no = 7
Factorial of7 is 5040

Here the method fact is recursive because it calls itself.

The whole precess something like this


result = fact(7-1) * 7 and so on until it returns 1.

So one thing is sure that we have to take care that in every recursive process
there must be a terminate condition to come out from recursion.

nested class

nested class :

It is possible to define a class within another class; such classes are known as
nested classes.

The scope of a nested class is bounded by the scope of its enclosing class.

That means, if class B is defined within class A, then B is known to A, but


not outside A.

If A is nesting class B, then A has access to all the members of B, including


private members. But the B does not have access to the members of
nested class.

70
Java Brilliant

There are two types of nested classes:

1. Static

2. Non – Static

Static nested class

A static nested class is one which has the static modifier, as it is static it
must access the member of its enclosing class through an object.

That means it cannot refer to member of its enclosing class directly.

Non – Static nested class

Non – Static nested class is known as inner class.

It has access to all of its variables and methods of its outer class and can
refer to them directly.

An inner class is fully within the scope of its enclosing class.

EX :

class Inner1
{
class Contents
{
private int i = 16;
public int value()
{
return i;
}
}

class Destination
{
private String label;
Destination(String whereTo)
{
label = whereTo;
}
}
public void ship(String dest)
{
Contents c = new Contents(); // create object of inner
class Contents
Destination d = new Destination(dest); // create object of
inner class Destination

System.out.println("Shipped " + c.value() + " item(s) to " +


dest);
}

public static void main(String args[])


{
Inner1 p = new Inner1();
p.ship("Congo"); //call ship method of outer class "inner1"
}
71
Java Brilliant

Output :

Shipped 16 item(s) to Congo

Let us see one more example but here the program will not compile
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}

// this is an inner class

class Inner
{
int y = 10; // y is local to Inner
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
void showy()
{
System.out.println(y); // error, y not known here!
}
}

class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}

Here, y is declared as an instance variable of Inner. Thus it is not known outside


of
that class and it cannot be used by showy( ).

Command Line Argument

Command Line Argument :

Sometimes you will want to pass information into a program when you run it.
This is accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program’s


name on the command line when it is executed.

72
Java Brilliant

To access the command-line arguments inside a Java program is quite easy—they


are stored as strings in the String array passed to main( ).
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i < args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}

Try executing this program, as shown here:

java CommandLine this is a test 100 -1

When you do, you will see the following output:

args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

But first of all you should have the basic knowledge about command line and
how any java program run through command prompt.

Inheritance in java:
What is a Inheritance ?

The derivation of one class from another class is called Inheritance.

Type of inheritance :

A class that is inherited is called a superclass.

The class that does the inheriting is called as subclass.

In above figure all class A is superclass.

A subclass inherits all instance variables and methods from its superclass and
also has its own variables and methods.

One can inherit the class using keyword extends.

Syntax :

Class subclass-name extends superclass-name

// body of class.

73
Java Brilliant

In java, a class has only one super class.

Java does not support Multiple Inheritance.

One can create a hierarchy of inheritance in which a subclass becomes a


superclass of another subclass.

However, no class can be a superclass of itself.

EX :

class A //superclass
{
int num1; //member of superclass
int num2; //member of superclass
void setVal(int no1, int no2) //method of superclass
{
num1 = no1;
num2 = no2;
}
}

class B extends A //subclass B


{
int multi; //member of subclass
void mul() //method of subclass
{
multi = num1*num2; //accessing member of superclass from
subclass
}
}

class inhe2
{
public static void main(String args[])
{
B subob = new B();
subob.setVal(5,6); //calling superclass method throgh
subclass object
subob.mul();
System.out.println("Multiplication is " + subob.multi);
}
}

Output :

Multiplication is 30

Note : Private members of superclass is not accessible in subclass,


superclass is also called parentclass or baseclass,
subclass is also called childclass or derivedclass.

super - final - keywords in java:


74
Java Brilliant

Let us see now two most important keywords of java

1. super :

super keyword is used to call a superclass constructor and to call or access super
class members(instance variables or methods).

syntax of super :

=> super(arg-list)

When a subclass calls super() it is calling the constructor of its immediate


superclass.

super() must always be the first statement executed inside a subclass


constructor.

=> super.member

Here member can be either method or an instance variables.

This second form of super is most applicable to situation in which member names
of a subclass hide member of superclass due to same name.

EX :

class A1
{
public int i;
A1()
{
i=5;
}
}

class B1 extends A1
{
int i;
B1(int a,int b)
{
super(); //calling super class constructor
//now we will change value of superclass variable i
super.i=a; //accessing superclass member from subclass
i=b;
}
void show()
{
System.out.println("i in superclass = " + super.i );
System.out.println("i in subclass = " + i );
}
}

public class Usesuper


{
public static void main(String[] args)
{
B1 b = new B1(10,12);
b.show();

75
Java Brilliant

}
}

Output :

i in superclass = 10
i in subclass = 12

The instance variable i in B1 hides the i in A, super allows access to the i defined
in the superclass.

super can also be used to call methods that are hidden by a subclass.

2. final :

final keyword can be use with variables, methods and class.

=> final variables.

When we want to declare constant variable in java we use final keyword.

Syntax : final variable name = value;

=> final method

Syntax final methodname(arg)

When we put final keyword before method than it becomes final method.

To prevent overriding of method final keyword is used, means final method cant
be override.

=> final class

A class that can not be sub classed is called a final class.

This is archived in java using the keyword final as follow.

Syntax : final class class_name { ... }

Any attempt to inherit this class will cause an error and compiler will not allow it.

EX:

final class aa
{
final int a=10;
public final void ainc()
{
a++; // The final field aa.a cannot be assigned
}

class bb extends aa // The type bb cannot subclass the final class aa

76
Java Brilliant

{
public void ainc() //Cannot override the final method from aa
{
System.out.println("a = " + a);
}
}

public class Final_Demo


{
public static void main(String[] args)
{
bb b1 = new bb();
b1.ainc();
}
}

Here no output will be there because all the comments in above program are
errors. Remove final keyword from class than you will get error like final method
can not be override.

Method overriding :

Defining a method in the subclass that has the same name, same arguments and
same return type as a method in the superclass and it hides the super class
method is called method overriding.

Now when the method is called, the method defined in the subclass is invoked
and executed instead of the one in the superclass.

class Xsuper
int y;
Xsuper(int y)
{
this.y=y;
}
void display()
{
System.out.println("super y = " +y);
}
}

class Xsub Xsuper


{
int y;
Xsuper extends Xsuper
{
int z;
Xsub(int z , int y)
{
super(y);
this.z=z;
}
void display()
{
System.out.println("super y = " +y);
System.out.println("sub z = " +z);
77
Java Brilliant

public class TestOverride


{
public static void main(String[] args)
{
Xsub s1 = new Xsub(100,200);
s1.display();
}
}

Output :

super y = 200
sub z = 100

Here the method display() defined in the subclass is invoked.

Overloading VS Overriding :

Methodoverloading is comiple time polymorphism.

Method overriding is run time polymorphism.

Overloading a method is a way to provide more than one method in one class
which have same name but different argument to distinguish them.

Defining a method in the subclass that has the same name, same arguments and
same return type as a method in the superclass is called method overriding.

Multilevel Inheritance in java:


Multilevel Hierarchy :

class student
{
int rollno;
String name;

student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}

class marks extends student


{
int total;

78
Java Brilliant

marks(int r, String n, int t)


{
super(r,n); //call super class (student) constructor
total = t;
}
void dispdatam()
{
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}

class percentage extends marks


{
int per;

percentage(int r, String n, int t, int p)


{
super(r,n,t); //call super class(marks) constructor
per = p;
}
void dispdatap()
{
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe
{
public static void main(String args[])
{
percentage stu = new percentage(1912, "SAM", 350, 50); //call
constructor percentage
stu.dispdatap(); // call dispdatap of percentage class
}
}

Output :

Rollno = 1912
Name = SAM
Total = 350
Percentage = 50

It is common that a class is derived from another derived class.

The class student serves as a base class for the derived class marks, which in
turn serves as a base class for the derived class percentage.

The class marks is known as intermediated base class since it provides a link for
the inheritance between student and percentage.

The chain is known as inheritance path.

When this type of situation occurs, each subclass inherits all of the features
found in all of its super classes. In this case, percentage inherits all aspects of
marks and student.

To understand the flow of program read all comments of program.

79
Java Brilliant

When a class hierarchy is created, in what order are the constructors for the
classes that
make up the hierarchy called?

EX :
class X
{
X()
{
System.out.println("Inside X's constructor.");
}
}

class Y extends X // Create a subclass by extending class A.


{
Y()
{
System.out.println("Inside Y's constructor.");
}
}

class Z extends Y // Create another subclass by extending B.


{
Z()
{
System.out.println("Inside Z's constructor.");
}
}

public class CallingCons


{
public static void main(String args[])
{
Z z = new Z();
}
}

Output:

Inside X's constructor.


Inside Y's constructor.
Inside Z's constructor.

The answer is that in a class hierarchy, constructors are called in order of


derivation, from superclass to subclass.

Further, since super( ) must be the first statement executed in a subclass’


constructor, this order is the same whether or not super( ) is used.

If super( ) is not used, then the default or parameterless constructor of each


superclass will be executed.

As you can see from the output the constructors are called in order of derivation.

If you think about it, it makes sense that constructors are executed in order
of derivation.

80
Java Brilliant

Because a superclass has no knowledge of any subclass, any initialization


it needs to perform is separate from and possibly prerequisite to any
initialization performed by the subclass. Therefore, it must be executed first.

Dynamic Method Dispatch:

Dynamic method dispatch is the mechanism by which a call to an overridden


method is resolved at run time, rather than compile time.

Dynamic method dispatch is important because this is how Java implements run-
time polymorphism.

method to execution based upon the type of the object being referred to at the
time the call occurs. Thus, this determination is made at run time.

In other words, it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will
be executed.

EX :

class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}

class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}

class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}

public class Dynamic_disp


{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object

81
Java Brilliant

r.callme(); // calls B's version of callme

r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}

Output :

Inside A's callme method


Inside B's callme method
Inside C's callme method

Here reference of type A, called r, is declared.

The program then assigns a reference to each type of object to r and uses that
reference to invoke callme( ).

As the output shows, the version of callme( ) executed is determined by the type
of object being referred to at the time of the call.

Abstract Classes :

When the keyword abstract appears in a class definition, it means that zero or
more of it’s methods are abstract.

An abstract method has no body.

Some of the subclass has to override it and provide the implementation.

Objects cannot be created out of abstract class.

Abstract classes basically provide a guideline for the properties and methods
of an object.

In order to use abstract classes, they have to be subclassed.

There are situations in which you want to define a superclass that declares
the structure of a given abstraction without providing a complete
implementation of every method.

That is, sometimes you want to create a superclass that only defines
generalized form that will be shared by all of its subclasses, leaving it to each
subclass to fill in the details.

One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.

Syntax :

abstract type name(parameter-list);

As you can see, no method body is present.

82
Java Brilliant

Any class that contains one or more abstract methods must also be declared
abstract.

To declare a class abstract, you simply use the abstract keyword in front of
the class keyword at the beginning of the class declaration.

There can be no objects of an abstract class.

That is, an abstract class cannot be directly instantiated with the new
operator.

Any subclass of an abstract class must either implement all of the abstract
methods of the superclass, or be itself declared abstract.

EX :

abstract class A1
{
abstract void displayb1();
void displaya1()
{
System.out.println("This is a concrete method");
}

class B1 extends A1
{
void displayb1()
{
System.out.println("B1's implementation");
}
}

public class Abstract_Demo


{
public static void main(String args[])
{
B1 b = new B1();
b.displayb1();
b.displaya1();
}
}

Output :

B1's implementation
This is a concrete method

EX 2 :

abstract class shape


{
double dim1;
83
Java Brilliant

double dim2;
shape(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}

class rectangle extends shape


{
rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of rectangle.");
return dim1*dim2;
}
}

class triangle extends shape


{
triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of triangle.");
return dim1*dim2/2;
}
}

public class Abstract_D2


{
public static void main(String args[])
{
rectangle r = new rectangle(10,20);
triangle t = new triangle(10,6);

System.out.println(r.area());
System.out.println(t.area());
}
}

Output:

Area of rectangle.
200.0
Area of triangle.
30.0

The Object class :

There is one special class, Object, defined by Java. All other classes are
subclasses of Object.
84
Java Brilliant

That is, Object is a superclass of all other classes.

This means that a reference variable of type Object can refer to an object of any
other class.

Every class in java is descended from the java.lang.Object class.

If no inheritance is specified when a class is defined, the super class of the class
is Object by default.

EX :

public class circle { ... }

is equivalent to

public class circle extends Object { ... }

Methods of Object class

METHOD PURPOSE
Creates a new object that is the same as the
Object clone()
object being cloned.
Determines whether one object is equal to
boolean equals(Object obj_name)
another

Void finalize() Called before an unused object is recycled

Class getClass( ) Obtains the class of an object at run time.


Returns the hash code associated with the
int hashCode( )
invoking object.
Resumes execution of a thread waiting on
void notify( )
the invoking object.
Resumes execution of all threads waiting on
void notifyAll( )
the invoking object.
String toString( ) Returns a string that describes the object.
void wait( )

void wait(long milliseconds)


Waits on another thread of execution.
void wait(long milliseconds, int
nanoseconds)

The methods getclass(), notify(), notifyall() and wait() are declared as final.

You may override the others.

tostring()

?public String tostring()

85
Java Brilliant

it returns a String that describe an object.

?It consisting class name, an at (@) sign and object memory address in
hexadecimal.

EX :

Circle c1 = new Circle();

System.out.println(c1.tostring());

It will give O/P like Circle@15037e5

We can also write System.out.println(c1);

Polymorphism :

An object of a sub class can be used whenever its super class object is required.

This is commonly known as polymorphism.

In simple terms polymorphism means that a variable of super type can refer to a
sub type object.

86
Java Brilliant

We already discussed all three topics mentioned above.

Java Interface:
Interfaces are similar to abstract classes, but differ in their functionality.

In interfaces, none of the methods are implemented means interfaces defines


methods without body.

Interfaces are syntactically similar to classes, but they lack instance


variables, and their methods are declared without any body.

But, it can contain final variables, which must be initialized with values.

Once it is defined, any number of classes can implement an interface.

One class can implement any number of interfaces.

If we are implementing an interface in a class we must implement all the


methods defined in the interface as well as a class can also implement its own
methods.

87
Java Brilliant

Interfaces add most of the functionality that is required for many applications
which would normally resort to using multiple inheritance in C++.

Defining interfaces in java with


syntax:
Syntax :

[Access-specifier] interface interface-name

Access-specifier return-type method-name(parameter-list);

final type var1=value;

Where, Access-specifier is either public or it is not given.

When no access specifier is used, it results into default access specifier and if
interface has default access specifier then it is only available to other
members of the same package.

When it is declared as public, the interface can be used by any other code of
other package.

Interface-Name: name of an interface, it can be any valid identifier.

The methods which are declared having no bodies they end with a semicolon
after the parameter list. Actually they are abstract methods;

Any class that includes an interface must implement all of the methods.
Variables can be declared inside interface declarations.

They are implicitly final and static, means they can not be changed by
implementing it in a class.

They must also be initialized with a constant value.

EX :

interface Item

static final int code = 100;

static final String name = "Fan";

88
Java Brilliant

void display ( );

interface Area

static final float pi = 3.14F;

float compute ( float x, float y );

void show ( );

Implementing interfaces

Once an interface has been defined, one or more classes can implement that
interface.

To implement an interface, include the implements clause in a class definition,


and then create the methods declared by the interface.

The general form of a class that includes the implements clause looks like
this:

Access-specifier class classname [extends superclass] [implements interface,


[, interface..]]

// class body

If a class implements from more than one interface, names are separated by
comma.

If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.

The methods that implement an interface must be declared as public.

The type-signature of implementing method must match exactly the type


signature specified in the interface.

89
Java Brilliant

interface religion
{
String city = new String("Amritsar");

void greet();
void pray();
}

class gs implements religion


{
public void greet()
{
System.out.println("We greet - ABCD");
}
public void pray()
{
System.out.println("We pray at " + city + " XYZ ");
}
}

class iface1
{
public static void main(String args[])
{
gs sikh = new gs();
sikh.greet();
sikh.pray();
}
}

Output :

We greet - ABCD
We pray at Amritsar XYZ

EX 2 :
interface i1
{
void dispi1();
}

interface i2
{
void dispi2();
}

class c1 implements i1
{
public void dispi1()
{
System.out.println("This is display of i1");
}
}

class c2 implements i2
{
public void dispi2()
{

90
Java Brilliant

System.out.println("This is display of i2");


}
}

class c3 implements i1, i2


{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}

class iface2
{
public static void main(String args[])
{
c1 c1obj = new c1();
c2 c2obj = new c2();
c3 c3obj = new c3();

c1obj.dispi1();
c2obj.dispi2();
c3obj.dispi1();
c3obj.dispi2();

}
}

Output :

This is display of i1
This is display of i2
This is display of i1
This is display of i2

EX 3 : // Implementing interface having common function name


?
interface i1
{
void disp();
}

interface i2
{
void disp();
}

class c implements i1, i2


{
public void disp()
{
System.out.println("This is display .. ");
}
}

91
Java Brilliant

class iface7
{
public static void main(String args[])
{
c cobj = new c();

cobj.disp();
}
}

Output :

This is display ..

Note : When implementing an interface method, it must be declared as public. It


is possible for classes that implement interfaces to define additional members of
their own.

Partial Implementation of Interface :

If we want to implement an interface in a class we have to implement all the


methods defined in the interface.

But if a class implements an interface but does not fully implement the
method defined by that interface, then that class must be declared as
abstract.

EX :

interface i1
{
void disp1();
void disp2();
}

abstract class c1 implements i1


{
public void disp1()
{
System.out.println("This is display of 1");
}
}

class c2 extends c1
{
public void disp2()
{
System.out.println("This is display of 2");
}
}

class iface
{
public static void main(String args[])
{
c2 c2obj = new c2();
c2obj.disp1();

92
Java Brilliant

c2obj.disp2();
}
}

Output :

This is display of 1
This is display of 2

interface variables

One can declare variable as object references that uses an interface rather than a
class type.

When you call a method through one of these references, the correct version will
be called based on the actual instance of the interface being referred to.

interface AreaCal
{
final double pi = 3.14;
double areacalculation(double r);
}

class Circle implements AreaCal


{
public double areacalculation(double r)
{
double ar;
ar = pi*r*r;
return ar;
}
}

class iface3
{
public static void main(String args[])
{
double area;
AreaCal ac = new Circle();
area = ac.areacalculation(10.25);
System.out.println("Area of Circle is : " + area);
}
}

Output :

Area of Circle is : 329.89625

Here variable ac is declared to be of the interface type AreaCal,

it was assigned an instance of circle. Although ac can be used to access the


areacalculation() method,

93
Java Brilliant

it cannot access any other members of the client class. An interface reference
variable only has knowledge of the method declared by its interface declaration.

Extending interfaces :

One interface can inherit another by use of the keyword extends. The syntax is
the same as for inheriting classes.

When a class implements an interface that inherits another interface,

It must provide implementation of all methods defined within the interface


inheritance.

Note : Any class that implements an interface must implement all methods
defined by that interface, including any that inherited from other interfaces.

EX :

interface if1
{
void dispi1();
}
interface if2 extends if1
{
void dispi2();
}
class cls1 implements if2
{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}
public class Ext_iface
{
public static void main(String args[])
{
cls1 c1obj = new cls1();

c1obj.dispi1();
c1obj.dispi2();
}

Output :

This is display of i1
This is display of i2

Note : We have to define disp1() and disp2() in cls1.


94
Java Brilliant

Multiple inheritance using interface..

class stu
{
int rollno;
String name = new String();
int marks;
stu(int r, String n, int m)
{
rollno = r;
name = n;
marks = m;
}
}

interface i
{
void display();
}

class studerived extends stu implements i


{
studerived(int r, String n, int m)
{
super(r,n,m);
}
public void display()
{
System.out.println("Displaying student details .. ");
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
System.out.println("Marks = " + marks);
}
}

public class Multi_inhe_demo


{
public static void main(String args[])
{
studerived obj = new studerived(1912, "Ram", 75);
obj.display();
}

Output :

Displaying student details ..


Rollno = 1912
Name = Ram
Marks = 75

We can make various forms of interface implementation as below

95
Java Brilliant

Java inbuilt packages:


Package : Packages are java`s way of grouping a veriety of classes and/or
interfaces together.

Java API packages : java API provides a large number of classes grouped into
different packages according to functionality.

Frequently used API packages are as under.

Syntax for import packages is as under

import packagename.classname;

or

import packagename.*;

These are known as import statements and must appear at the top of the file,
before any file declaration as you can see in our few examples.

Here import is a keyword.

The first statement allows the specified class in the specified package to be
imported.

EX :

import java.awt.Color;

double y = java.lang.Math.sqrt(x);

Here lang is a package, Math is a class and sqrt is a method.

For create new package you can write...

96
Java Brilliant

package firstPackage;

public class Firstclass

..................

body of class

.................

Vector class :

 The Vector class is one of the most important in all of the Java class
libraries. We cannot expand the size of a static array.
 We may think of a vector as a dynamic array that automatically expands as
more elements are added to it.
 All vectors are created with some initial capacity.
 When space is needed to accommodate more elements, the capacity is
automatically increased.
 That is why vectors are commonly used in java programming.

This class provides the following constructors:

Vector()

Vector(int n)

Vector(int n, int delta)

 The first form creates a vector with an initial capacity of ten elements.
 The second form creates a vector with an initial capacity of n elements.
 The third form creates a vector with an initial capacity of n elements that
increases by delta elements each time it needs to expand.

EX :

import java.util.*;
public class Vector_Demo
{
public static void main(String args[])
{
int i;
Vector v = new Vector();
v.addElement(new Integer(10));
v.addElement(new Float(5.5f));
v.addElement(new String("Hi"));
v.addElement(new Long(2500));
v.addElement(new Double(23.25));
System.out.println(v);
String s = new String("Brilliant");
v.insertElementAt(s,1);
System.out.println(v);
v.removeElementAt(2);

97
Java Brilliant

System.out.println(v);
for(i=0;i<5;i++)
{
System.out.println(v.elementAt(i));
}
}
}

Output :

10 .
Brilliant
Hi
2500
23.25

Random class :

 The Random class allows you to generate random double, float, int, or long
numbers.
 This can be very helpful if you are building a simulation of a real-world
system.
 This class provides the following constructors.

Random()

Random(long start)

Here, start is a value to initialize the random number generator.

Method Description
Double nextDouble() Returns a random double value.
Float nextFloat() Returns a random float value.
Returns a random double value.
Numbers obtained from repeated calls to
Double nextGaussian() this method have a Gaussian distribution
with a mean of 0 and a standard
deviation of 1.
Int nextInt() Returns a random int value.
Long nextLong() Returns a random long value.

EX :

import java.util.*;
public class Random_Demo
{
public static void main(String args[])
{
Random ran = new Random();
for(int i = 0; i<5;i++)
{
System.out.println(ran.nextInt());
}
98
Java Brilliant

}
}

Output:

64256704
1265771787
-1962940029
1372052

Date class :

The Date classes encapsulate information about a specific date and time.

It provides the following constructors.

Date()

Date(long msec)

 Here, the first form returns an object that represent the current date and
time.
 The second form returns an object that represents the date and time msec
in milliseconds after the time.

The time is defined as midnight on January 1,1970 GMT (Greenwich Mean Time).

Method Description
Returns true if d is after the current date.
Boolean after(Date d)
Otherwise, returns false.
Returns true if d is before the current
Boolean before(Date d)
date. Otherwise, returns false.
Returns true if d has the same value as the
Boolean equals(Date d)
current date. Otherwise, returns false.
Returns the number of milliseconds since
Long getTime()
the epoch.
Void setTime Sets the date and time of the current
object to represent msec milliseconds since
(long msec) the epoch.
String toString() Returns the string equivalent of the date.

EX :

import java.util.*;
public class Date_Demo
{
public static void main(String args[])
{
Date dt = new Date();
System.out.println(dt);

99
Java Brilliant

Date epoch = new Date(0);


System.out.println(epoch);
}
}

Output :

Fri May 25 00:04:06 IST 2012


Thu Jan 01 05:30:00 IST 1970

EX :
import java.util.Date;
public class date2
{
public static void main(String[] args)
{

Date d1 = new Date();

try
{
Thread.sleep(1000);
}
catch(Exception e){}

Date d2 = new Date();

System.out.println("First Date : " + d1);


System.out.println("Second Date : " + d2);
System.out.println("Is second date after first ? : " +
d2.after(d1));

}
}

Output :

First Date : Fri May 25 00:06:46 IST 2012


Second Date : Fri May 25 00:06:47 IST 2012
Is second date after first ? : true

NOTE: learn about thread sleep and try catch

EX :
import java.util.*;
public class date3
{

public static void main(String args[])


{

Date date = new Date();


System.out.println("Date is : " + date);
System.out.println("Milliseconds since January 1, 1970, 00:00:00
GMT : " + date.getTime());

Date epoch = new Date(0);


date.setTime(10000);

100
Java Brilliant

System.out.println("Time after 10 second " + epoch);


System.out.println("Time after 10 second " + date);
String st = date.toString();
System.out.println(st);
}

Output :

Date is : Fri May 25 00:12:52 IST 2012


Milliseconds since January 1, 1970, 00:00:00 GMT : 1337884972842
Time after 10 second Thu Jan 01 05:30:00 IST 1970
Time after 10 second Thu Jan 01 05:30:10 IST 1970
Thu Jan 01 05:30:10 IST 1970

& Gregorian class :

The Calendar class allows you to interpret date and time information.

This class defines several integer constants that are used when you get or set
components of the calendar. These are listed here.

AM AM_PM APRIL
AUGUST DATE DAY_OF_MONTH
DAY_OF_WEEK DAY_OF_WEEK_IN_MONTH DAY_OF_YEAR
DECEMBER DST_OFFSET ERA
FEBRUARY FIELD_COUNT FRIDAY
HOUR HOUR_OF_DAY JANUARY
JULY JUNE MARCH
MAY MILLISECOND MINUTE
MONDAY MONTH NOVEMBER
OCTOBER PM SATURADAY
SECOND SEPTEMBER SUNDAY
THURSDAY TUESDAY UNDERIMBER
WEDNESDAY WEEK_OF_MONTH WEEK_OF_YEAR
The Calendar class does not
have public constructors.
Instead, you may use the
YEAR ZONE_OFFSET static getInstance() method
to obtain a calendar
initialized to the current
date and time.

One of its forms is shown here:

101
Java Brilliant

Calendar getInstance()

EX :

import java.util.Calendar;
public class Cal1
{

public static void main(String[] args)


{

Calendar cal = Calendar.getInstance();

System.out.println("DATE is : " + cal.get(cal.DATE));


System.out.println("YEAR is : " + cal.get(cal.YEAR));
System.out.println("MONTH is : " + cal.get(cal.MONTH));
System.out.println("DAY OF WEEK is : " + cal.get(cal.DAY_OF_WEEK));
System.out.println("WEEK OF MONTH is : " + cal.get(cal.WEEK_OF_MONTH));
System.out.println("DAY OF YEAR is : " + cal.get(cal.DAY_OF_YEAR));
System.out.println("DAY OF MONTH is : " + cal.get(cal.DAY_OF_MONTH));
System.out.println("WEEK OF YEAR is : " + cal.get(cal.WEEK_OF_YEAR));
System.out.println("HOUR is : " + cal.get(cal.HOUR));
System.out.println("MINUTE is : " + cal.get(cal.MINUTE));
System.out.println("SECOND is : " + cal.get(cal.SECOND));
System.out.println("DAY OF WEEK IN MONTH is : " +
cal.get(cal.DAY_OF_WEEK_IN_MONTH));
System.out.println("Era is : " + cal.get(cal.ERA));
System.out.println("HOUR OF DAY is : " + cal.get(cal.HOUR_OF_DAY));
System.out.println("MILLISECOND : " + cal.get(cal.MILLISECOND));
System.out.println("AM_PM : " + cal.get(cal.AM_PM));// Returns 0 if AM
and 1 if PM
}
}

Output :

DATE is : 23
YEAR is : 2012
MONTH is : 9
DAY OF WEEK is : 3
WEEK OF MONTH is : 4
DAY OF YEAR is : 297
DAY OF MONTH is : 23
WEEK OF YEAR is : 43
HOUR is : 2
MINUTE is : 32
SECOND is : 32
DAY OF WEEK IN MONTH is : 4
Era is : 1
HOUR OF DAY is : 14
MILLISECOND : 595
AM_PM : 1

 The GregorianCalendar class is a subclass of Calendar.


 It provides the logic to manage date and time information according to the
rules of the Gregorian calendar.
 This class provides following constructors:

102
Java Brilliant

GregorianCalendar()

GregorianCalendar(int year, int month, int date)

GregorianCalendar(int year, int month, int date, int hour, int minute, int sec)

GregorianCalendar(int year, int month, int date, int hour, int minute)

 The first form creates an object initialized with the current date and time.
 The other forms allow you to specify how various date and time
components are initialized.
 The class provides all of the method defined by Calendar and also adds the
isLeapYear() method shown here:

Boolean isLeapYear()

This method returns true if the current year is a leap year. Otherwise, it returns
false.

EX :

import java.util.*;

public class gcal1


{
public static void main(String[] args)
{
GregorianCalendar c1 = new GregorianCalendar() ;

System.out.println("Is leap year " + c1.isLeapYear(c1.get(c1.YEAR)));


//here we get current year and check for leap year
System.out.println("DATE is : " + c1.get(c1.DATE));
System.out.println("YEAR is : " + c1.get(c1.YEAR));
System.out.println("MONTH is : " + c1.get(c1.MONTH));
System.out.println("DAY OF WEEK is : " + c1.get(c1.DAY_OF_WEEK));
System.out.println("WEEK OF MONTH is : " + c1.get(c1.WEEK_OF_MONTH));
System.out.println("DAY OF YEAR is : " + c1.get(c1.DAY_OF_YEAR));
System.out.println("DAY OF MONTH is : " + c1.get(c1.DAY_OF_MONTH));
System.out.println("WEEK OF YEAR is : " + c1.get(c1.WEEK_OF_YEAR));
System.out.println("HOUR is : " + c1.get(c1.HOUR));
System.out.println("MINUTE is : " + c1.get(c1.MINUTE));
System.out.println("SECOND is : " + c1.get(c1.SECOND));
System.out.println("DAY OF WEEK IN MONTH is : " +
c1.get(c1.DAY_OF_WEEK_IN_MONTH));
System.out.println("Era is : " + c1.get(c1.ERA));
System.out.println("HOUR OF DAY is : " + c1.get(c1.HOUR_OF_DAY));
System.out.println("MILLISECOND : " + c1.get(c1.MILLISECOND));
System.out.println("AM_PM : " + c1.get(c1.AM_PM));// Returns 0 if AM and
1 if PM */
}
}

Output :

Is leap yer true


DATE is : 23
YEAR is : 2012

103
Java Brilliant

MONTH is : 9
DAY OF WEEK is : 3
WEEK OF MONTH is : 4
DAY OF YEAR is : 297
DAY OF MONTH is : 23
WEEK OF YEAR is : 43
HOUR is : 2
MINUTE is : 37
SECOND is : 26
DAY OF WEEK IN MONTH is : 4
Era is : 1
HOUR OF DAY is : 14
MILLISECOND : 939
AM_PM : 1

Math Class :

 For scientific and engineering calculations, a variety of mathematical


functions are required.
 Java provides these functions in the Math class available in java.lang
package.
 The methods defined in Math class are given following:

Method Description
Returns the sine value of angle x in
Double sin(double x)
radians.
Returns the cosine value of the angle x in
Double cos(double x)
radians
Returns the tangent value of the angle x in
Double tan(double x)
radians
Returns angle value in radians for arcsin
Double asin(double x)
of x
Returns angle value in radians for arcos of
Double acos(double x)
x
Returns angle value in radians for
Double atan(double x)
arctangent of x
Double exp(double x) Returns exponential value of x
Double log(double x) Returns the natural logarithm of x
Double pow(double x, double y) Returns x to the power of y
Double sqrt(double x) Returns the square root of x
Int abs(double n) Returns absolute value of n
Returns the smallest wholoe number
Double ceil(double x)
greater than or equal to x
Returns the largest whole number less
Double floor(double x)
than or equal to x
Int max(itn n, int m) Returns the maximum of n and m
Int min(int n, int m) Returns the minimum of n and m
Double rint(double x) Returns the rounded whole number of x
Int round(float x) Returns the rounded int value of x
Long round(double x) Returns the rounded int value of x

104
Java Brilliant

Double random() Returns a random value between 0 and 1.0


Double toRandians(double angle) Converts the angle in degrees to radians
Double toDegrees(double angle) Converts the angle in radians to degrees

EX :

public class Angles


{
public static void main(String args[])
{
double theta = 120.0;
System.out.println(theta + " degrees is " +
Math.toRadians(theta) + " radians.");
theta = 1.312;
System.out.println(theta + " radians is " +
Math.toDegrees(theta) + " degrees.");
}
}

Output :

120.0 degrees is 2.0943951023931953 radians.


1.312 radians is 75.17206272116401 degrees.

Hashtable :

Hashtable is a part of the java.util library and is a concrete implementation of a


dictionary.

(Dictionary is a class that represents a key/value storage repository. Given a


key and value, you can store the value in a Dictionary object. Once the value
is stored, you can retrieve it by using its key.)

Hashtable stores key/value pairs in a hash table.

When using a Hashtable, you specify an object that is used as a key, and the
value that you want to link to that key.

The key is then hashed, and the resulting hash code is used as the index at
which the value is stored within the table.

The Hashtable constructors are shown here:

Hashtable()

Hashtable(int size)

The first constructor is the default constructor.

The second constructor creates a hash table that has an initial size specified
by size.

The methods available with Hashtable are

105
Java Brilliant

Method Description
Void clear() Resets and empties the hash table.
Returns true if some key equals to key
Boolean containsKey(Object key) exists within the hash table. Returns
false if the key isn’t found.
Returns true if some value equal to value
Boolean containsValue(Object value) exists within the hash table. Returns
false if the value isn’t found.
Returns an enumeration of the values
Enumeration elements( )
contained in the hash table.
Returns the object that contains the
Object get(Object key) value associated with key. If key is not in
the hash table, a null object is returned.
Returns true if the hash table is empty;
Boolean isEmpty( ) Returns false if it contains at least one
key.
Returns an enumeration of the keys
Enumeration keys( )
contained in the hash table.
Inserts a key and a value into the hash
Object put(Object key Object value)
table.
Removes key and its value. Returns the
Object remove(Object key) value associated with key. If key is not in
the hash table, a null object is returned.
Returns the number of entries in the
Int size( )
hash table.
Returns the string equivalent of a hash
String toString( )
table.

EX :

import java.util.*;

public class hash1


{
public static void main(String args[])
{
Hashtable marks = new Hashtable();
Enumeration names;
Enumeration emarks;
String str;
int nm;

// Checks wheather the hashtable is empty


System.out.println("Is Hashtable empty " + marks.isEmpty());
marks.put("Ram", 58);
marks.put("Laxman", 88);
marks.put("Bharat", 69);
marks.put("Krishna", 99);
marks.put("Janki", 54);

System.out.println("Is Hashtable empty " + marks.isEmpty());


// Creates enumeration of keys
names = marks.keys();
while(names.hasMoreElements())

106
Java Brilliant

{
str = (String) names.nextElement();
System.out.println(str + ": " +
marks.get(str));
}
/*
nm = (Integer) marks.get("Janki");
marks.put("Janki", nm+15);
System.out.println("Janki's new marks: " +
marks.get("Janki"));

// Creates enumeration of values


emarks = marks.elements();
while(emarks.hasMoreElements())
{
nm = (Integer) emarks.nextElement();
System.out.println(nm);
}

// Number of entries in a hashtable


System.out.println("The number of entries in a table are " +
marks.size());

// Checking wheather the element available

System.out.println("The element is their " +


marks.containsValue(88));
*/
// Removing an element from hashtable

System.out.println("========");
marks.remove("Bharat");
names = marks.keys();
while(names.hasMoreElements())
{
str = (String) names.nextElement();
System.out.println(str + ": " +
marks.get(str));
}
// Returning an String equivalent of the Hashtable

System.out.println("String " + marks.toString());


// Emptying hashtable

marks.clear();
System.out.println("Is Hashtable empty " + marks.isEmpty());
}
}

Output :

Laxman: 88
Janki: 54
Ram: 58
String {Krishna=99, Laxman=88, Janki=54, Ram=58}
Is Hashtable empty true

Introduction to wrapper class in java:


107
Java Brilliant

Wrapper Class :

 Java uses primitive types, such as int, char, double to hold the basic data
types supported by the language.
 Sometimes it is required to create an object representation of these
primitive types.
 These are collection classes that deal only with such objects. One needs to
wrap the primitive type in a class.
 To satisfy this need, java provides classes that correspond to each of the
primitive types. Basically, these classes encapsulate, or wrap, the primitive
types within a class.
 Thus, they are commonly referred to as type wrapper. Type wrapper are
classes that encapsulate a primitive type within an object.
 The wrapper types are Byte, Short, Integer, Long, Character, Boolean,
Double, Float.

These classes offer a wide array of methods that allow to fully integrate the
primitive types into Java’s object hierarchy.

Wrapper classes for converting simple types

Converting primitive numbers to Object numbers using constructor methods

NOTE : I, f, d and l are primitive data values denoting int, float, double and long
data types. They may be constants or variables.

Converting Object numbers to Primitive numbers using typeValue() method

Converting Numbers to Strings using toString() method

Converting String Object in to Numeric Object using static method ValueOf()

108
Java Brilliant

Converting Numeric Strings to Primitive numbers using Parsing method

NOTE : parseInt() and parseLong() methods throw a NumberFormatException if


the value of the str does not represent an integer.

Byte class example in java:


The Byte class encapsulates a byte value. It defines the constants
MAX_VALUE and MIN_VALUE and provides these constructors:

Byte(byte b)

Byte(String str)

Here, b is a byte value and str is the string equivalent of a byte value.

EX :

import java.util.*;
public class Byte_Demo
{
public static void main(String args[])
{
Byte b1 = new Byte((byte)120);
for(int i = 125; i<=135; i++)
{
Byte b2 = new Byte((byte)i);
System.out.println("b2 = " + b2);
}
System.out.println("b1 Object = " + b1);
System.out.println("Minimum Value of Byte = " + Byte.MIN_VALUE);
System.out.println("Maximum Value of Byte = " + Byte.MAX_VALUE);
System.out.println("b1* 2 = " + b1*2);
System.out.println("b1* 2 = " + b1.byteValue()*2);
Byte b3 = new Byte("120");
System.out.println("b3 Object = " + b3);
System.out.println("(b1==b3)? " + b1.equals(b3));
System.out.println("(b1.compareTo(b3)? " + b1.compareTo(b3));
/*Returns 0 if equal. Returns -1 if b1 is less than b3 and 1 if b1
is
greater than 1*/
}
}

Output :

b2 = 125
b2 = 126
b2 = 127
b2 = -128
b2 = -127
b2 = -126
109
Java Brilliant

b2 = -125
b2 = -124
b2 = -123
b2 = -122
b2 = -121
b1 Object = 120
Minimum Value of Byte = -128
Maximum Value of Byte = 127
b1* 2 = 240
b1* 2 = 240
b3 Object = 120
(b1==b3)? true
(b1.compareTo(b3)? 0

Short :

The Short class encapsulates a short value. It defines the constants MAX_VALUE
and MIN_VALUE and provides the following constructors:

Short(short s)

Short(String str)

EX :

import java.util.*;
public class Short_Demo
{
public static void main(String args[])
{
Short s1 = new Short((short)2345);
for(int i = 32765; i<=32775; i++)
{
Short s2 = new Short((short)i);
System.out.println("s2 = " + s2);
}
System.out.println("s1 Object = " + s1);
System.out.println("Minimum Value of Short = " + Short.MIN_VALUE);
System.out.println("Maximum Value of Short = " + Short.MAX_VALUE);
System.out.println("s1* 2 = " + s1.shortValue()*2);
Short s3 = new Short("2345");
System.out.println("s3 Object = " + s3);
System.out.println("(s1==s3)? " + s1.equals(s3));
Short s4 = Short.valueOf("10", 16);
System.out.println("s4 Object = " + s4);
}
}

Output :

s2 = 32765
s2 = 32766
s2 = 32767
s2 = -32768
s2 = -32767
s2 = -32766
110
Java Brilliant

s2 = -32765
s2 = -32764
s2 = -32763
s2 = -32762
s2 = -32761
s1 Object = 2345
Minimum Value of Short = -32768
Maximum Value of Short = 32767
s1* 2 = 4690
s3 Object = 2345
(s1==s3)? true
s4 Object = 16

Integer class :

The Integer class encapsulates an integer value. This class provides following
constructors:

Integer(int i)

Integer(String str)

Here, i is a simple int value and str is a String object.

EX :

import java.util.*;
public class Int_Demo
{
public static void main(String args[])
{
Integer i1 = new Integer(12);
System.out.println("I1 = " + i1);
System.out.println("Binary Equivalent = " +
Integer.toBinaryString(i1));
System.out.println("Hexadecimal Equivalent = " +
Integer.toHexString(i1));
System.out.println("Minimum Value of Integer = " +
Integer.MIN_VALUE);
System.out.println("Maximum Value of Integer = " +
Integer.MAX_VALUE);
System.out.println("Byte Value of Integer = " + i1.byteValue());
System.out.println("Double Value of Integer = " + i1.doubleValue());
Integer i2 = new Integer(12);
System.out.println("i1==i2 " + i1.equals(i2));
System.out.println("i1.compareTo(i2) = " + i2.compareTo(i1));
// Compareto - if it is less than it returns -1 else 1, if equal it
return 0.
Integer i3 = Integer.valueOf("11", 16);
System.out.println("i3 = " + i3);
}
}

Output :

I1 = 12
Binary Equivalent = 1100
Hexadecimal Equivalent = c
111
Java Brilliant

Minimum Value of Integer = -2147483648


Maximum Value of Integer = 2147483647
Byte Value of Integer = 12
Double Value of Integer = 12.0
i1==i2 true
i1.compareTo(i2) = 0
i3 = 17

Long :

The Long class encapsulates a long value. It defines the constants MAX_VALUE
and MIN_VALUE and provides the following constructors:

Long(long l)

Long(String str)

EX :

import java.util.*;

public class Long_Demo


{
public static void main(String args[])
{
Long L1 = new Long(68764);
Long L2 = new Long("686748");
System.out.println("Object L1 = " + L1);
System.out.println("Object L2 = " + L2);
System.out.println("Minimum Value of Long = " + Long.MIN_VALUE);
System.out.println("Maximum Value of Long = " + Long.MAX_VALUE);
System.out.println("L1 * 2 = " + L1 * 2);
System.out.println("L1.longValue() * 2 = " + L1.longValue() * 2);
System.out.println("L1.compareTo(l2) = " + L1.compareTo(L2));
System.out.println("L1==L2 ? = " + L1.equals(L2));
Long L3 = Long.valueOf("10", 16);
System.out.println("Object L3 = " + L3);
System.out.println("Byte value of Long = " + L1.byteValue());
System.out.println("int value of Long = " + L1.intValue());
System.out.println("Double value of Long = " + L1.doubleValue());
int i = 12;
System.out.println("Binary equivalent of decimal " + i + "=" +
Long.toBinaryString(i));
System.out.println("Hexadecimal equivalent of decimal " + i + "=" +
Long.toHexString(i));

}
}

Output :

Object L1 = 68764
Object L2 = 686748
Minimum Value of Long = -9223372036854775808
Maximum Value of Long = 9223372036854775807
L1 * 2 = 137528
L1.longValue() * 2 = 137528
L1.compareTo(l2) = -1
112
Java Brilliant

L1==L2 ? = false
Object L3 = 16
Byte value of Long = -100
int value of Long = 68764
Double value of Long = 68764.0
Binary equivalent of decimal 12=1100
Hexadecimal equivalent of decimal 12=c

Double class :

The Double class encapsulates a double value. It defines several constants.

The largest and smallest values are saved in MAX_VALUE and MIN_VALUE.

The constant NaN (Not a Number) indicates that a value is not a number.

If you divide a double number by zero, the result is NaN. This class defines
these constructors:

Double(double d)

Double(String str)

Here, d is a double value to be encapsulated in a Double object. In the last form,


str is the string representation of a double value.

EX :

import java.util.*;
class Double_Demo
{
public static void main(String args[])
{
Double d1 = new Double(687642365.4563);
Double d2 = new Double("686748");
System.out.println("Object d1 = " + d1);
System.out.println("Object d2 = " + d2);
System.out.println("Minimum Value of Double = " +
Double.MIN_VALUE);
System.out.println("Maximum Value of Double = " +
Double.MAX_VALUE);
System.out.println("Byte value of Double = " +
d1.byteValue());
System.out.println("int value of Double = " + d1.intValue());
System.out.println("Float value of Double = " +
d1.floatValue());
Double d3 = Double.parseDouble("765.89");
System.out.println("Double value from the string
\"765.89\"="+d3);

}
}

113
Java Brilliant

Output :

Object d1 = 6.876423654563E8
Object d2 = 686748.0
Minimum Value of Double = 4.9E-324
Maximum Value of Double = 1.7976931348623157E308
Byte value of Double = -3
int value of Double = 687642365
Float value of Double = 6.8764237E8
Double value from the string "765.89"=765.89

Float class :

The float class encapsulates a float value.

It defines several constants the largest and smallest values are stored in
MAX_VALUE and MIN_VALUE.

The constant NaN indicates that a value is not a number. If you divide a floating
– point number by zero, the result is NaN.

This class defines these constructors:

Float(float f)

Float(double d)

Float(String str)

Here, f and d are float and double types to be encapsulated in a Float object.

str is the string representation of a float value.

EX :

import java.util.*;

public class Float_Demo


{
public static void main(String args[])
{
Float f1 = new Float(123.5626);
Float f2 = new Float(854.32f);
Float i = new Float(10);
System.out.println("Object f1 = " + f1);
System.out.println("Object f2 = " + f2);
System.out.println("Minimum Value of Float = " +
Float.MIN_VALUE);
System.out.println("Maximum Value of Float = " +
Float.MAX_VALUE);
System.out.println("Byte value of Float = " +
f1.byteValue());

114
Java Brilliant

System.out.println("Short value of Float = " +


f1.shortValue());
System.out.println("Integer value of Float = " +
f1.intValue());
System.out.println("Double value of Float = " +
f1.doubleValue());
System.out.println("(f1==f2) ?= " + f1.equals(f2));
System.out.println("f1.compareTo(f2) = " + f1.compareTo(f2));
System.out.println("f1 is not a number = " + i.isNaN());

}
}

Output :

Object f1 = 123.5626
Object f2 = 854.32
Minimum Value of Float = 1.4E-45
Maximum Value of Float = 3.4028235E38
Byte value of Float = 123
Short value of Float = 123
Integer value of Float = 123
Double value of Float = 123.5625991821289
(f1==f2) ?= false
f1.compareTo(f2) = -1
f1 is not a number = false

Character class :

The Character class encapsulates a char value. This class provides the following
constructor.

Character(char ch)

Here, c is a char value. charValue() method returns the char value that is
encapsulated by a Character object and has the following form:

char charValue()

EX :

import java.util.*;

public class Char_Demo


{
public static void main(String args[])
{
Character c1 = new Character('m');
char c2 = 'O';
System.out.println("Object C1 = " + c1);
System.out.println("char value of Character Object = " +
c1.charValue());
System.out.println(c2 + " is defined character set ? " +
Character.isDefined(c2));
System.out.println("c2 is digit = " + Character.isDigit(c2));
System.out.println("c2 is lowercase character = " +
Character.isLowerCase(c2));
115
Java Brilliant

System.out.println("c2 is uppercase character = " +


Character.isUpperCase(c2));

}
}

Output :

Object C1 = m
char value of Character Object = m
O is defined character set ? true
c2 is digit = false
c2 is lowercase character = false
c2 is uppercase character = true

Boolean class :

The Boolean class encapsulates a Boolean value. It defines FALSE and TRUE
constants.

This class provides following constructors:

Boolean(Boolean b)

Boolean(String str)

Here, b is a Boolean value and str is the string equivalent of a Boolean value.

The methods associated with Boolean Class are as follows:

1. Boolean booleanValue()

2. Boolean equals(Boolean b)

3. String toString(Boolean b)

EX :

import java.util.*;

public class Boolean_Demo


{
public static void main(String args[])
{
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(false);
System.out.println("Object B1 = " + b1);
System.out.println("Object B2 = " + b2);
Boolean b3 = new Boolean("true");
Boolean b4 = new Boolean("false");
System.out.println("Object B3 = " + b3);
System.out.println("Object B4 = " + b4);
System.out.println("Boolean Value = " + b1.booleanValue());

116
Java Brilliant

System.out.println("(b1==b2)? " + b1.equals(b2));


String S1 = b1.toString();
System.out.println("String S1 " + S1);

}
}

Output :

Object B1 = true
Object B2 = false
Object B3 = true
Object B4 = false
Boolean Value = true
(b1==b2)? false
String S1 true

String Handling in java:


In Java, a string is defined as a sequence of characters.

But, unlike many other languages that implement strings as character arrays,
java implements strings as objects of type String.

Java handles String by two classes StringBuffer and String. The String and
StringBuffer classes are defined in java.lang.

Thus, they are available to all programs automatically.

1. String Concatenation (+)

EX :

import java.util.*;
class str3
{
public static void main(String args[])
{
String s1 = new String ("Java");
String s2 = "2all";
String s3 = s1+s2;
System.out.println("S1 = " + s1);
System.out.println("S2 = " + s2);
System.out.println("Concatenation Operator = " + s1+s2);
System.out.println("S3 = " + s3);

byte num [] = {65,66,67,68};


String s4 = new String(num);
System.out.println("S4 = " + s4);
}
}

Output :
117
Java Brilliant

S1 = Java
S2 = 2all
Concatenation Operator = Java2all
S3 = Java2all
S4 = ABCD

2. Character Extraction :

The String class provides ways in which characters can be extracted from a
String object.

3. String Comparison :

The String class provides several methods that compare strings or substrings
within strings.

equals( ) – used to compare two strings

General form:

Boolean equals(Object str)

Here, str is a String object.

It returns true if the strings contain the same character otherwise it returns
false.

The comparison is case-sensitive.

equalsIgnoreCase( ) – Same as equals but this ignores case.

General form:

Boolean equalsIgnoreCase(String str)

Here, str is the String object.

It returns true if the strings contain the same character otherwise it returns
false.

This is case in – sensitive.

regionMatches( )

This method compares a specific region inside a string with another specific
region in another string.

There is an overloaded form that allows you to ignore case in such comparisons.

General form:

118
Java Brilliant

Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int


numChars)

Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int


str2StartIndex, int numChars)

startsWith( ) and endsWith()

The startsWith( ) method determines whether a given String begins with a


specified string.

endsWith( ) determines whether the String ends with a specified string.

General Form

Boolean startsWith(String str)

Boolean endsWith(String str)

equals( ) Versus = =

Equals( ) method and the = = operator perform two different operations. The
equals ( ) method compares the characters inside a String object. The = =
operator compares two object references to see whether they refer to the same
instance.

compareTo( )

It is not enough to know that two strings just for equal or not. For sorting
applications, we need to know which is less than, equal to, or greater than the
other string.

The String method compareTo( ) serves this purpose.

General Form:

int compareTo(String str)

4 Modifying a string :

If we want to modify a String, we must either copy it into a StringBufer or we


can use following String methods:

5 valueOf() :

The valueOf() method converts data from internal format into a human-readable
form. It has several forms:

String valueOf(double num)

String valueOf(long num)

String valueOf(Object ob)

String valueOf(char chars[ ] )


119
Java Brilliant

String valueOf(char chars[], int startIndex, int numChars)

String Methods in java:


Example :

import java.util.*;
class str1
{
public static void main(String args[])
{
String s1 = "Bhagirath";
System.out.println("S1 = " + s1);
int length = s1.length();
System.out.println("S1 lenth = " + length);
System.out.println("S1 lowercase = " + s1.toLowerCase());
System.out.println("S1 uppercase = " + s1.toUpperCase());
System.out.println("S1 replace a with z = " +
s1.replace('a','z'));
System.out.println("S1 indexOf('e')= " + s1.indexOf('e'));
System.out.println("S1 lastindexof('e') = " +
s1.lastIndexOf('e'));
String s2 = "ViewSonic";
System.out.println("S2 = " + s2);
System.out.println("S1 and S2 trim = " + s1.trim() +
s2.trim());
System.out.println("S1 and S2 equals = " + s1.equals(s2));
System.out.println("S1 and S2 equals ignoring case = " +
s1.equalsIgnoreCase(s2));
System.out.println("S1 and S2 compareTo = " +
s1.compareTo(s2));
System.out.println("S1 and S2 concate = " + s1.concat(s2));
System.out.println("S1 substring(n) = " + s1.substring(5));
System.out.println("S1 substring(n,m) = " +
s1.substring(5,8));
System.out.println("S1 toString() = " + s1.toString());
int i = 100;
System.out.println("S1.valueOf(variable) = " +
(s1.valueOf(i)).length()); // converts the parameter to string
System.out.println("Start with " + s1.startsWith("P"));
System.out.println("Start with " + s1.endsWith("y"));

}
}

Output :

S1 = Bhagirath
S1 lenth = 9
S1 lowercase = bhagirath
S1 uppercase = BHAGIRATH
S1 replace a with z = Bhzgirzth
S1 indexOf('e')= -1
S1 lastindexof('e') = -1
S2 = ViewSonic

120
Java Brilliant

S1 and S2 trim = BhagirathViewSonic


S1 and S2 equals = false
S1 and S2 equals ignoring case = false
S1 and S2 compareTo = -20
S1 and S2 concate = BhagirathViewSonic
S1 substring(n) = rath
S1 substring(n,m) = rat
S1 toString() = Bhagirath
S1.valueOf(variable) = 3
Start with false
Start with false
import java.util.*;
class str4
{
public static void main(String args[])
{
String s = "This is a dAmo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[10];
//System.out.println("Character at 10 = " + s.charAt(10));
s.getChars(start, end, buf,0);
System.out.println(buf);
s.getChars(start, end, buf,5);
System.out.println(buf);

byte bt [] = new byte[10];


s.getBytes(start, end, bt,0);
System.out.println(bt[0]);
System.out.println(bt[1]);
System.out.println(bt[2]);
System.out.println(bt[3]);

char buf1[] = s.toCharArray();


System.out.println(buf1);

}
}

Output :

jav
jav jav
32
74
97
118
Welcome to Java2all

import java.util.*;
class str5
{
public static void main(String args[])
{
String s1 = "Rome was not built in a not day";
System.out.println("S1 = " + s1);
/*System.out.println("S1 = " + s1.indexOf('o'));

121
Java Brilliant

System.out.println("S1 = " + s1.indexOf("not"));


System.out.println("S1 = " + s1.indexOf('o',5));
System.out.println("S1 = " + s1.indexOf("not", 15));

System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o'));


System.out.println("S1 lastIndexOf= " +
s1.lastIndexOf("not"));
System.out.println("S1 lastIndexOf= " +
s1.lastIndexOf('o',15));
System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not",
15));
*/
String s2 = "Rome was not built in a Not day";
System.out.println("S2 = " + s2);
//System.out.println("S1 = " + s1.indexOf("not"));
//System.out.println("S1 = " + s1.lastIndexOf("not"));
System.out.println("Region Matches = ");
boolean b1 = s1.regionMatches(false,9,s2,24,3);
System.out.println("b1 = " + b1);

}
}

Output :

S1 = Rome was not built in a not day


S2 = Rome was not built in a Not day
Region Matches =
b1 = false

import java.util.*;
class str6
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

}
}

Output :

Hello equals Hello -> true


Hello == Hello -> false

StringBuffer class :

StringBuffer is a peer class of String. String creates strings of fixed length,


while StringBuffer creates strings of flexible length that can be modified in
terms of both length and content.

122
Java Brilliant

So Strings that need modification are handled by StringBuffer class.

We can insert characters and substrings in the middle of a string, or append


another string to the end.

StringBufer defines these Constructor:

StringBuffer()

StringBuffer(int size)

StringBuffer(String str)

Method Call Task Performed


Sb.length() Gives the current length of a StringBuffer.
Sb.capacity() Gives the total allocated capacity (default 16)
Set the length of the buffer within a String
setLength(int len)
Buffer object.
charAt(int where) Gives the value of character
Set the value of a character within a
setCharAt(int where, char ch)
StringBuffer.
S1.append(s2) Appends the string s2 to s1 at the end
Inserts the string s2 at the position n of the
S1.insert(n,s2)
string s1
S1.reverse() Reverse the string of s1
S1.deleteCharAt(nth) Delete the nth character of string s1
S1.delete(StartIndex, endIndex) Delete characters from start to end.

EX :

import java.util.*;

class strbuf1
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer("Bhagirath");
StringBuffer s3 = new StringBuffer(s2);
StringBuffer s4 = new StringBuffer(100);
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);

System.out.println("s1.length = " + s1.length());


System.out.println("s2.length = " + s2.length());
System.out.println("s3.length = " + s3.length());
System.out.println("s4.length = " + s4.length());

System.out.println("s1.capacity = " + s1.capacity());


System.out.println("s2.capacity = " + s2.capacity());
System.out.println("s3.capacity = " + s3.capacity());
System.out.println("s4.capacity = " + s4.capacity());

123
Java Brilliant

}
}

Output :

s1 =
s2 = Bhagirath
s3 = Bhagirath
s1.length = 0
s2.length = 9
s3.length = 9
s4.length = 0
s1.capacity = 16
s2.capacity = 25
s3.capacity = 25
s4.capacity = 100

EX :

import java.util.*;
class strbuf2
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Java2all");
StringBuffer s2 = new StringBuffer("Hello");
System.out.println("s1 = " + s1);
//System.out.println("s1.charAt(5) = " +
s1.charAt(5));
//s1.setCharAt(5,'z');
//System.out.println("s1 = " + s1);
//System.out.println("Inserting String = " +
s1.insert(5,s2));
//System.out.println("s1 = " + s1);
//System.out.println("Appending String = " +
s1.append(s2));
//System.out.println("s1 = " + s1);
//System.out.println("Reversing String = " +
s1.reverse());
//System.out.println("Deleting 5th character = " +
s1.deleteCharAt(5));
System.out.println("Deleting 5 to 8 character = " +
s1.delete(5,8));
}
}

Output :

s1 = Java2all
Deleting 5 to 8 character = Java2

EX :

import java.util.*;

public class strbuf3


{

124
Java Brilliant

public static void main(String[] args)


{

StringBuffer s = new StringBuffer("Hello world!");

System.out.println("s = " + s);


System.out.println("s.length() = " + s.length());
System.out.println("s.length() = " + s.capacity());
// Change the length of buffer to 5 characters:
s.setLength(5);

System.out.println(s);
System.out.println("s.length() = " + s.length());
System.out.println("s.length() = " + s.capacity());

}
}

Output :

s = Hello world!
s.length() = 12
s.length() = 28
Hello
s.length() = 5
s.length() = 28

java exception handling:


Exception is a run-time error which arises during the execution of java program.
The term exception in java stands for an “exceptional event”.

So Exceptions are nothing but some abnormal and typically an event or


conditions that arise during the execution which may interrupt the normal flow
of program.

An exception can occur for many different reasons, including the following:

· A user has entered invalid data.

· A file that needs to be opened cannot be found.

· A network connection has been lost in the middle of


communications, or the JVM has run out of memory.

“If the exception object is not handled properly, the interpreter will display the
error and will terminate the program.

Now if we want to continue the program with the remaining code, then we
should write the part of the program which generate the error in the try{} block
and catch the errors using catch() block..

125
Java Brilliant

Exception turns the direction of normal flow of the program control and send to
the related catch() block and should display error message for taking proper
action. This process is known as Exception handling.”

The purpose of exception handling is to detect and report an exception so that


proper action can be taken and prevent the program which is automatically
terminate or stop the execution because of that exception.

Java exception handling is managed by using five keywords: try, catch, throw,
throws and finally.

Try:

Piece of code of your program that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try block, it is
thrown.

Catch:

Catch block can catch this exception and handle it in some logical manner.

Throw:

System-generated exceptions are automatically thrown by the Java run-time


system. Now if we want to manually throw an exception, we have to use the
throw keyword.

Throws:

If a method is capable of causing an exception that it does not handle, it must


specify this behavior so that callers of the method can guard themselves against
that exception.

You do this by including a throws clause in the method’s declaration. Basically it


is used for IOException. A throws clause lists the types of exceptions that a
method might throw.

This is necessary for all exceptions, except those of type Error or


RuntimeException, or any of their subclasses.

All other exceptions that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.

Finally:

Any code that absolutely must be executed before a method returns, is put in a
finally block.

General form:

try {

// block of code to monitor for errors

126
Java Brilliant

catch (ExceptionType1 e1) {

// exception handler for ExceptionType1

catch (ExceptionType2 e2) {

// exception handler for ExceptionType2

// ...

finally {

// block of code to be executed before try block ends

Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class.

The exception class is a subclass of the Throwable class. Other than the
exception class there is another subclass called Error which is derived from the
Throwable class.

Errors :

These are not normally trapped form the Java programs.

Errors are typically ignored in your code because you can rarely do anything
about an error.

These conditions normally happen in case of severe failures, which are not
handled by the java programs. Errors are generated to indicate errors generated
by the runtime environment.

For Example :

(1) JVM is out of Memory. Normally programs cannot recover from errors.

(2) If a stack overflow occurs then an error will arise. They are also ignored at
the time of compilation.

The Exception class has two main subclasses:

(1) IOException or Checked Exceptions class and

127
Java Brilliant

(2) RuntimeException or Unchecked Exception class

(1) IOException or Checked Exceptions :

Exceptions that must be included in a method’s throws list if that method can
generate one of these exceptions and does not handle it itself. These are
called checked exceptions.

For example, if a file is to be opened, but the file cannot be found, an exception
occurs. These exceptions cannot simply be ignored at the time of compilation.

Java’s Checked Exceptions Defined in java.lang

(2) RuntimeException or Unchecked Exception :

Exceptions need not be included in any method’s throws list. These are
called unchecked exceptions because the compiler does not check to see if a
method handles or throws these exceptions.

As opposed to checked exceptions, runtime exceptions are ignored at the time of


compilation.

Java’s Unchecked RuntimeException Subclasses

Try and catch with example in


java:
We have already seen introduction about try and catch block in java exception
handling.

Now here is the some examples of try and catch block.

EX :

public class TC_Demo


{
public static void main(String[] args)
{
int a=10;
int b=5,c=5;
int x,y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
y = a / (b+c);

128
Java Brilliant

System.out.println("y = " + y);

Output :
Divide by zero
y=1

Note that program did not stop at the point of exceptional condition.It catches
the error condition, prints the error message, and continues the execution, as if
nothing has happened.

If we run same program without try catch block we will not gate the y value in
output. It displays the following message and stops without executing further
statements.

Exception in thread "main" java.lang.ArithmeticException: / by zero


at Thrw_Excp.TC_Demo.main(TC_Demo.java:10)

Here we write ArithmaticException in catch block because it caused by math


errors such as divide by zero.

Now how to display description of an exception ?

You can display the description of thrown object by using it in a println()


statement by simply passing the exception as an argument. For example;

catch (ArithmeticException e)

system.out.pritnln(“Exception:” +e);

Multiple catch blocks :

?It is possible to have multiple catch blocks in our program.

EX :

public class MultiCatch


{
public static void main(String[] args)
{
int a [] = {5,10};
int b=5;
try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}

129
Java Brilliant

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y = a[1]/a[0];
System.out.println("y = " + y);
}
}

Output :
Array index error
y=2

Note that array element a[2] does not exist. Therefore the index 2 is outside the
array boundry.

When exception in try block is generated, the java treats the multiple catch
statements like cases in switch statement.

The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will be skipped.

When you are using multiple catch blocks, it is important to remember that
exception subclasses must come before any of their superclasses.

This is because a catch statement that uses a superclass will catch exceptions of
that type plus any of its subclasses.

Thus, a subclass will never be reached if it comes after its superclass. And it will
result into syntax error.

// Catching super exception before sub

EX :

class Exception3
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;

try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}

catch (Exception e)
{

130
Java Brilliant

System.out.println("This is mistake. ");


}
catch(ArithmeticException g)
{
System.out.println("Division by zero");

}
}
}

Output :

If you try to compile this program, you will receive an error message because the
exception has already been caught in first catch block.

Since ArithmeticException is a subclass of Exception, the first catch block will


handle all exception based errors,

including ArithmeticException. This means that the second catch statement will
never execute.

To fix the problem, revere the order of the catch statement.

Nested try statements :

The try statement can be nested.

That is, a try statement can be inside a block of another try.

Each time a try statement is entered, its corresponding catch block has to
entered.

The catch statements are operated from corresponding statement blocks defined
by try.

EX :

public class NestedTry


{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;

try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " +
result1);
}
catch(ArithmeticException e)
{

131
Java Brilliant

System.out.println("This is inner
catch");
}
}
catch(ArithmeticException g)
{
System.out.println("This is outer catch");
}
}
}

Output :
This is outer catch

Java supports another statement known as finally statement that can be used to
handle an exception that is not caught by any of the previous catch statements.

We can put finally block after the try block or after the last catch block.

The finally block is executed in all circumstances. Even if a try block completes
without problems, the finally block executes.

EX :

public class Finally_Demo


{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;

try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");

}
finally
{
System.out.println("This is final");
}

}
}

Output :
Division by zero
This is final

132
Java Brilliant

Throw

We saw that an exception was generated by the JVM when certain run-time
problems occurred.

It is also possible for our program to explicitly generate an exception.

This can be done with a throw statement. Its form is as follows:

Throw object;

Inside a catch block, you can throw the same exception object that was provided
as an argument.

This can be done with the following syntax:

catch(ExceptionType object)

throw object;

Alternatively, you may create and throw a new exception object as follows:

Throw new ExceptionType(args);

Here, exceptionType is the type of the exception object and args is the optional
argument list for its constructor.

When a throw statement is encountered, a search for a matching catch block


begins and if found it is executed.

EX :

class Throw_Demo
{
public static void a()
{
try
{
System.out.println("Before b");
b();
}
catch(ArrayIndexOutOfBoundsException j) //manually thrown object
catched here
{
System.out.println("J : " + j) ;
}

public static void b()

133
Java Brilliant

{
int a=5,b=0;
try
{
System.out.println("We r in b");
System.out.println("********");
int x = a/b;
}
catch(ArithmeticException e)
{
System.out.println("c : " + e);
throw new ArrayIndexOutOfBoundsException("demo"); //throw from
here
}
}

public static void main(String args[])


{

try
{
System.out.println("Before a");
a();
System.out.println("********");
System.out.println("After a");
}
catch(ArithmeticException e)
{
System.out.println("Main Program : " + e);
}
}
}

Output :
Before a
Before b
We r in b
********
c : java.lang.ArithmeticException: / by zero
J : java.lang.ArrayIndexOutOfBoundsException: demo
********

After a

Throwing our own object :

?If we want to throw our own exception, we can do this by using the keyword
throw as follow.

throw new Throwable_subclass;

Example : throw new ArithmaticException( );

throw new NumberFormatException( );

EX :

import java.lang.Exception;

134
Java Brilliant

class MyException extends Exception


{
MyException(String message)
{
super(message);
}

}
class TestMyException
{
public static void main(String[] args)
{
int x = 5, y = 1000;
try
{
float z = (float)x / (float)y;
if(z < 0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught MyException");
System.out.println(e.getMessage());
}
finally
{
System.out.println("java2all.com");
}
}
}

Output :
Caught MyException
Number is too small
java2all.com

Here The object e which contains the error message "Number is too small" is
caught by the catch block which then displays the message using getMessage( )
method.

NOTE:

Exception is a subclass of Throwable and therefore MyException is a subclass of


Throwable class. An object of a class that extends Throwable can be thrown and
caught.

Throws

If a method is capable of causing an exception that it does not handle,

it must specify this behavior so that callers of the method can guard themselves
against that exception.

135
Java Brilliant

You do this by including a throws clause in the method’s declaration. Basically it


is used for IOException.

A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException,or
any of their subclasses. All other exceptions that a method can throw must be
declared in the throws clause.

If they are not, a compile-time error will result.

This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list

// body of method

Here, exception-list is a comma-separated list of the exceptions that a method


can throw.

Throw is used to actually throw the exception, whereas throws is declarative


statement for the method. They are not interchangeable.

EX :

class NewException extends Exception


{
public String toS()
{
return "You are in NewException ";
}
}

class customexception
{
public static void main(String args[])
{
try
{
doWork(3);
doWork(2);
doWork(1);
doWork(0);
}
catch (NewException e)
{
System.out.println("Exception : " + e.toS());
}
}

static void doWork(int value) throws NewException


{
if (value == 0)
{
throw new NewException();
}
136
Java Brilliant

else
{
System.out.println("****No Problem.****");
}
}
}

Output:
****No Problem.****
****No Problem.****
****No Problem.****
Exception : You are in NewException

Thread introduction - Multithreading in java:

Thread: A thread is a single flow of control like simple program.

A unique property of java is multithreading only because java supports


multithreading.

More than one thread (program) run simultaneously is known as multithreading


(multiprogramming).

In multithreading java interpreter handles the switching of control between the


threads in such a way that it looks like they are running concurrently.

Multithreading is useful in a number of ways. We can divide a long program into


number of threads and executes them in parallel.

We are going to learn so many useful things in thread lets start with single main
thread.

The Main Thread:

When our simple program starts one single thread begins running immediately.

This is called our single main thread.

The main thread create automatically when program is started.

It is very important thread because of two reason.

1.) From the main thread other child thread will be created.
137
Java Brilliant

2.) Main thread is all most everytime stop running lastly because it has to
remove or shutdown few resources as well as few action.

Now the question is how can we control our main thread?

Actually by calling the method currentThread() of Thread class we can control


our main thread.

EX:
public class Main_Thread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);

// change the name of the thread


t.setName("My Thread");
System.out.println("After name change: " + t);
try
{
for(int n = 5; n > 0; n--)
{
System.out.println(n); //print number with interval of 1
sec.
Thread.sleep(1000); //Thread is going to sleep for 1
sec.
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}

Output:

Current thread: Thread[main,5,main]


After name change: Thread[My Thread,5,main]
5
4
3
2
1

Here first of all we give reference of our current main single thread to t by thread
object and currentThread() method.

The number 5 to 1 will be print at interval of 1 second due to sleep method.

Thread will go to sleep for 1000 ms. due to sleep method

Now we will see the lifecycle of thread.

Thread Life Cycle:


Thread has many different state through out its life.
138
Java Brilliant

1 Newborn State

2 Runnable State

3 Running State

4 Blocked State

5 Dead State

Thread should be in any one state of above and it can be move from one state to
another by different methods and ways.

1 Newborn State

When we create a thread it will be in Newborn State.

The thread is just created still its not running.

We can move it to running mode by invoking the start() method and it can be
killed by using stop() method.

139
Java Brilliant

2 Runnable State

It means that thread is now ready for running and its waiting to give control.

We can move control to another thread by yield() method.

3 Running State

It means thread is in its execution mode becaause the control of cpu is given to
that particular thread.

140
Java Brilliant

It can be move in three different situation from running mode.

These all are different methods which can be apply on running thread and how
the state is changing and how we can come in our original previous state using
different methods are shown in above figure.

4 Blocked State

A thread is called in Blocked State when it is not allowed to entering in Runnable


State or Running State.

It happens when thread is in waiting mode, suspended or in sleeping mode.

5 Dead State

When a thread is completed executing its run() method the life cycle of that
particular thread is end.

141
Java Brilliant

We can kill thread by invoking stop() method for that particular thread and send
it to be in Dead State.

Creating Thread

Create Thread:

We can create thread in java with two different ways.

1. Extending the Thread Class.

2. Implements runnable interface.

lets try to understand step by step both of this.

1. Extending the Thread class:

In this method one normal class extends the inbuilt class thread and override its
run() method with the code required by that particular thread.

Here we are going to extend class java.lang.Thread. so we can access all the
methods of thread class.

Create one class which extends the thread class.

Override the run method and put lines of code inside thread method that will be
perform by thread.

Create an object of class which we created with extending the thread class and
call the start() method to execute the thread.

Class MyThread extends Thread

………………..

………………..

So now we have one thread named MyThread.

Implementing the run() method

Public void run()

………

// Thread code here

142
Java Brilliant

Starting new Thread

MyThread aTh = new MyThread(); // it instantiates a new object of class


MyThread

aTh.start(); // invokes run() method

EX:

class A extends Thread


{
public void run()
{
System.out.println("Thread A");
for(int i=1;i<=5;i++)
{
System.out.println("From thread A i = " + i);
}
System.out.println("Exit from A");

}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B");
for(int i=1;i<=5;i++)
{
System.out.println("From thread B i = " + i);
}
System.out.println("Exit from B");
}
}
public class Thread_Class
{
public static void main(String[] args)
{
new A().start(); //creating A class thread object and
calling run method
new B().start(); //creating B class thread object and
calling run method
System.out.println("End of main thread");
}
}

Output 1:

Thread A

From thread A i = 1
From thread A i = 2
From thread A i = 3
From thread A i = 4
From thread A i = 5
Exit from A

143
Java Brilliant

End of main thread


Thread B
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B

Output 2:

Thread A
From thread A i = 1
From thread A i = 2
End of main thread
From thread A i = 3
From thread A i = 4
Thread B
From thread A i = 5
From thread B i = 1
Exit from A
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B

Here you can see that both outputs are different though our program code is
same.

It happens in thread program because they are running concurrently on their


own.

Threads are running independently of one another and each executes whenever
it has a chance.

2. Implementing the Runnable interface:

In this method we have one interface named runnable and we implements this
interface for implement a thread.

Create one class which implements runnable interface.

Override the run() method and put some line of code for that particular thread.

Now create an object of inbuilt thread class and create an object of class that
implements runnable interface.

Give the reference of object to thread object by passing an argument (argument


must be the object of class which implements the runnable interface) while
creating a thread object.

Call the start() method to run the thread.

EX:

public class Thread_Interface


144
Java Brilliant

{
public static void main(String[] args)
{
X x1 = new X(); //class object
Thread xthread = new Thread(x1); //creating thread
object and giving reference of class object to thread object
xthread.start();
System.out.println("End of main Thread");
}

}
class X implements Runnable
{
public void run()
{
System.out.println("Inside X thread");
for(int i=1;i<=10;i++)
{
System.out.println("From xthread i = " +i);
}
System.out.println("Exit from X");
}
}

Output :

End of main Thread


Inside X thread
From xthread i = 1
From xthread i = 2
From xthread i = 3
From xthread i = 4
From xthread i = 5
From xthread i = 6
From xthread i = 7
From xthread i = 8
From xthread i = 9
From xthread i = 10
Exit from X

Thread Priority

Java Thread Priority:


Each java thread has its own priority which decides the order of thread to be
schedule.

The threads of equal priority will be given same treatment by java scheduler. And
they will follow the FCFS (First Come First Serve) algorithm.

User can also set the priority of thread by using the setPriority() method as
follow:

ThreadName.setPriority(int Number);

145
Java Brilliant

Here the number is integer value between 1 to 10, Here 1 is minimum priority 10
is maximum priority.

The Thread class defines few priority constants:

MIN_PRIORITY = 1

NORM_PRIORITY = 5

MAX_PRIORITY = 10

In any Thread the default priority is NORM_PRIORITY

In multithreading by assigning priority we can answer an input as quickly as we


want.

Whenever more than one threads are ready to run java system select the highest
priority thread and execute it

If another thread of higher priority comes the running thread will be preempted
by the incoming thread and current thread will move to runnable state.

EX:

class A extends Thread


{

public void run()


{
System.out.println("ThreadA strated");
for(int i = 1; i<=5; i++)
{
System.out.println("\t From ThreadA i = " +i);
}
System.out.println("Exit from A");
}
}

class B extends Thread


{
public void run()
{
System.out.println("ThreadB strated");
for(int j = 1; j<=5; j++)
{
System.out.println("\t From ThreadB j = " +j);
}
System.out.println("Exit from B");
}
}
public class Thread_Priority
{
public static void main(String[] args)
{
A threadA = new A();
B threadB = new B();

threadA.setPriority(Thread.MIN_PRIORITY);

146
Java Brilliant

threadB.setPriority(threadA.getPriority()+3);

System.out.println("Start Thread A");


threadA.start();

System.out.println("Start Thread B");


threadB.start();

System.out.println("End of main Thread");


}
}

Output:

Start Thread A

Start Thread B

End of main Thread

ThreadB strated

From ThreadB j = 1

From ThreadB j = 2

From ThreadB j = 3

From ThreadB j = 4

From ThreadB j = 5

Exit from B

ThreadA strated

From ThreadA i = 1

From ThreadA i = 2

From ThreadA i = 3

From ThreadA i = 4

From ThreadA i = 5

Exit from A

Here You can see that we start ThreadA first but than also ThreadB completed
its task first because of higher priority.

But again its multithreading so we all know that output may be vary each time
you run the program.

147
Java Brilliant

148

You might also like