java_Notes1
java_Notes1
HISTORY OF JAVA
In 1991, Sun Microsystems was attempting to develop a nework technology for
programming next generation smart appliances.
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
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.
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:
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.)
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.
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.
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.
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 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).
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.
, Comma declaration.
Literals :
We describe this topic in next chapter named Literals.
5
Java Brilliant
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.
6
Java Brilliant
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
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.
This is demonstrating simple example program that displays the text,” My First
JAVA program...............” on the console.
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.
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 comment. Like most other programming languages, Java lets you enter
a remark into a program’s source file.
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
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.
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.
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 is the only statement in the entire program. It calls a method named println
that belongs to the System.out object.
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.
}:
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
java FirstProg
Output :
12
Java Brilliant
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.
Java defines eight types of data: byte, short, int, long, float, double, char and
boolean.
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.
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.
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
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
Variables of type byte are especially useful when you’re working with a stream
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
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
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
root, or transcendental such as sine and cosine, result in a value whose precision
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.
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
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.
Unicode defines a fully international character set that can represent all of the
characters
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.
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;
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?
Ex.
Dynamic Initialization
a = l * b;
System.out.println("normal initaialization : area is = "+a);
Output :
Normal initaialization : area is = 200
Dynamic initaialization : area is = 200
19
Java Brilliant
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.
So we will get error on line no. 14 because we are trying to access variable y
which is out side of its scope.
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.
20
Java Brilliant
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 :
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.
EX.
21
Java Brilliant
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 :
EX.
From the above image we can easily understand the indexing of multi
dimensional array.
22
Java Brilliant
1. Arithmatic operator
2. Bitwise operator
3. Relational operator
5. Assignment operator
6. Condetional operator
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();
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();
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.................
<-------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
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.
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------->");
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
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
28
Java Brilliant
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
EX.
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
Output :
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;
EX
Output :
<------------Assignment Operator------------->
x + y + z = 150
b = a < 0 ? -a : a;
EX.
Output :
32
Java Brilliant
These statements allow you to control the flow of your program’s execution
based upon conditions known only during run time.
Before going further let us know something about Scanner class of java.
Scanner :
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 :
33
Java Brilliant
Here we import java.uti.Scanner because the Scanner class is inside util package
of java library.
"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.
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
Output :
Tuesday
Nested if :
A nested if is an if statement that is the target of another if or else.
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.
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.
The value of the expression is compared with each ‘case’ values. If a match is
found, the corresponding statement or statements are executed.
If default statement is absent, then if no matches are found, then the switch
statement completes without doing anything.
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
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 :
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
}
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);
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;
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.
statementName : SomeJavaStatement
break statementName;
The execution continues with the statement having the label. This is equivalent
to a goto statement of c and c++..
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
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.
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
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?
Data members are nothing but simply variables that we declare inside the class
so it called data member of that particular class.
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.
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.
void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}
48
Java Brilliant
Output :
Here x and y are data members of class MyPoint and displayPoint() is a member
function of the same class.
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:
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.
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:
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.
Suppose
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.
§ Return type
§ A list of parameters
Syntax:
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;
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:
Volume is : 3000.00
Here width, height and depth are data members of class Box and void volume()
is method of class Box.
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:
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
Output:
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
Constructors do not specify a return type, not even void. This is because they
return the instance of the class itself.
Syntax:
Constructor_name([arguments])
// body
1. Non-Parameterized
2. Parameterized
54
Java Brilliant
1. Non-Parameterized:
Output:
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
Output:
Keywords
1. new
2. this
3. static
4. super
5. final
new:
The new keyword dynamically allocates memory for an object.
Syntax:
EX.
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.
java requires that the this(arg-list) statement appear first in the constructor
before any other statements.
EX :
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
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.
main() is declared as static because it must be called before any object exist.
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.
One can also declare a static block which gets executed exactly once, when the
class is first loaded.
EX :
58
Java Brilliant
Output :
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,
Java provides a set to access specifiers. Some aspects of access control are
related to inheritance or packages.
public:
private:
o A private variable can be used by methods in it’s own class but not
by objects of any other class.
o The only place these variables and methods can be seen is from
within their own class.
protected:
59
Java Brilliant
default:
o Any method declared the same way can be called by any other class
in the same package.
A class can contain any number of methods. Methods can be with parameter and
without parameter.
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.
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.
EX :
}
}
Output :
You can see that here we have 3 square methods with different argument.
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;
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);
}
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
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
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().
Now in next topic we will discuss about how you can return an object.
We have seen that methods can take parameters as input and process them.
class PassObj
{
int n1;
int n2;
// constructor
PassObj()
{
n1 = 0;
n2 = 0;
}
64
Java Brilliant
Output :
Multiplication is 30
// 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;
Output :
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);
}
Output :
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
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.
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 :
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 :
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 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
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 :
You can see that after calling method value of original a and b is changed
because of call by reference.
Recursion
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;
}
}
Output :
Enter int no = 7
Factorial of7 is 5040
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.
70
Java Brilliant
1. Static
2. Non – Static
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.
It has access to all of its variables and methods of its outer class and can
refer to them directly.
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
Output :
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();
}
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();
}
}
Sometimes you will want to pass information into a program when you run it.
This is accomplished by passing command-line arguments to main( ).
72
Java Brilliant
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 ?
Type of inheritance :
A subclass inherits all instance variables and methods from its superclass and
also has its own variables and methods.
Syntax :
// body of class.
73
Java Brilliant
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 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
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)
=> super.member
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 );
}
}
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 :
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.
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
}
76
Java Brilliant
{
public void ainc() //Cannot override the final method from aa
{
System.out.println("a = " + a);
}
}
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);
}
}
Output :
super y = 200
sub z = 100
Overloading VS Overriding :
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.
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);
}
}
78
Java Brilliant
Output :
Rollno = 1912
Name = SAM
Total = 350
Percentage = 50
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.
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.
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.");
}
}
Output:
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
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");
}
}
81
Java Brilliant
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Output :
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.
Abstract classes basically provide a guideline for the properties and methods
of an object.
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 :
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.
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");
}
}
Output :
B1's implementation
This is a concrete method
EX 2 :
double dim2;
shape(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}
System.out.println(r.area());
System.out.println(t.area());
}
}
Output:
Area of rectangle.
200.0
Area of triangle.
30.0
There is one special class, Object, defined by Java. All other classes are
subclasses of Object.
84
Java Brilliant
This means that a reference variable of type Object can refer to an object of any
other class.
If no inheritance is specified when a class is defined, the super class of the class
is Object by default.
EX :
is equivalent to
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
The methods getclass(), notify(), notifyall() and wait() are declared as final.
tostring()
85
Java Brilliant
?It consisting class name, an at (@) sign and object memory address in
hexadecimal.
EX :
System.out.println(c1.tostring());
Polymorphism :
An object of a sub class can be used whenever its super class object is required.
In simple terms polymorphism means that a variable of super type can refer to a
sub type object.
86
Java Brilliant
Java Interface:
Interfaces are similar to abstract classes, but differ in their functionality.
But, it can contain final variables, which must be initialized with values.
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++.
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.
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.
EX :
interface Item
88
Java Brilliant
void display ( );
interface Area
void show ( );
Implementing interfaces
Once an interface has been defined, one or more classes can implement that
interface.
The general form of a class that includes the implements clause looks like
this:
// 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.
89
Java Brilliant
interface religion
{
String city = new String("Amritsar");
void greet();
void pray();
}
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
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
interface i2
{
void disp();
}
91
Java Brilliant
class iface7
{
public static void main(String args[])
{
c cobj = new c();
cobj.disp();
}
}
Output :
This is display ..
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();
}
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 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 :
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.
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
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();
}
Output :
95
Java Brilliant
Java API packages : java API provides a large number of classes grouped into
different packages according to functionality.
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.
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);
96
Java Brilliant
package firstPackage;
..................
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.
Vector()
Vector(int n)
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)
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.
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
Output :
EX :
import java.util.Date;
public class date2
{
public static void main(String[] args)
{
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
Output :
EX :
import java.util.*;
public class date3
{
100
Java Brilliant
Output :
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.
101
Java Brilliant
Calendar getInstance()
EX :
import java.util.Calendar;
public class Cal1
{
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
102
Java Brilliant
GregorianCalendar()
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.*;
Output :
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 :
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
EX :
Output :
Hashtable :
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.
Hashtable()
Hashtable(int size)
The second constructor creates a hash table that has an initial size specified
by size.
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.*;
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"));
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
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
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.
NOTE : I, f, d and l are primitive data values denoting int, float, double and long
data types. They may be constants or variables.
108
Java Brilliant
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)
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
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.*;
}
}
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 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)
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 :
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.
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.
EX :
import java.util.*;
114
Java Brilliant
}
}
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.*;
}
}
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.
Boolean(Boolean b)
Boolean(String str)
Here, b is a Boolean value and str is the string equivalent of a Boolean value.
1. Boolean booleanValue()
2. Boolean equals(Boolean b)
3. String toString(Boolean b)
EX :
import java.util.*;
116
Java Brilliant
}
}
Output :
Object B1 = true
Object B2 = false
Object B3 = true
Object B4 = false
Boolean Value = true
(b1==b2)? false
String S1 true
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.
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);
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.
General form:
It returns true if the strings contain the same character otherwise it returns
false.
General form:
It returns true if the strings contain the same character otherwise it returns
false.
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
General Form
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.
General Form:
4 Modifying a string :
5 valueOf() :
The valueOf() method converts data from internal format into a human-readable
form. It has several forms:
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
}
}
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
}
}
Output :
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 :
StringBuffer class :
122
Java Brilliant
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
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);
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.*;
124
Java Brilliant
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
An exception can occur for many different reasons, including the following:
“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.”
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:
Throws:
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 {
126
Java Brilliant
// ...
finally {
Exception Hierarchy:
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 :
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.
127
Java Brilliant
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.
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.
EX :
128
Java Brilliant
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.
catch (ArithmeticException e)
system.out.pritnln(“Exception:” +e);
EX :
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.
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
}
}
}
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.
including ArithmeticException. This means that the second catch statement will
never execute.
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 :
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 :
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.
Throw object;
Inside a catch block, you can throw the same exception object that was provided
as an argument.
catch(ExceptionType object)
throw object;
Alternatively, you may create and throw a new exception object as follows:
Here, exceptionType is the type of the exception object and args is the optional
argument list for its constructor.
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) ;
}
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
}
}
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
?If we want to throw our own exception, we can do this by using the keyword
throw as follow.
EX :
import java.lang.Exception;
134
Java Brilliant
}
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:
Throws
it must specify this behavior so that callers of the method can guard themselves
against that exception.
135
Java Brilliant
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.
This is the general form of a method declaration that includes a throws clause:
// body of method
EX :
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());
}
}
else
{
System.out.println("****No Problem.****");
}
}
}
Output:
****No Problem.****
****No Problem.****
****No Problem.****
Exception : You are in NewException
We are going to learn so many useful things in thread lets start with single main
thread.
When our simple program starts one single thread begins running immediately.
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.
EX:
public class Main_Thread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
Output:
Here first of all we give reference of our current main single thread to t by thread
object and currentThread() method.
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
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.
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
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
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:
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.
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.
………………..
………………..
………
142
Java Brilliant
EX:
}
}
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
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.
Threads are running independently of one another and each executes whenever
it has a chance.
In this method we have one interface named runnable and we implements this
interface for implement a thread.
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.
EX:
{
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 :
Thread Priority
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.
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
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:
threadA.setPriority(Thread.MIN_PRIORITY);
146
Java Brilliant
threadB.setPriority(threadA.getPriority()+3);
Output:
Start Thread A
Start Thread B
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