Documente Academic
Documente Profesional
Documente Cultură
ACKENOWLEDGEMENTS
The Author is grateful to God,
his parents, teachers and
students(UIIT Batch 201014). Writing this requires
sincere efforts, hardwork and
blessings of omnipresent God
and other who motivated me
to write.
anurag RANA
OVERVIEW
CORE JAVA
1.Introduction
2.Data Types
3.Operators
4.Control Statements
5.Introduction to Class
7.Inheritance
8.Interfaces
9.Packages
INTERNET TECHNOLOGY (CORE JAVA)
10.
Wrapper Class
11.
12.
Exception Handling
13.
Multithread
CONTENTS
1.Introduction
a. History
b. Features of Java
c. Tokens
d. Java Literals
2.Data Types
a. Introduction
INTERNET TECHNOLOGY (CORE JAVA)
3.Operators
a. Introduction to operator
b. Arithmetic operators
c. Bitwise Operators
d. Relational Operators
e. Boolean Logical Operators
f. Assignment Operator
g. The ? Operator
4.Control Statements
a. Selection Statements
b. If selection statements
c. Switch selection statement
d. Looping statements
e. Jump Statements
5.Introduction to Class
a. What is class?
b. Declaring Objects
c. Introduction to method
d. Constructor
e. Keywords
f. Access Control
f. Recursion
g. Nested class
h. Command Line Argument
7.Inheritance
a. Inheritance
b. Super & final
c. Method overriding
d. Multilevel Inheritance
e. Dynamic Method Dispatch
f. Abstract Classes
g. Object Class
h. Polymorphism
8.Interfaces
a. Introduction
b. Defining interfaces
c. Implementing interfaces
d. Interface variables
e. Extending interfaces
9.Packages
a. Introduction
b. Vector class
c. Random class
d. Date class
e. Calendar & Gregorian class
f. Math Class
g. Hashtable
b. Byte
c. Short
d. Integer
e. Long
f. Double
g. Float
h. Character
i. Boolean
13.Multithreading
a. Introduction to thread
b. The Main Thread
c. Thread Life Cycle
d. Creating Thread
e. Thread Priority
CORE JAVA
History of java:
In 1991, Sun Microsystems was attempting to develop a new technology for programming
next generation smart appliances.
The original plan was for the Star7 operating system to be developed in C++ but rejected the idea for
several reasons. As a result we have new language that was better for the purposes of the Green project
than C++ developed by Gosling. He called the language Oak in honor of a tree that could be seen from his
office window.
James Gosling was part of Green, an isolated research project at Sun that was studying how to put
computers into everyday household items like thoughtful toasters, sagacious Salad Shooters and lucid
lamps. The group also wanted these devices to communicate with each other.
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:
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.
Platform Independent / Portable
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.
Simple and Powerful
Java inherits the C/C++ syntax and many of the object-oriented features of C++.so we can
say that Java was designed to be easy to learn and use. java provides a small number of clear ways to
achieve a given task. Unlike other programming systems that they provide dozens of complicated ways to
perform a simple task.
Secure
Java Compatible Browser, anyone can safely download Java applets without the fear of viral
infection or malicious intent because of its key design principle. So anyone can download applets with
confidence that no harm will be done and no security will be violated. Java achieves this protection by
confining a Java program to the Java execution environment and by making it inaccessible to other parts of
the computer.
Robust
Most programs in use today fail for one of the two reasons:
(i) MEMORY MANAGEMENT MISTAKES
For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This
sometimes leads to problems, because programmers will either forget to free memory that has been
previously allocated or, sometimes try to free some memory that another part of their code is still using.
Java virtually eliminates these problems by managing memory allocation (with the help of new operator)
and deallocation. (deallocation is completely automatic, because Java provides garbage collection for
unused objects.)
(ii) MISHANDLED EXCEPTIONAL CONDITIONS
With the help of Exception Handling (try.catch block), the programmer can easily handle an error
or exception so user can prevent the program by automatically stop the execution when an exception
found.
Thus, the ability to create robust programs was given a high priority in the design of Java.
Multithreaded
Java supports programming, which allows the user to write programs that perform many
functions simultaneously. The two or more part of the program can run concurrently then each part of such
a program is called a Thread and this type of programming is called multithreaded programming. Each
thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.
Architecture-neutral
The Java designers worked hard in achieving their goal write once; run anywhere,
anytime, forever and as a result the Java Virtual Machine was developed. Java is Architecture-neutral it
generates bytecode that resembles machine code, and are not specific to any processor.
Interpreted and High performance
The source code is first compile and generates the code into an intermediate
representation called Java bytecode which is a highly optimized set of instruction code. This code can be
interpreted on any system that has a Java Virtual Machine and generates the machine code. Java bytecode
was carefully designed by using a just-in-time compiler so that it can be easily translated into native
machine code for very high performance. Most of the earlier cross-platform solutions are run at the
expense of performance.
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.
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.
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 are tokens that represent names. These names can be assigned to variables,
methods, and classes to uniquely identify them to the compiler. 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.
Valid and invalid Java identifiers.
Valid
Invalid
HelloWorld
Hi_JAVA
value3
Tall
$age
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 cannot be use as a
identifier means cannot be used as names for a variable, class, or method.
There are 49 reserved keywords currently defined in the Java language (see the following table).
abstract
double
int
switch
assert
else
interface
synchronized
boolean
extends
long
this
break
false
native
throw
byte
final
new
transient
case
finally
package
true
catch
float
private
try
char
for
protected
void
class
goto
public
volatile
const
if
return
while
continue
implements
short
default
import
static
do
instanceof
super
The keywords const and goto are reserved but not used. In the early days of Java,several other keywords
were reserved for possible future use. In addition to the keywords, Java reserves the following: true, false,
and null. These are values defined by Java. You may not use these words for the names of variables,
classes, and so on.
Separators :
Separators are used to inform the Java compiler of how things are grouped in the code. For
example, items in a list are separated by commas much like lists of items in a sentence. The most
commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements.
Symbol
Name
Semicolon
Purpose
Terminates statements.
Comma
declaration.
Also used to chain statements together inside a for statement.
Braces
Also used to define a block of code, for classes, methods, and local scopes.
Parentheses
Brackets
Also used when dereferencing array values.
Period
Used to separate package names from subpackages and classes Also used to
separate a variable or method from a reference variable.
Type
Syntax
Usage
Example
Single-line
//
All characters after the // up to the end of the line //This is a Single-line style
comment are ignored.
comment.
Multiline
/*
comment All characters between /* and */ are ignored.
*/
/**
Same as /* */, except that the comment can be
/** This is a javadoc style
Documentation comment used with the javadoc tool to create automatic
comment. */
*/
documentation.
Literals :
A constant value in Java is created by using a literal representation of it.
For example, Here are some literals :
integer literal value : 100
floating-point literal value : 98.6
character literal value : X
string literal value : This is a test
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 32bit 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
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.
3.1415.
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.
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.
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. 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.
Operators:
Operators means specify an evaluation to be performed on a data (Operands).
Explanation :
public :
A keyword of the Java language that indicates that the element that follows should be made
available to other Java elements. Public keyword indicates that the FirstProg class is a public class,
which means other classes can use it.
class :
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 program, the identifier
FirstProg provides a name for the public class being defined here.
{:
The opening brace marks the beginning of the body of the class. The end of the body is marked by
the closing brace. Everything that appears within these braces belongs to the class. As you work with Java,
youll find that it uses these braces a lot.
//This is a first java program. :
This is a comment. Like most other programming languages, Java lets you enter a remark
into a programs source file. The contents of a comment are ignored by the compiler. Instead, a comment
describes or explains the operation of the program to anyone who is reading its source code. In this case,
the comment describes the program and reminds you that the source file should be called FirstProg.java.
Of course, in real applications, comments generally explain how some part of the program works or what a
specific feature does.
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 :
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. 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.
main :
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) :
Its called a parameter list, and its used to pass data to a method. Java requires that the
main method must receive a single parameter thats an array of String objects. By convention, this
parameter is named args. If you dont know what a parameter, a String, or an array is, dont worry about it
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.
System.out.println(Hello Java World! First JAVA program..........); :
Statement in the entire program. It calls a method named println that belongs to the System.out
object. System is a predefined class, it is automatically included in your programs that provides access to
the system and out is the output stream that is connected to the console. 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 Hello Java World! First
JAVA program................ enclosed in a set of double quotation marks. As a result, this statement displays
the text on the console.
Note: In Java, statements end with a semicolon. Because this is the only statement in the program, this
line is the only one that requires a semicolon. Java is case-sensitive. Thus, Main is different from main.
javac FirstProg.java
This command creates a class file named FirstProg.class that contains the Java bytecodes compiled for
the FirstProg class. Now run the program by entering this command:
java FirstProg
Output :
Hello Java World! First JAVA program................
Integers:This group includes byte, short, int, and long, which are for signed and unsigned number
including zero.
Floating-point numbers:This group includes float and double, which can store numbers with fractional
precision.
Characters:This group includes char, which represents symbols in a characterset, like letters and numbers.
Boolean:This group includes boolean, which is a special type for representing true/false values.
NOTE: The data types mentioned above are primitive data types. Java also support reference data types
like Array, Class and Interface.
1. Integers:
Java defines four integer types: byte, short, int, and long. All of these can have signed
unsigned or zero value. Java does not support unsigned, positive-only integers.
Name Width (in bits)
Range
long
64
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int
32
2,147,483,648 to 2,147,483,647
short
16
32,768 to 32,767
byte
08
128 to 127
Note: Divide width with 8 to get size in Bytes; the table mentioned above is providing width and range of
the integer data type. Width is the size the data type will occupy in the program if you write int a,b; than a
and b both will occupy 32 bits (4 bytes) in memory.
1.1 byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from 128 to 127
Exp. byte b1;
Variables of type byte are especially useful when were working with a stream of data from a network or
file.
1.2 short
Short is a signed 16-bit type. It has a range from 32,768 to 32,767 so if you are sure that your value will
not more than the range of Short data type than and only we recommended to use this.
Exp short s1,s2;
1.3 int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from
2,147,483,648 to 2,147,483,647.
Exp. 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 enough to hold
the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are
needed.
Prog.No.:- 1
//Demonstrate the integer data type
public class ITesst
{
public static void main(String[] args)
{
byte b1=50,b2=0;
short s1=10,s2=20;
Output :
2. Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
For example, calculations such as square root, or transcendental such as sine and cosine, result in a value
whose precision requires a floating-point type.
Name Width in Bits
Approximate Range
double
64
4.9e324 to 1.8e+308
float
32
1.4e-045 to 3.4e+038
2.1 float
Float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on
some processors and takes half as much space as double precision, but will become imprecise when the
values are either very large or very small. When you require to store floating point value use float and
double.
Ex. float r, pi;
2.2 double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precision is actually faster than single precision on some modern processors that have been optimized for
high-speed mathematical calculations.
Prog.No.:- 2
//Demonstrate floating point data type.
public class FTest
{
public static void main(String[] args)
{
float f1=1.2f,f2=123.2f;
Output :
3. Characters:
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. Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the characters found
in all human languages. In Java char require 16-bit. The range of a char is 0 to 65,536. There are no
negative chars. The standard set of characters known as ASCII still ranges from 0 to 127. The extended 8bit 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.
Prog.No.:- 3
//Demonstrate char data type.
public class CharTest
{
public static void main(String[] args)
{
char ch1, ch2;
ch1 = 88;
// code for X
ch2 = 'Y';
"+ch2);
}
}
Output :
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.
Exp. boolean b; So here the value of b is either true or false.
Prog.No.:- 4
//Demonstrate boolean data type.
public class BoolTest
{
public static void main(String[] args)
{
boolean b;
b = false;
b is " + b);
//never execute
Output :
b is false
VARIABLES IN JAVA
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 initialize. 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
Syntax for declaring a variable is...
type identifier1=val , identifier2;
Exp.
Dynamic Initialization
Prog.No.:- 5
public class VariableTest
{
public static void main(String[] args)
{
int l = 10;
int b = 20;
int a;
a = l * b;
System.out.println("normal initaialization : area is = "+a);
int area = l * b;
Prog.No.:- 6
// Demonstrate variable scope.
class Scope
{
public static void main(String args[])
{
int x;
x = 10;
if(x == 10)
{
Here we initialize variable x in main block but the variable y is initialized in if block so scope
of variable y is limited to if block. So we will get error on line no. 14 because we are trying to
access variable y which is outside of its scope.
Array:
It is a group of variables with same data types.
Data Type
Description
Array
A collection of several items of the same data type. For example names of
student.
Class
Interface
We have one dimensional and multidimensional array in java. It works differently compare to C and C++
language. 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.
Description
Only
Syntax
Example
Declaration
Declaration and
creation
char ch[]
Declares the array,
data type identifier[] ={A,B,C,D};
Declaration, creation allocates memory for
= {value1, value2, declares an array ch to
and initialization
it and assigns initial
.ValueN};
store 4 pre-as signed
values to its elements.
character values.
Exp.
month = new month[12];
So obtaining an array is a two-step process. First, you must declare a variable of the desired array type.
Second, you must allocate the memory that will hold the array, using new, and assign it to the array
variable. Thus, in Java all arrays are dynamically allocated. Now we have 12 different int type variable
month[0] to month[11]. It is possible to combine the declaration of the array variable with the allocation
of the array itself like... int month[] = new int[12];
In java array is an object even when the array is made up of primitive type and as with other class type, the
declaration does not create the object itself. Instead, the declaration of an array creates a reference that we
can use to refer to an array. Actual memory used by the array elements is allocated dynamically either by
new statement or by an array initializer.
Execution Stack
Char[]
A
B
C
D
createArray
this
main
Heap Memory
Fig. 1
NOTE:- Indexes the individual array elements always begins from 0 and must be maintained in the legal
Range: greater than 0 or equal to 0 and less than the array length. Any attempt to access an array element
outside these bounds causes a runtime exception.
Creating Reference Array:P=new Point[10]; // create an array of the 10 references of type Point. However, it does not
create 10 Point objects.
Execution Stack
Point []
createArray
this
main
Heap Memory
Fig. 2
Initializing Arrays:When we create an array every element is initialized. In case of char, each value is
initialized to the null(\u0000) character. In case of array p each value is initialized to null, indicating that
it does not refer to a Point object. After the assignment P[0]=new Point(), the first element of the array
refer to real Point object.
NOTE:Initializing all variables i including elements of arrays is essential to the security of the system. We
must not use variables in an uninitialized state.
Multidimensional array :
Declaration syntax : type var-name[ ][ ];
Exp.
int mat[ ][ ] = new int[4][5];
In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array
variable, specify each additional index using another set of square brackets. This allocates a 4 by 5 array
and assigns it to mat. Internally this matrix is implemented as an array of arrays of int. conceptually.
OPERATOR IN JAVA
Operator: It is a symbol that tells the computer to perform mathematical and logical calculation.
Java supports basically 6 types of operators.
1. Arithmetic operator
2. Bitwise operator
3. Relational operator
4. Boolean Logical operator
5. Assignment operator
6. Conditional operator
Arithmetic operator
Prog. No.:- 7
INTERNET TECHNOLOGY (CORE JAVA)
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
// pre_incr = ++d => d = d + 1 then pre_incr = d => d = 30 + 1 = 31 and
pre_incr = 31
System.out.println();
System.out.println("<-------Decrement Operator------->");
/* e = 40, f = 50
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 :
Bitwise operator
Prog. No.:- 8
public class BitewiseTest
{
public static void main(String[] args)
{
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;
int d = a & b;
//Bitwise OR operator
int e = a ^ b;
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();
System.out.println("<-------Bitewise Shift Operators------->");
int u = -1;
System.out.println("The original decimal value of u = " +u);
u = u >>> 30;
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;
Output :
..............Bitewise operators.................
<-------Bitewise Logical Operators------->
The binary value of a = 0010
The binary value of b = 0111
The Bitwise OR : a | b = 0111 and Decimal value = 7
The Bitwise AND : a & b = 0010 and Decimal value = 2
The Bitwise XOR(exclusive OR) : a ^ b = 0101 and Decimal value = 5
The Bitwise unary NOT : ~a & a = 0000 and Decimal value = 0 ~a&b|a&~b = 0101 and
Decimal value = 5
<-------Bitewise Shift Operators------->
The original binary value of a = 0010 and Decimal value of a = 2
The Left shift : a = a << 2 means a = 0010 << 2 hence a = 1000 and Decimal value of a
= 8
The original binary value of b = 0111 and Decimal value of b = 7
The Right shift : b = b >> 2 means b =
b = 1
The Unsigned Right shift : u = u >>> 30 means u = 11111111 11111111 11111111 11111111
>>> 30 hence u = 0011 and Decimal value of u = 3
<-------Bitewise Assignment Operators------->
The original binary value of p = 0101 and Decimal value of p = 5
The Bitewise Shift Right Assignment Operators : p >>= 2 means p = p >> 2 hence p =
0101 >> 2 so p = 0001 and Decimal value of p = 1
Relational operator
Prog. No.:- 9
// != Not equal to
{
if(mark == 65 | mark > 65)
to
System.out.println("You got a Third class and you got " + mark + "
marks........");
else
System.out.println("You are failed and you got " + mark + "
marks........");
}
else
System.out.println("Please give the valid mark...............");
}
}
Output :
..............Relational operators.................
Congratulation ,You got a distinction and you got 70 marks........
boolean b = true;
boolean c = a | b;
boolean d = a & b;
//Logical OR operator
boolean e = a ^ b;
System.out.println();
System.out.println("<---------Boolean Logical Assignment Operators---------
>");
//
Output :
Prog. No.:- 11
public class Boolean_ShortCircuitTest
{
public static void main(String[] args)
{
System.out.println("<---------Boolean Short-Circuit Operators--------->");
int i = 10;
int j = 20;
if (i != 10 && ++j/i>0)
{
System.out.println("i = "+i);
System.out.println("j = "+j);
}
Output :
Assignment operator
var = expression;
int x, y, z;
x = y = z = 50; // set x, y, and z to 50
Prog. No.:- 12
public class Assignment_OperatorTest
{
public static void main(String[] args)
{
System.out.println("<------------Assignment Operator------------->");
int x,y,z,sum;
varible
x = y = z = 50;
sum = x + y + z;
System.out.println("x + y + z = "+sum);
}
}
Output :
Conditional operator
It is also known as ternary operator or conditional operator.
Syntax:- expression1 ? expression2 : expression3
b = a < 0 ? -a : a;
Prog. No.:- 13
public class TernaryTest
{
public static void main(String[] args)
{
int a, b;
a = 50;
b = a < 0 ? -a : a; // get absolute value of a
System.out.println("The Absolute value of "+ a + " is " + b);
a = -10;
b = a < 0 ? -a : a; // get absolute value of a
Output :
SCANNER
Import java.uti.Scanner because the Scanner class is inside util package of java
library. Than we create reference (object) of class Scanner named s. "System.in" This is the
predefine library which allow user to enter value in any variable at run time through
keyboard. We can say same as scanf() in c and cin >> in c++.
Now in Scanner class there are so many different different methods for scaning different type of values.
Prog. No.:- 14
INTERNET TECHNOLOGY (CORE JAVA)
import java.util.Scanner;
public class ScannerTest
{
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();
int sum = a + b;
System.out.println("The addition of a and b : a + b = "+sum);
}
}Output
Selection Statements
If selection statements
Switch selection statement
Looping statements
Jump Statements
Selection Statements
Java supports two selection statements: if and switch. These statements allow you to control the
flow of your programs execution based upon conditions known only during run time.
if in java:
The if statement is Javas 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.
Prog. No.:- 15
import java.util.Scanner;
class larger
{
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 :
NOTE: The number of statement in if block is only one than parentheses are optional but if its more than
one than parentheses are compulsory. 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;
}
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.
Prog. No.:- 16
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 :
C:\java> javac result.java
C:\java> java result
The student has passed...
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.
Prog. No.:- 17
INTERNET TECHNOLOGY (CORE JAVA)
import java.util.Scanner;
class Day
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enet day between 0 to 6 Day = ");
int day = s.nextInt();
if (day == 0)
{
System.out.println("\n Sunday");
}
else if (day == 1)
{
System.out.println("\n Monday");
}
else if (day == 2)
{
System.out.println("\n Tuesday");
}
else if (day == 3)
{
System.out.println("\n Wednesday");
}
else if (day == 4)
{
System.out.println("\n Thursday");
}
else if (day == 5)
{
System.out.println("\n Friday");
}
else
{
System.out.println("\n Saturday");
}
}
}
Output :
C:\java> javac Day.java
C:\java> java Day
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....
}
Prog. No.:- 18
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
max=c;
}
else
{
if(b>c)
max=b;
else
max=c;
}
System.out.println("\n max value = " +max);
}
}
Output :
C:\java> javac MaxValue.java
C:\java> java MaxValue
max value = 15
switch :
The switch statement is Javas multi branch statement. It provides an easy way
to dispatch execution to different parts of your code based on the value of an expression. It
is difficult to understand large number of if else..if statements. So we have switch
statement.
Syntax :
switch (expression)
{
case value 1 :
statement 1 ; break;
case value 2 :
statement 2 ; break;
...
...
case value N :
statement N ; break;
default :
statements ; break;
}
The expression must be of type byte, short, int, or char; each of the values specified in the
case statements must be of a type compatible with the expression. Each case value must be
a unique literal (constant, not a variable). Duplicate case values are not allowed. The value
of the expression is compared with each case values. If a match is found, the
corresponding statement or statements are executed. If no match is found, statement or
statements in the default case are executed. Default statement is optional. If default
statement is absent, then if no matches are found, then the switch statement completes
without doing anything. The break statement is used inside the switch to terminate a
statement sequence.
Prog. No.:- 19
import java.util.Scanner;
public class Calculator
{
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");
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;
System.out.println("a / b = " + ans);
break;
default:
System.out.println("Enter correct choice");
}
}
Output :
C:\java> javac Calculator.java
C:\java> java Calculator
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
Looping statements
Javas repetition (iteration) statements are for, while, and do-while. These statements create
what we commonly call loops. A loop repeatedly executes the same set of instructions until a termination
condition is met.
1. for :
The for loop repeats a set of statements a certain number of times until a condition is
matched.
It is commonly used for simple iteration. The for loop appears as shown below.
Syntax :
for (initialization; condition; expression)
{
Set of statements;
}
The second part consists of a test condition that returns only a Boolean value. The
last part is an expression, evaluated every time the loop is executed.
Prog. No.:- 20
class ForTest
{
public static void main(String args[])
{
int i;
for (i=0;i<10;i++)
{
System.out.println("\nHELLO ! This is java For Loop.");
}
}
}
Output :
2. while :
The while loop executes a set of code repeatedly until the condition returns false.
Syntax :
while (condition)
{
body(statements) of the loop
}
Where <condition> is the condition to be tested. If the condition returns true then the
statements inside the <body of the loop> are executed.
Prog. No.:- 21
class WhileTest
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println("\n" + i);
i++;
}
}
}
Output :
C:\java> javac WhileTest.java
C:\java> java WhileTest
1
2
3
4
5
6
7
8
9
10
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.
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.
Prog. No.:- 22
class
DowhileTest
{
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 :
C:\java> javac
C:\java> java
DowhileTest.java
DowhileTest
The sum of 1 to 10 is .. 55
Nested loops :
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.
Prog. No.:- 23
INTERNET TECHNOLOGY (CORE JAVA)
Class NestedTest
{
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
{
System.out.print(".");
}
System.out.println();
}
}
}
Output :
C:\java> javac NestedTest.java
C:\java> java NestedTest
..........
.........
........
.......
......
.....
....
...
..
.
Jump Statements
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.
On encountering a break statement within a loop, the execution continues with the
next statement outside the loop.
The remaining statements which are after the break and within the loop are skipped.
statementName : SomeJavaStatement
break statementName;
The execution continues with the statement having the label. This is equivalent to a goto
statement of c and c++
Prog. No.:- 24
class BreakTest
{
public static void main(String args[])
{
int i = 1;
while (i<=10)
{
System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
}
}
}
Output :
C:\java> javac BreakTest.java
C:\java> java BreakTest
1
2
3
4
5
Break to a label
Prog. No.:- 25
class BreakT
{
public static void main (String args[])
{
boolean t=true;
a:
{
b:
{
c:
{
System.out.println("Before the break");
if(t)
break b;
System.out.println("This will not execute");
}
System.out.println("This will not execute");
}
System.out.println("This is after b");
}
}
}
Output :
C:\java> javac BreakT.java
C:\java> java BreakT
Before the break
This is after b
Continue statement
The remaining statements in the loop are skipped. The execution starts from the top
of loop again.
Prog. No.:- 26
INTERNET TECHNOLOGY (CORE JAVA)
class ContinueTest
{
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 :
C:\java> javac ContinueTest.java
C:\java> java ContinueTest
1
3
5
7
9
The last control statement is return. The return statement is used to explicitly return
from a method.
That is, it causes program control to transfer back to the caller of the method.
Prog. No.:- 27
class ReturnTest
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return;
// return to caller
Output :
C:\java> javac ReturnTest.java
C:\java> java ReturnTest
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.
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. The most important thing to understand about a
class is that it defines a new data type. Once defined, this new type can be used to create objects of that
type. Thus, a class is a template for an object, and an object is an instance of a class. Because an object is
an instance of a class, you will often see the two words object and instance used interchangeably.
Syntax of class:
class classname
{
type instance-variable1;
type instance-variable2;
//....
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
When we define a class, you declare its exact form and nature. We 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.
Prog. No.:- 28
void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}
// declaration
obj.y=20;
obj.displayPoint(); // calling a member method
}
}
Output :
C:\java> javac Coordinate.java
C:\java> java Coordinate
Printing the coordinates
10
20
Here x and y are data members of class MyPoint and displayPoint() is a member function of the same
class.
Syntax:
accessing data member of the class: objectname.datamember name;
accessing methods of the class: objectname.method name();
So for accessing data of the class: we have to use (.) dot operator.
NOTE: we can use or access data of any particular class without using (.) dot operator from inside that
particular class only.
\\ declaration of object.
Prog. No.:- 29
class Box
{
double width;
double height;
double depth;
}
class BoxTest
{
public static void main(String args[])
{
Output :
C:\java> javac BoxTest.java
C:\java> java BoxTest
Volume is 3000.0
Volume is 162.0
In program we can understand that each object has its own copies of the instance variables. This means
that if you have two Box objects, each has its own copy of depth, width, and height. It is important to
understand that changes to the instance variables of one object have no effect on the instance variables of
another.
Assigning Object Reference Variables :
Suppose
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.
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 OF METHOD
Classes usually consist of two things instance variables and methods.
Methods are defined as follows:
Return type
Name of the method
A list of parameters
Body of the method.
Syntax:
return type method name (list of parameters)
{
//Body of the method
}
return type specifies the type of data returned by the method. This can be any valid data type including
class types that you create. If the method does not return a value, its return type must be void, Means you
can say that void means no return. Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:
return value;
The list of parameter is a sequence of type and identifier pairs separated by commas. Parameters are
essentially variables that receive the value of the arguments passed to the method when it is called. If the
method has no parameters, then the parameter list will be empty.
Prog. No.:- 30
import java.util.Scanner;
class Box1
{
double width;
double height;
double depth;
void volume()
{
System.out.print("Volume is : ");
System.out.println(width * height * depth);
}
}
class Box1Test
{
public static void main(String args[])
{
Box box1 = new Box();
}
}
Output:
C:\java> javac Box1Test.java
C:\java> java Box1Test
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
Width, height and depth are data members of class Box and void volume () is method of class Box.
Method has no parameter and no return value.
Program in different way
Prog. No.:- 31
import java.util.Scanner;
class Box2
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
class Box2Test
{
public static void main(String args[])
{
double vol;
Box box1 = new Box();
Output:
C:\java> javac Box2Test.java
C:\java> java Box2Test
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
In program volume() method has return type double so we took one vol variable. It is a local variable of
class BoxDemo and it catches 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
Prog. No.:- 32
import java.util.Scanner;
class Box3
{
double width;
double height;
double depth;
double volume(double w, double h, double d)
{
return width * height * depth;
}
}
class Box3Test
{
public static void main(String args[])
{
double vo,wth,ht,dth;
Box box1 = new Box();
Output:
In program volume() method has three parameters as well as double return type. 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 IN JAVA
Java supports a special type of methods, called constructor that enables an object to
initialize itself when it is created. Constructors have the same name as the class it-self. Constructors do
not specify a return type, not even void. This is because they return the instance of the class itself. A
constructor is automatically called when an object is created.
Syntax:
Constructor_name([arguments])
{
// body
}
Non-Parameterized
2.
Parameterized
Non-Parameterized
Prog. No.:- 33
// Non - parameterised constructor
class Point1
{
int x;
int y;
Point1()
//constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + "
" + y);
}
}
class Point1Test
{
public static void main(String args[])
{
Point1 p1 = new Point1();
from here
p1.display();
Output:
C:\java> javac Point1Test.java
C:\java> java Point1Test
20
Parameterized
Prog. No.:- 34
// 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 Point2Test
{
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();
System.out.print("Enter int value for k : ");
k = s.nextInt();
Point2 p1 = new Point2(i,k);
p1.display();
}
}
Output:
C:\java> javac Point2Test.java
C:\java> java Point2Test
Enter int value for i : 10
Enter int value for k : 20
-----Printing the coordinates----10
20
KEYWORDS IN JAVA
We are going to learn few regularly used keywords.
1. new
2. this
3. static
4. super
5. final
new:
The new keyword dynamically allocates memory for an object.
Syntax:
EX.
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. We can have local variables, including
formal parameters to methods which overlap with the names of the class` instance variables. The local
variable hides the instance variable so we use this keyword. Another common use of this keyword is to
enable a constructor to invoke another constructor of the same class. java requires that the this(arg-list)
statement appear first in the constructor before any other statements.
Prog. No.:- 35
class abc
{
int x,y;
abc()
{
this(10,20);
}
abc(int x,int y)
{
this.x=x+5;
this.y=y+5;
Output :
C:\java> javac This_Test.java
C:\java> java This_Test
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. It
is possible in java to create a member that can be used by itself, without reference to a specific instance. To
create such a member, precede its declaration with the keyword static. When a member is declared static, it
can be accessed before any objects of its class are created, and without reference to any object. One can
declare both methods and variables to be static. The most common example of a static member is main().
Main () is declared as static because it must be called before any object exist. Instance variables declared
as static are actually, global variables. When objects of its class are declared, no copy of a static variable is
made. Instead, all instances of the class share the same static variable.
Method declared as static have several restrictions:
1.
2.
3.
One can also declare a static block which gets executed exactly once, when the class is first loaded.
Prog. No.:- 36
public class Static_Test
{
public static void main(String[] args)
{
display(40); //call static method
}
static int i = 5;
static int j;
int k = 10;
static void display(int a)
{
System.out.println("a = "+a);
// here a = 40
System.out.println("i = "+i);
// here i = 5
System.out.println("j = "+j);
* 10 = 5 * 10 =50 )
Output :
C:\java> javac Static_Test.java
C:\java> java Static_Test
Static block initialized..........
a = 40
i = 5
j = 50
super :
super keyword is used to call a superclass constructor and to call or access super class
members(instance variables or methods).
Syntax of super :
=> super(arg-list)
When a subclass calls super() it is calling the constructor of its immediate
superclass. super() must always be the first statement executed inside a subclass constructor.
=> super.member
Member can be either method or instance variables. This second form of super is
most applicable to situation in which member names of a subclass hide member of superclass due to same
name.
Prog. No.:- 37
class A1
{
public int i;
A1()
{
i=5;
}
}
class B1 extends A1
{
int i;
B1(int a,int b)
{
super();
i=b;
}
void show()
{
System.out.println("i in superclass = " + super.i );
System.out.println("i in subclass = " + i );
}
}
{
B1 b = new B1(10,12);
b.show();
}
}
Output :
C:\java> javac Usesuper.java
C:\java> java Usesuper
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.
final :
final keyword can be use with variables, methods and class.
=> final variables
When we want to declare constant variable in java we use final keyword.
Syntax : final variable name = value;
=> final method
Syntax: final methodname(arg)
When we put final keyword before method than it becomes final method. To prevent
overriding of method final keyword is used, means final method cant be override.
=> final class
A class that can not be sub classed is called a final class. This is archived in java
using the keyword final as follow. Any attempt to inherit this class will cause an error and compiler will
not allow it.
Syntax : final class class_name { ... }
Prog. No.:- 38
INTERNET TECHNOLOGY (CORE JAVA)
final class aa
{
final int a=10;
public final void ainc()
{
a++;
class bb extends aa
{
public void ainc()
{
System.out.println("a = " + a);
}
}
Error:.
Above program have 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
o We have seen that when no access control modifier is specified, it is called as default access.
o Classes written like this are not accessible in other package.
o Any variable declared without a modifier can be read or changed by any other class in the
same package.
o Any method declared the same way can be called by any other class in the same package.
o When a member does not have an explicit access specification,
o
Access
Public
Protected
Default
Private
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
No
No
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
Method overloading:
A class can contain any number of methods. Methods can be with parameter and
without parameter. The parameter in a method are called type signature. It is possible in java to define two
or more methods within the same class that share the same name, but with different parameter declarations
(type signatures). When this is the case, the methods are said to be overloaded, and the process is referred
to as method overloading. Overloading methods demonstrate the concept of polymorphism. When an
overloaded method is invoked, java uses the type and/or number of arguments as its guide to determine
which version of the overloaded method to call. Thus, overloaded methods must differ in the type and/or
number of their parameters. Overloaded methods may have different return types. When java encounters a
call to an overloaded method, it simply executes the version of the method whose parameters match the
arguments used in the call.
Prog. No.:- 39
//METHOD OVERLOADING
public class MethodOver
{
int n1;
int n2;
MethodOver()
{
n1 = 10;
n2 = 20;
}
void square()
{
System.out.println("The Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("The Square is " + n1 * n2);
}
void square(int p1, int p2)
{
n1 = p1;
n2 = p2;
System.out.println("The Square is " + n1 * n2);
}
public static void main(String args[])
{
MethodOver obj1 = new MethodOver();
obj1.square(); //call non parameterise method
obj1.square(4);
obj1.square(7,8);
}
}
Output :
C:\java> javac MethodOver.java
C:\java> java MethodOver
The Square is 200
The Square is 80
The Square is 56
We can see that there are 3 square methods with different argument. Its called method overloading.
Prog. No.:- 40
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;
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 :
C:\java> javac Circle.java
C:\java> java Circle
--Center at 5 and 5
Radius = 3
--Center at 10 and 20
Radius = 5
--Center at 15 and 25
Radius = 10
NOTE:- Above program is quite complicated here i am giving you perfect flow of program. First of all
note one thing that new ClassName() this is a short syntax of creating object of any class. And we all
know that when we create object the constructor of that class will be called automatically. So in our
program first of all due to syntax Circle c1 = new Circle(); non parameterize constructor will be called for
object c1 so we get output like Center at 5 and 5 Radius = 3 in c1.display(). Next due to syntax Circle c2 =
new Circle(10,20,5); constructor which has 3 arguments will be called for object c2 so we get output like
Center at 10 and 20 Radius = 5 in c2.display(). Now when we define object c3 our syntax is like Circle c3
= new Circle(new Point(15,25),10); so first of all it will create object for Point class so constructor of point
class will be called and it will set parameter x and y. Then constructor of circle class which has Point class
object as an argument along with one int argument will be called and set all parameter as per program and
we get output like Center at 15 and 25 Radius = 10 in c3.display().
Prog. No.:- 41
class PassObj
{
int n1;
int n2;
// constructor
PassObj()
{
n1 = 0;
n2 = 0;
}
obj2.multiply(obj1);
}
}
Output :
C:\java> javac PassObj.java
C:\java> java PassObj
Multiplication is 30
Prog. No.:- 42
class MetObjOv
{
int n1;
int n2;
// constructor
MetObjOv()
{
n1 = 0;
n2 = 0;
}
MetObjOv(int x, int y)
{
n1 = x;
n2 = y;
}
void multiply(MetObjOv p1)
{
n1 = p1.n1;
n2 = p1.n2;
System.out.println("There is nothing to multiply ");
System.out.println("n1 = "+n1+"\tn2 = " +n2);
}
void multiply(MetObjOv p1, MetObjOv p2)
{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;
Output :
C:\java> javac MetObjOv.java
C:\java> java MetObjOv
There is nothing to multiply
n1 = 5 n2 = 6
Return an Object.
A method can return any type of data, including class type (object) that you create.
Prog. No.:- 43
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 :
C:\java> javac RetObj.java
C:\java> java RetObj
An Example of returning an Object
n1 = 30 n2 = 30
RetObj multiply(RetObj p1, RetObj p2) This is the syntax in our program which has return type object.
obj3 = obj3.multiply(obj1, obj2); this is the syntax which calls method multiply and return object, it will
store in obj3.
CALL BY VALUE
In call by value when we call any method we pass value as method parameter so
changing in local variables of the method doesn't`t affect the original variables of class.This method copies
the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the
parameter of the subroutine have no effect on the argument. In java, when we pass a primitive type to a
method, it is passed by value. Thus, what occurs to the parameter that receives the argument has no effect
outside the method.
Prog. No.:- 44
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;
}
}
v.call(v.a,v.b);
// CALL BY VALUE
Output :
C:\java> javac CallBy_Value.java
C:\java> java CallBy_Value
a and b before call............
a = 10
b = 20
a and b after call............
a = 10
b = 20
We can see that after calling method we change value of a and b but it will not affect 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 :
We pass reference as parameter in function calling. We all know that reference means
object so we pass object as parameter. A reference to an argument (not value of argument) is passed to the
parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call.
This means that changes made to the parameters will affect the argument used to call the subroutine. When
we pass an object to a method, the situation changes, because objects are passed by call-by-reference.
When we create a variable of a class type, we are only creating a reference to an object. Thus, when you
pass this reference to a method, the parameter that receives it will refer to the same object as that referred
to by the argument. This effectively means that objects are passed to method do affect the object used as an
argument.
Prog. No.:- 45
INTERNET TECHNOLOGY (CORE JAVA)
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;
}
}
// CALL BY REFERENCE
Output :
C:\java> javac Reference.java
C:\java> java Reference
a and b before call............
a = 10
b = 20
a and b after call.............
a = 20
b = 40
We can see that after calling method value of original a and b is changed because of call by reference. We
pass "r" reference (Object) as parameter in method calling. So changes inside method will affect original
variable of class.
RECURSION
Recursion is the process of defining something in terms of itself. When function calls itself
is called recursion. A method that calls itself is said to be recursive.
Prog. No.:- 46
import java.util.Scanner;
class Factorial
{
// this is a recursive function
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
Output :
C:\java> javac Recursion.java
C:\java> java Recursion
Enter int no = 7
Factorial of7 is 5040
The method fact is recursive because it calls itself.The whole precess something like this result = fact(7-1)
* 7 and so on until it returns 1. So one thing is sure that we have to take care that in every recursive
process there must be a terminate condition to come out from recursion.
NESTED CLASS
It is possible to define a class within another class; such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
That means, if class B is defined within class A, then B is known to A, but not outside A.
If A is nesting class B, then A has access to all the members of B, including private members. But
the B does not have access to the members of nested class.
Static
2.
Non Static
Prog. No.:- 47
class InnerTest
{
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();
}
}
Output :
C:\java> javac InnerTest.java
C:\java> java InnerTest
Shipped 16 item(s) to Congo
Prog. No.:- 48
class OuterTest
{
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();
}
}
Here, y is declared as an instance variable of Inner. Thus it is not known outside of that class and it cannot
be used by showy( ).
Prog. No.:- 49
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i < args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
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
Inheritance :
The derivation of one class from another class is called Inheritance. A class that is inherited
is called a superclass. The class that does the inheriting is called as subclass. A subclass inherits all
instance variables and methods from its superclass and also has its own variables and methods. One can
inherit the class using keyword extends.
Syntax :
Class subclass-name extends superclass-name
{
// body of class.
}
In java, a class has only one super class. Java does not support Multiple Inheritance. One can create a
hierarchy of inheritance in which a subclass becomes a superclass of another subclass. However, no class
can be a superclass of itself.
Prog. No.:- 50
class A
//superclass
{
int num1;
//member of superclass
int num2;
//member of superclass
//method of superclass
{
num1 = no1;
num2 = no2;
}
}
class B extends A
//subclass B
{
int multi;
//member of subclass
void mul()
//method of subclass
{
multi = num1*num2;
}
}
class InheritTest
{
public static void main(String args[])
{
B subob = new B();
subob.setVal(5,6);
subob.mul();
System.out.println("Multiplication is
" + subob.multi);
}
}
Output :
C:\java> javac InheritTest.java
30
Note : Private members of super class is not accessible in subclass, super class is also called parent class
or base class, subclass is also called child class or derived class.
Method Overriding:
Defining a method in the subclass that has the same name, same arguments and
same return type as a method in the super class 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 super class.
Prog. No.:- 51
class Xsuper
{
int y;
Xsuper(int y)
{
this.y=y;
}
void display()
{
System.out.println("super y = " +y);
}
}
class Xsub extends Xsuper
{
int z;
Xsub(int z , int y)
{
super(y);
this.z=z;
}
void display()
{
System.out.println("super y = " +y);
System.out.println("sub z = " +z);
}
Output :
C:\java> javac TestOverride.java
C:\java> java TestOverride
super y = 200
sub z = 100
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 super class is called method overriding.
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
total = t;
}
void dispdatam()
{
dispdatas();
per = p;
}
void dispdatap()
{
dispdatam();
}
}
Output :
C:\java> javac Multi_Inherit.java
C:\java> java Multi_Inherit
Rollno = 1912
Name = SAM
Total = 350
Percentage = 50
It is common that a class is derived from another derived class. The class student serves as a base class for
the derived class marks, which in turn serves as a base class for the derived class percentage. The class
marks is known as intermediated base class since it provides a link for the inheritance between student and
percentage.
The chain is known as inheritance path. When this type of situation occurs, each subclass inherits all of the
features found in all of its super classes. In this case, percentage inherits all aspects of marks and
student. To understand the flow of program read all comments of program.
Q:- When a class hierarchy is created, in what order are the constructors for the classes that make
up the hierarchy called?
Ans: Constructors are called in order of derivation, from super class to subclass. Further, since super ( )
must be the first statement executed in a subclass constructor, this order is the same whether or not super (
) is used. If super ( ) is not used, then the default or parameter less constructor of each super class will be
executed. As you can see from the output the constructors are called in order of derivation. If you think
about it, it makes sense that constructors are executed in order of derivation. Because a super class has no
knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite
to any initialization performed by the subclass. Therefore, it must be executed first
Prog. No.:- 52
class X
{
X()
{
System.out.println("Inside X's constructor.");
}
}
class Y extends X
{
Y()
{
System.out.println("Inside Y's constructor.");
}
}
class Z extends Y
{
Z()
{
System.out.println("Inside Z's constructor.");
}
}
Output:
C:\java> javac CallingCons.java
C:\java> java CallingCons
Inside X's constructor.
Inside Y's constructor.
Inside Z's constructor.
Prog. No.:- 53
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");
}
}
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
Output :
C:\java> javac Dynamic_disp.java
C:\java> java Dynamic_disp
Inside A's callme method
Inside B's callme method
Inside C's callme method
Reference of type A, called r, is declared. The program then assigns a reference to each type of object to r
and uses that reference to invoke callme( ). As the output shows, the version of callme( ) executed is
determined by the type of object being referred to at the time of the call.
Abstract Classes :
When the keyword abstract appears in a class definition, it means
that zero or more of its methods are abstract. An abstract method has no body. Some of the subclass
has to override it and provide the implementation. Objects cannot be created out of abstract class.
Abstract classes basically provide a guideline for the properties and methods of an object. In order to
use abstract classes, they have to be sub classed. There are situations in which you want to define a
super class that declares the structure of a given abstraction without providing a complete
implementation of every method. That is, sometimes you want to create a super class 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 super class is unable to create a meaningful
implementation for a method.
Syntax :
abstract type name(parameter-list);
As you can see, no method body is present. Any class that contains one or more abstract methods must
also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of
the class keyword at the beginning of the class declaration. There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with the new operator. Any subclass of an
abstract class must either implement all of the abstract methods of the super class, or be itself declared
abstract.
Prog. No.:- 54
abstract class shape
{
double dim1;
double dim2;
shape(double a, double b)
{
dim1 = a;
dim2 = b;
}
abstract double area();
}
class rectangle extends shape
{
rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of rectangle.");
return dim1*dim2;
}
}
class triangle extends shape
{
triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of triangle.");
return dim1*dim2/2;
}
}
public class AbstractTest
{
public static void main(String args[])
{
rectangle r = new rectangle(10,20);
triangle t = new triangle(10,6);
System.out.println(r.area());
System.out.println(t.area());
}
}
Output:
C:\java> javac AbstractTest.java
C:\java> java AbstractTest
Area of rectangle.
200.0
Area of triangle.
30.0
OBJECT CLASS
Object class:
There is one special class, Object, defined by Java. All other classes are subclasses
of Object. That is, Object is a super class of all other classes. This means that a reference variable of type
Object can refer to an object of any other class. Every class in java is descended from the
java.lang.Object class. If no inheritance is specified when a class is defined, the super class of the class is
Object by default.
public class circle { ... }
is equivalent to
public class circle extends Object { ... }.
METHOD
PURPOSE
Object clone()
Void finalize()
Class getClass( )
int hashCode( )
void notify( )
void notifyAll( )
String toString( )
void wait( )
void wait(long milliseconds)
The methods getclass(), notify(), notifyall() and wait() are declared as final. We may override the
others.
tostring()
?public String tostring(). It returns a String that describes an object.
?It consisting class name, an at (@) sign and object memory address in hexadecimal.
EX :
Circle c1 = new Circle();
System.out.println(c1.tostring());
It will give O/P like Circle@15037e5
We can also write System.out.println(c1);
POLYMORPHISM
Polymorphism:
An object of a sub class can be used whenever its super class object is required. This is
commonly known as polymorphism. In simple terms polymorphism means that a variable of super type
can refer to a sub type object.
Fig. 4(Polymorphism)
JAVA INTERFACE
Java Interface:
{
Access-specifier return-type method-name(parameter-list);
final type var1=value;
}
Where, Access-specifier is either public or it is not given. When no access specifier is used, it results
into default access specifier and if interface has default access specifier then it is only available to
other members of the same package. When it is declared as public, the interface can be used by any
other code of other package.
Interface-Name: name of an interface, it can be any valid identifier.
The methods which are declared having no bodies they end with a semicolon after the parameter list.
Actually they are abstract methods; Any class that includes an interface must implement all of the
methods. Variables can be declared inside interface declarations. They are implicitly final and static,
means they cannot be changed by implementing it in a class. They must also be initialized with a
constant value.
EX :
interface Item
{
static final int code = 100;
static final String name = "Fan";
void display ( );
}
interface Area
{
static final float pi = 3.14F;
float compute ( float x, float y );
void show ( );
}
Implementing interfaces
Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, include the implements clause in a class definition, and then create the methods declared by
the interface.
The general form of a class that includes the implements clause looks like this:
The type-signature of implementing method must match exactly the type signature specified in the
interface.
Prog. No.:- 55
interface religion
{
String city = new String("Shimla");
void greet();
void pray();
}
class IfaceTest
{
public static void main(String args[])
{
gs s = new gs();
s.greet();
s.pray();
}
}
Output :
C:\java> javac IfaceTest.java
C:\java> java IfaceTest
We greet B.Tech 4th yr.
We pray at Shimla SummerHill
interface i2
{
void disp();
}
class IfaceTest7
{
public static void main(String args[])
{
c cobj = new c();
cobj.disp();
}
}
Output :
C:\java> javac IfaceTest7.java
C:\java> java IfaceTest7
This is display ..
Note : When implementing an interface method, it must be declared as public. It is possible for classes that
implement interfaces to define additional members of their own.
Partial Implementation of Interface :
If we want to implement an interface in a class we have to implement all the methods defined in the
interface. But if a class implements an interface but does not fully implement the method defined by
that interface, then that class must be declared as abstract.
Prog. No.:- 57
interface i1
{
void disp1();
void disp2();
}
class c2 extends c1
{
public void disp2()
{
System.out.println("This is display of 2");
}
}
class IfaceTest9
{
public static void main(String args[])
{
c2 c2obj = new c2();
c2obj.disp1();
c2obj.disp2();
}
}
Output :
C:\java> javac IfaceTest9.java
C:\java> java IfaceTest9
This is display of 1
This is display of 2
Prog. No.:- 58
interface AreaCal
{
final double pi = 3.14;
double areacalculation(double r);
}
double ar;
ar = pi*r*r;
return ar;
}
}
class IfaceTest09
{
public static void main(String args[])
{
double area;
AreaCal ac = new Circle();
ar = ac.areacalculation(10.25);
System.out.println("Area of Circle is : " + ar);
}
}
Output :
C:\java> javac IfaceTest09.java
C:\java> java IfaceTest09
Area of Circle is : 329.89625
Here variable ac is declared to be of the interface type AreaCal, it was assigned an instance of circle.
Although ac can be used to access the areacalculation() method, it cannot access any other members of the
client class. An interface reference variable only has knowledge of the method declared by its interface
declaration.
Extending interfaces:
One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes. When a class implements an interface that inherits another interface, It must
provide implementation of all methods defined within the interface inheritance.
Note: Any class that implements an interface must implement all methods defined by that interface,
including any that inherited from other interfaces.
Prog. No.:- 59
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_ IfaceTest
{
public static void main(String args[])
{
cls1 c1obj = new cls1();
c1obj.dispi1();
c1obj.dispi2();
}
Output :
C:\java> javac Ext_ IfaceTest.java
C:\java> java Ext_ IfaceTest
This is display of i1
This is display of i2
Prog. No.:- 60
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 :
C:\java> javac Multi_inhe_Test.java
C:\java> java Multi_inhe_Test
Displaying student details ..
Rollno = 1912
Name = Ram
Marks = 75
PACKAGES IN JAVA
Java inbuilt packages:
Package:
Packages are java`s way of grouping a variety of classes and/or interfaces together.
package firstPackage;
public class Firstclass
{
..................
body of class
.................
}
Vector class:
The Vector class is one of the most important in all of the Java class libraries. We cannot expand
the size of a static array.
We may think of a vector as a dynamic array that automatically expands as more elements are
added to it.
When space is needed to accommodate more elements, the capacity is automatically increased.
The first form creates a vector with an initial capacity of ten 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.
Prog. No.:- 61
import java.util.*;
Output :
C:\java> javac Vector_Test.java
C:\java> java Vector_Test
Internet
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.
Method
Description
Double nextDouble()
Float nextFloat()
Double nextGaussian()
Int nextInt()
Long nextLong()
Prog. No.:- 62
import java.util.*;
Output:
C:\java> javac Random_Test.java
C:\java> java Random_Test
64256704
1265771787
-1962940029
1372052
Date class:
The Date classes encapsulate information about a specific date and time.
It provides the following constructors.
Date()
Date(long msec)
Here, the first form returns an object that represent the current date and time.
The second form returns an object that represents the date and time msec in milliseconds after the
time.
The time is defined as midnight on January 1,1970 GMT (Greenwich Mean Time).
Method
Description
Boolean after(Date d)
Boolean before(Date d)
Boolean equals(Date d)
Long getTime()
Void setTime
(long msec)
String toString()
Prog. No.:- 63
import java.util.*;
public class Date_Test
{
public static void main(String args[])
{
Date_Test dt = new Date_Test();
System.out.println(dt);
Output :
C:\java> javac Date_Test.java
C:\java> java Date_Test
Thu Sep 05 05:04:06 IST 2013
Thu Jan 01 05:30:00 IST 1970
Prog. No.:- 64
import java.util.Date;
public class date2_Test
{
public static void main(String[] args)
{
try
{
Thread.sleep(1000);
}
catch(Exception e){}
Output :
C:\java> javac Date2_Test.java
C:\java> java Date_Test2
First Date : Thu Sep 05 05:06:46 IST 2013
Second Date : Thu Sep 05 05:06:47 IST 2013
Is second date after first ? : true
AM
AM_PM
APRIL
AUGUST
DATE
DAY_OF_MONTH
DAY_OF_WEEK
DAY_OF_WEEK_IN_MONT
DAY_OF_YEAR
H
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
ZONE_OFFSET
YEAR
Calendar getInstance()
Prog. No.:- 65
import java.util.Calendar;
public class Cal_Test
{
Output :
C:\java> javac Cal_Test.java
C:\java> java Cal_Test
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
It provides the logic to manage date and time information according to the rules of the Gregorian
calendar.
GregorianCalendar()
GregorianCalendar(int year, int month, int date)
GregorianCalendar(int year, int month, int date, int hour, int minute, int sec)
GregorianCalendar(int year, int month, int date, int hour, int minute)
The first form creates an object initialized with the current date and time.
The other forms allow you to specify how various date and time components are initialized.
The class provides all of the method defined by Calendar and also adds the isLeapYear() method
shown here:
Boolean isLeapYear()
This method returns true if the current year is a leap year. Otherwise, it returns false.
Math Class:
For scientific and engineering calculations, a variety of mathematical functions are required.
Java provides these functions in the Math class available in java.lang package.
Method
Description
Double sin(double x)
Double cos(double x)
Double tan(double x)
Double asin(double x)
Double acos(double x)
Double atan(double x)
Double exp(double x)
Double log(double x)
Double sqrt(double x)
Int abs(double n)
Double ceil(double x)
Double floor(double x)
Double rint(double x)
Int round(float x)
Long round(double x)
Double random()
Prog. No.:- 66
public class Angles
{
public static void main(String args[])
{
double theta = 120.0;
System.out.println(theta + " degrees is " + Math.toRadians(theta) + "
radians.");
theta = 1.312;
System.out.println(theta + " radians is " + Math.toDegrees(theta) + "
degrees.");
}
}
Output :
C:\java> javac Angles.java
Hashtable :
Hashtable is a part of the java.util library and is a concrete implementation of a
dictionary. (Dictionary is a class that represents a key/value storage repository. Given a key and value, you
can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key.)
Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is
used as a key, and the value that you want to link to that key. The key is then hashed, and the resulting
hash code is used as the index at which the value is stored within the table.
The Hashtable constructors are shown here:
Hashtable()
Hashtable(int size)
The first constructor is the default constructor.
The second constructor creates a hash table that has an initial size specified by size.
Description
Method
Void clear()
Enumeration elements( )
Boolean isEmpty( )
Enumeration keys( )
Int size( )
String toString( )
Prog. No.:- 67
import java.util.*;
Enumeration names;
Enumeration emarks;
String str;
int nm;
marks.get("Janki"));
while(emarks.hasMoreElements())
{
nm = (Integer) emarks.nextElement();
System.out.println(nm);
}
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 :
C:\java> javac Hash1.java
C:\java> java Hash1
Amit: 88
Jyoti: 54
Ankit: 58
String {Kriti=99, Amit=88, Jyoti=54, Ankit=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.
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 wrappers 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 Javas
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.
NOTE : parseInt() and parseLong() methods throw a NumberFormatException if the value of the str does
not represent an integer.
Prog. No.:- 68
INTERNET TECHNOLOGY (CORE JAVA)
import java.util.*;
public class Byte_Test
{
public static void main(String args[])
{
Byte_Test b1 = new Byte_Test ((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 :
C:\java> javac Byte_Test.java
C:\java> java Byte_Test
b2 = 125
b2 = 126
b2 = 127
b2 = -128
b2 = -127
b2 = -126
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)
Prog. No.:- 69
import java.util.*;
public class Short_Test
{
Output :
C:\java> javac Short_Test.java
C:\java> java Short_Test
s2 = 32765
s2 = 32766
s2 = 32767
s2 = -32768
s2 = -32767
s2 = -32766
s2 = -32765
s2 = -32764
s2 = -32763
s2 = -32762
s2 = -32761
s1 Object = 2345
Minimum Value of Short = -32768
Maximum Value of Short = 32767
s1* 2 = 4690
s3 Object = 2345
(s1==s3)? true
s4 Object = 16
Integer class:
The Integer class encapsulates an integer value. This class provides following constructors:
Integer(int i)
Integer(String str)
Here, i is a simple int value and str is a String object.
Prog. No.:- 70
import java.util.*;
public class Integer_Test
{
public static void main(String args[])
{
Integer_Test i1 = new Integer_Test (12);
System.out.println("I1 = " + i1);
System.out.println("Binary Equivalent = " + Integer.toBinaryString(i1));
System.out.println("Hexadecimal Equivalent = " + Integer.toHexString(i1));
Output :
C:\java> javac Integer_Test.java
C:\java> java Integer_Test
I1 = 12
Binary Equivalent = 1100
Hexadecimal Equivalent = c
Minimum Value of Integer = -2147483648
Maximum Value of Integer = 2147483647
Byte Value of Integer = 12
Double Value of Integer = 12.0
i1==i2 true
i1.compareTo(i2) = 0
i3 = 17
Long :
INTERNET TECHNOLOGY (CORE JAVA)
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)
Prog. No.:- 71
import java.util.*;
Output :
C:\java> javac Long_Test.java
C:\java> java Long_Test
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
L1==L2 ? = false
Object L3 = 16
Byte value of Long = -100
int value of Long = 68764
Double value of Long = 68764.0
Binary equivalent of decimal 12=1100
Hexadecimal equivalent of decimal 12=c
Double class:
The Double class encapsulates a double value. It defines several constants. The largest and smallest values
are saved in MAX_VALUE and MIN_VALUE. The constant NaN (Not a Number) indicates that a value is
not a number. If you divide a double number by zero, the result is NaN.
Prog. No.:- 72
import java.util.*;
class Double_Test
{
public static void main(String args[])
{
Double_Test d1 = new Double_Test (687642365.4563);
Double_Test d2 = new Double_Test ("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_Test d3 = Double.parseDouble("765.89");
System.out.println("Double value from the string \"765.89\"="+d3);
}
}
Output :
C:\java> javac Double_Test.java
Float class:
The float class encapsulates a float value. It defines several constants the largest and smallest values are
stored in MAX_VALUE and MIN_VALUE. The constant NaN indicates that a value is not a number. If
you divide a floating point number by zero, the result is NaN.
This class defines these constructors:
Float(float f)
Float(double d)
Float(String str)
Here, f and d are float and double types to be encapsulated in a Float object. str is the string representation
of a float value.
Prog. No.:- 73
import java.util.*;
}
}
Output :
C:\java> javac Float_Test.java
C:\java> java Float_Test
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
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().
Prog. No.:- 74
import java.util.*;
Output :
C:\java> javac Char_Test.java
C:\java> java Char_Test
Object C1 = m
char value of Character Object = m
O is defined character set ? true
c2 is digit = false
c2 is lowercase character = false
c2 is uppercase character = true
Boolean class:
The Boolean class encapsulates a Boolean value. It defines FALSE and TRUE constants.
This class provides following constructors:
Boolean(Boolean b)
Boolean(String str)
Here, b is a Boolean value and str is the string equivalent of a Boolean value.
The methods associated with Boolean Class are as follows:
1. Boolean booleanValue()
2. Boolean equals(Boolean b)
3. String toString(Boolean b)
Prog. No.:- 75
import java.util.*;
{
public static void main(String args[])
{
Boolean_Test b1 = new Boolean_Test (true);
Boolean_Test b2 = new Boolean_Test (false);
System.out.println("Object B1 = " + b1);
System.out.println("Object B2 = " + b2);
Boolean_Test b3 = new Boolean_Test ("true");
Boolean_Test b4 = new Boolean_Test ("false");
System.out.println("Object B3 = " + b3);
System.out.println("Object B4 = " + b4);
System.out.println("Boolean Value = " + b1.booleanValue());
System.out.println("(b1==b2)? " + b1.equals(b2));
String S1 = b1.toString();
System.out.println("String S1 " + S1);
}
}
Output :
C:\java> javac Boolean_Test.java
C:\java> java Boolean_Test
Object B1 = true
Object B2 = false
Object B3 = true
Object B4 = false
Boolean Value = true
(b1==b2)? false
String S1 true
String Handling:In Java, a string is defined as a sequence of characters. But, unlike many other
languages that implement strings as character arrays, java implements strings as objects of type String.
Java handles String by two classes StringBuffer and String. The String and StringBuffer classes are
defined in java.lang. Thus, they are available to all programs automatically.
Output :
C:\java> javac STest.java
C:\java> java STest
S1 = Java
S2 = 2all
Concatenation Operator = Java2all
S3 = Java2all
S4 = ABCD
Character Extraction :
The String class provides ways in which characters can be extracted from a String object.
String Comparison :
The String class provides several methods that compare strings or substrings within strings.
equals( ) used to compare two strings
General form:
Boolean equals(Object str)
Here, str is a String object.
It returns true if the strings contain the same character otherwise it returns false.
The comparison is case-sensitive.
equalsIgnoreCase( ) Same as equals but this ignores case.
General form:
Boolean equalsIgnoreCase(String str)
valueOf() :
The valueOf() method converts data from internal format into a human-readable form. It
has several forms:
String valueOf(double num)
String valueOf(long num)
String valueOf(Object ob)
String valueOf(char chars[ ] )
String valueOf(char chars[], int startIndex, int numChars)
Method Call
Task Performed
Sb.length()
Sb.capacity()
setLength(int len)
charAt(int where)
S1.append(s2)
S1.insert(n,s2)
S1.reverse()
S1.deleteCharAt(nth)
S1.delete(StartIndex, endIndex)
Prog. No.:- 77
import java.util.*;
class Strbuf_Test
{
public static void main(String args[])
{
Strbuf_Test s1 = new Strbuf_Test ();
Strbuf_Test s2 = new Strbuf_Test ("Anurag");
Strbuf_Test s3 = new Strbuf_Test (s2);
Strbuf_Test s4 = new Strbuf_Test (100);
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
}
}
Output :
C:\java> javac Strbuf_Test.java
C:\java> java Strbuf_Test
s1 =
s2 = Anurag
s3 = Anurag
s1.length = 0
s2.length = 9
s3.length = 9
s4.length = 0
s1.capacity = 16
s2.capacity = 25
s3.capacity = 25
s4.capacity = 100
Prog. No.:- 78
import java.util.*;
class Strbuf2_Test
{
public static void main(String args[])
{
Strbuf2_Test s1 = new Strbuf2_Test ("Anurag Rana");
Strbuf2_Test s2 = new Strbuf2_Test ("Hello");
System.out.println("s1 = " + s1);
//System.out.println("s1.charAt(6) = " + s1.charAt(6));
//s1.setCharAt(6,'z');
//System.out.println("s1 = " + s1);
//System.out.println("Inserting String = " + s1.insert(6,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 6th character = " + s1.deleteCharAt(6));
System.out.println("Deleting 6 to 11 character = " + s1.delete(6,11));
}
}
Output :
C:\java> javac Strbuf2_Test.java
C:\java> java Strbuf2_Test
s1 = Anurag Rana
Prog. No.:- 79
import java.util.*;
System.out.println(s);
System.out.println("s.length() = " + s.length());
System.out.println("s.length() = " + s.capacity());
}
}
Output :
C:\java> javac Strbuf3_Test.java
A network connection has been lost in the middle of communications, or the JVM has run
out of memory.
If the exception object is not handled properly, the interpreter will display the error and will terminate the
program.
Now if we want to continue the program with the remaining code, then we should write the part of the
program which generate the error in the try{} block and catch the errors using catch() block..
Exception turns the direction of normal flow of the program control and send to the related catch() block
and should display error message for taking proper action. This process is known as Exception handling.
The purpose of exception handling is to detect and report an exception so that proper action can be taken
and prevent the program which is automatically terminate or stop the execution because of that exception.
Java exception handling is managed by using five keywords: try, catch, throw, throws and finally.
Try:
Piece of code of your program that you want to monitor for exceptions are contained within
a try block. If an exception occurs within the try block, it is thrown.
Catch:
Catch block can catch this exception and handle it in some logical manner.
Throw:
System-generated exceptions are automatically thrown by the Java run-time system. Now if
we want to manually throw an exception, we have to use the throw keyword.
Throws:
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
You do this by including a throws clause in the methods declaration. Basically it is used for IOException.
A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their
subclasses.
All other exceptions that a method can throw must be declared in the throws clause. If they are not, a
compile-time error will result.
Finally:
Any code that absolutely must be executed before a method returns, is put in a finally block.
General form:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 e1) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 e2) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than the exception class there is another
subclass called Error which is derived from the Throwable class.
Errors :
These are not normally trapped form the Java programs.
Errors are typically ignored in your code because you can rarely do anything about an error.
These conditions normally happen in case of severe failures, which are not handled by the java programs.
Errors are generated to indicate errors generated by the runtime environment.
For Example :
(1) JVM is out of Memory. Normally programs cannot recover from errors.
(2) If a stack overflow occurs then an error will arise. They are also ignored at the time of compilation.
(2)
Exceptions need not be included in any methods throws list. These are
called unchecked exceptions because the compiler does not check to see if a method handles or throws
these exceptions. As opposed to checked exceptions, runtime exceptions are ignored at the time of
compilation.
Javas Unchecked RuntimeException Subclasses.
Output :
C:\java> javac TC_Test.java
C:\java> java TC_Test
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.
Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero.
Prog. No.:- 81
public class MultiCatch
{
public static void main(String[] args)
{
int a [] = {5,10};
int b=5;
try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
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 :
Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundary. When
exception in try block is generated, the java treats the multiple catch statements like cases in switch
statement. The first statement whose parameter matches with the exception object will be executed, and
the remaining statements will be skipped. When you are using multiple catch blocks, it is important to
remember that exception subclasses must come before any of their superclasses. This is because a catch
statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a
subclass will never be reached if it comes after its superclass. And it will result into syntax error.
// Catching super exception before sub
Prog. No.:- 82
class etion3
{
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)
{
System.out.println("This is mistake. ");
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}
}
}
Output :
If you try to compile this program, you will receive an error message because the exception has already
been caught in first catch block. Since ArithmeticException is a subclass of Exception, the first catch block
will handle all exception based errors, including ArithmeticException. This means that the second catch
statement will never execute. To fix the problem, revere the order of the catch statement.
Nested try statements:
The try statement can be nested. That is, a try statement can be inside a
block of another try. Each time a try statement is entered, its corresponding catch block has to enter. The
catch statements are operated from corresponding statement blocks defined by try.
Prog. No.:- 83
public class NestedTry
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException e)
{
System.out.println("This is inner catch");
}
}
catch(ArithmeticException g)
{
System.out.println("This is outer catch");
}
}
}
Output :
C:\java> javac NestedTry.java
C:\java> java NestedTry
This is outer catch.
Finally:
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.
Prog. No.:- 84
public class Finally_Test
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}
finally
{
System.out.println("This is final");
}
}
}
Output :
Throw:
We saw that an exception was generated by the JVM when certain run-time problems
occurred. It is also possible for our program to explicitly generate an exception. This can be done with a
throw statement.
Throw object;
Inside a catch block, you can throw the same exception object that was provided as an argument.
Syntax:
catch(ExceptionType object)
{
throw object;
}
Alternatively, you may create and throw a new exception object as follows:
Throw new ExceptionType(args);
Here, exceptionType is the type of the exception object and args is the optional argument list for its
constructor. When a throw statement is encountered, a search for a matching catch block begins and if
found it is executed.
Prog. No.:- 85
class Throw_Test
{
public static void a()
{
try
{
System.out.println("Before b");
b();
}
catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here
{
System.out.println("J : " + j)
}
}
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 :
C:\java> javac Throw_Test.java
C:\java> java Throw_Test
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.
Prog. No.:- 86
import java.lang.Exception;
}
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("uiit.hpu");
}
}
}
Output :
C:\java> javac TestMyException.java
C:\java> java TestMyException
Caught MyException
Number is too small
uiit.hpu
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:
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that
callers of the method can guard themselves against that exception. We do this by including a throws clause
in the methods declaration. Basically it is used for IOException. A throws clause lists the types of
exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or
RuntimeException,or any of their subclasses. All other exceptions that a method can throw must be
declared in the throws clause. If they are not, a compile-time error will result.
Prog. No.:- 87
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());
}
}
Output:
C:\java> javac Customexception.java
C:\java> java Customexception
****No Problem.****
****No Problem.****
****No Problem.****
MULTITHREADING IN JAVA
Thread: A thread is a single flow of control like simple program.
A unique property of java is multithreading only because java
supports multithreading. More than one thread (program) run simultaneously is known as multithreading
(multiprogramming). In multithreading java interpreter handles the switching of control between the
threads in such a way that it looks like they are running concurrently. Multithreading is useful in a number
of ways. We can divide a long program into number of threads and executes them in parallel.
1.) From the main thread other child thread will be created.
2.) Main thread is all most everytime stop running lastly because it has to remove or
shutdown few resources as well as few action.
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}
Output:
C:\java> javac Main_Thread.java
C:\java> java Main_Thread
Here first of all we give reference of our current main single thread to t by thread object and
currentThread() method. The number 5 to 1 will be print at interval of 1 second due to sleep method.
Thread will go to sleep for 1000 ms. due to sleep method
Thread Life Cycle:
1 Newborn State:
When we create a thread it will be in Newborn State. The thread is just created still
its not running. We can move it to running mode by invoking the start() method and it can be killed by
using stop() method.
2 Runnable State:
It means that thread is now ready for running and its waiting to give control. We can
move control to another thread by yield() method.
3 Running State:
It means thread is in its execution mode becaause the control of cpu is given to that
particular thread. It can be move in three different situation from running mode.
4 Blocked State:
A thread is called in Blocked State when it is not allowed to entering in Runnable
State or Running State. It happens when thread is in waiting mode, suspended or in sleeping mode.
5 Dead State:
When a thread is completed executing its run() method the life cycle of that
particular thread is end. We can kill thread by invoking stop() method for that particular thread and send it
to be in Dead State.
Create Thread:
We can create thread in java with two different ways.
1. Extending the Thread Class.
2. Implements runnable interface.
.
aTh.start();
}
}
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");
}
}
new B().start();
Output :
C:\java> javac Thread_Class.java
C:\java> java Thread_Class
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
End of main thread
Thread B
From thread B i = 1
From thread B i = 2
From thread B i = 3
From thread B i = 4
From thread B i = 5
Exit from B
}
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 :
C:\java> javac Thread_Interface.java
C:\java> java Thread_Interface
End of main Thread
Inside X thread
From xthread i = 1
From xthread i = 2
From xthread i = 3
From xthread i = 4
From xthread i = 5
From xthread i = 6
From xthread i = 7
From xthread i = 8
From xthread i = 9
From xthread i = 10
Exit from X