in Java Applet. - Online Guru Jee

advertisement
Unit 1: Introduction to Java
What is programming?
Computer program is a set of instructions that guide a computer to execute a particular
task. Programming or coding is a language that is used by operating systems to perform the task.
We know computer understands binary languages with digits 1s and 0s. These binary languages
are difficult to understand by human, so we generally use an intermediate language instead of
binary language. Again the program uses high-level language that is interpreted into bytes that
the computer understands. So a programmer writes a source code and uses a tool or interpreter
that allows the computer to read, translate and execute the programs to perform a function.
Today there are different user friendly and easily understandable languages supporting different
styles of programming. Some of the computer languages are like formula translation
(FORTRAN), C, C++, PASCAL, BASIC, Java, C sharp(C#) and many other high-level
languages.
Today there are different user friendly and easily understandable languages supporting different
styles of programming. Some of the computer languages are like formula translation
(FORTRAN), C, C++, PASCAL, BASIC, Java, C sharp(C#) and many other high-level
languages.
These languages enable one to create and perform various kinds of applications. However, in the
whole process of programming it is important to understand that a program written in any of the
high-level languages needs to be converted to machine language to run on a computer. This
conversion is done with a complier or an interpreter. In all kinds of programming languages a
complier and if required an interpreter is available. But the basic difference between these two is
that the complier converts the entire program into machine code. An interpreter, on the other
hand, converts one statement at a time to machine language and executes it.
There are two different programming approaches; procedure oriented and object
oriented.
Difference between C and C++
C++, as the name suggests is a superset of C. As a matter of fact, C++ can run most of C code
while C cannot run C++ code. Here are the 10 major differences between C++ & C.
1. C follows the procedural programming paradigm while C++ is a multi-paradigm language
(procedural as well as object oriented)
In case of C, importance is given to the steps or procedure of the program while C++ focuses on
the data rather than the process.
Also, it is easier to implement/edit the code in case of C++ for the same reason.
2. In case of C, the data is not secured while the data is secured (hidden) in C++
This difference is due to specific OOP features like Data Hiding which are not present in C.
3. C is a low-level language while C++ is a middle-level language
C is regarded as a low-level language (difficult interpretation & less user friendly) while C++ has
features of both low-level(concentration on what’s going on in the machine hardware) & highlevel languages(concentration on the program itself) & hence is regarded as a middle-level
language.
4. C uses the top-down approach while C++ uses the bottom-up approach
In case of C, the program is formulated step by step, each step is processed into detail while in
C++, the base elements are first formulated which then are linked together to give rise to larger
systems.
5. C is function-driven while C++ is object-driven
Functions are the building blocks of a C program while objects are building blocks of a C++
program.
6. C++ supports function overloading while C does not
Overloading means two functions having the same name in the same program. This can be done
only in C++ with the help of Polymorphism(an OOP feature)
7. We can use functions inside structures in C++ but not in C.
In case of C++, functions can be used inside a structure while structures cannot contain functions
in C.
8. The NAMESPACE feature in C++ is absent in case of C
C++ uses NAMESPACE which avoid name collisions. For instance, two students enrolled in the
same university cannot have the same roll number while two students in different universities
might have the same roll number. The universities are two different namespace & hence contain
the same roll number(identifier) but the same university(one namespace) cannot have two
students with the same roll number(identifier)
9. The standard input & output functions differ in the two languages
C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output
functions
10. C++ allows the use of reference variables while C does not
Reference variables allow two variable names to point to the same memory location. We cannot
use these variables in C programming.
Difference between C and Java
1. JAVA is Object-Oriented while C is procedural. Different Paradigms, that is.
Most differences between the features of the two languages arise due to the use of
different programming paradigms. C breaks down to functions while JAVA breaks down to
Objects. C is more procedure-oriented while JAVA is data-oriented.
2. Java is an Interpreted language while C is a compiled language.
We all know what a compiler does. It takes your code & translates it into something the machine
can understand-that is to say-0′s & 1′s-the machine-level code. That’s exactly what happens with
our C code-it gets ‘compiled’. While with JAVA, the code is first transformed to what is called
the bytecode. This bytecode is then executed by the JVM(Java Virtual Machine). For the same
reason, JAVA code is more portable.
3. C is a low-level language while JAVA is a high-level language.
C is a low-level language(difficult interpretation for the user, closer significance to the machinelevel code) while JAVA is a high-level lagunage(abstracted from the machine-level details,
closer significance to the program itself).
4. C uses the top-down approach while JAVA uses the bottom-up approach.
In C, formulating the program begins by defining the whole and then splitting them into smaller
elements. JAVA(and C++ and other OOP languages) follows the bottom-up approach where the
smaller elements combine together to form the whole.
5. Pointer go backstage in JAVA while C requires explicit handling of pointers.
When it comes to JAVA, we don’t need the *’s & &’s to deal with pointers & their addressing.
More formally, there is no pointer syntax required in JAVA. It does what it needs to do. While in
JAVA, we do create references for objects.
6. The Behind-the-scenes Memory Management with JAVA & The User-Based Memory
Management in C.
Remember ‘malloc’ & ‘free’? Those are the library calls used in C to allocate & free chunks of
memory for specific data(specified using the keyword ‘sizeof’). Hence in C, the memory is
managed by the user while JAVA uses a garbage collector that deletes the objects that no longer
have any references to them.
7. JAVA supports Method Overloading while C does not support overloading at all.
JAVA supports function or method overloading-that is we can have two or more functions with
the same name(with certain varying parameters like return types to allow the machine to
differentiate between them). That it to say, we can overload methods with the same name having
different method signatures. JAVA(unlike C++), does not support Operator Overloading while C
does not allow overloading at all.
8. Unlike C, JAVA does not support Preprocessors, & does not really them.
The preprocessor directives like #include & #define, etc are considered one of the most essential
elements of C programming. However, there are no preprocessors in JAVA. JAVA uses other
alternatives for the preprocessors. For instance, public static final is used instead of the #define
preprocessor. Java maps class names to a directory and file structure instead of the #include used
to include files in C.
9. The standard Input & Output Functions.
Although this difference might not hold any conceptual(intuitive) significance, but it’s maybe
just the tradition. C uses the printf & scanf functions as its standard input & output while JAVA
uses the System.out.print & System.in.read functions.
10. Exception Handling in JAVA and the errors & crashes in C.
When an error occurs in a Java program it results in an exception being thrown. It can then be
handled using various exception handling techniques. While in C, if there’s an error, there IS an
error.
Difference between C++ and Java
1.
2.
3.
4.
5.
Java does not support pointers while in C++ there are pointers.
In java there is no operator overloading while in C++ there is operator overloading.
In java there are no preprocessors while in C++ there are preprocessors.
Java does not support structure and union while C++ supports structure and union.
In java there are no functions (only methods within class) while in C++ there are
functions.
6. In java there is no goto statement. (In java goto and const are reserved words but unused)
while there is goto statement in C++.
7. In java there are no global variables (variable is a part of class) while in C++ there are
global variables.
8. Java includes automatic garbage collection while C++ requires explicit memory
management.
9. Java provides interfaces in case of multiple inheritance while C++ supports multiple
inheritance.
10. The main difference between C++ and Java is that "C++ does not allow persistence
because it does not support database connection while Java allows persistence because it
supports database connection."
11. Java is reusable and more reliable, more secure than C++.
What is JAVA and History of JAVA
Java is a high-level object-oriented programming language developed by the Sun
Microsystems. Earlier, C++ was widely used to write object oriented programming languages,
however, it was not a platform independent and needed to be recompiled for each different
CPUs. A team of Sun Microsystems including Patrick Naughton, Mike Sheridan in the guidance
of James Goslings decided to develop an advanced programming language for the betterment of
consumer electronic devices. They wanted to make it new software based on the power of
networks that can run on different application areas, such as computers and electronic devices. In
the year 1991 they make platform independent software and named it Oak. But later due to some
patent conflicts, it was renamed as Java and in 1995 the Java 1.0 was officially released to the
world.
Where JAVA is used?
Earlier, java-programming language was only developed for the small devices but now it can be
found in a variety of devices like cell phones, e-commerce application, PCs and almost all
network or computing devices.
Java is available in different form:
JSP? Like PHP and ASP, Java Server Pages based on a code with normal HTML tags, which
helps in creating dynamic web pages.
Java Applets? This is another type of Java program that used within a web page to add many
new features to a web browser. These are small program used in the programming of instant
messaging, chat service, solving some complex calculation and for many other purposes.
J2EE ? The software Java 2 Enterprise Edition are used by various companies to transfer data
based on XML structured documents between one another.
JavaBeans ? This is something like Visual Basic and a reusable software component that can be
easily assemble to create some new and advanced application.
Features of JAVA
Java is:
1. Simple
2. Object-oriented
3. Distributed
4. Interpreted
5. Robust
6. Secure
7. Architecturally Neutral
8. Portable
9. High-Performance
10. Dynamic
1. Java is simple- There are various features that makes the java as a simple language.
Programs are easy to write and debug because java does not use the pointers explicitly. Error
prone tasks such as pointers and memory management have either been eliminated or are
handled by the Java environment automatically rather than by the programmer. Java provides
the bug free system due to the strong memory management. It also has the automatic memory
allocation and deallocation system.
2. Java is Object Oriented- To be an Object Oriented language, any language must follow at
least the four characteristics.




Inheritance: It is the process of creating the new classes and using the behavior of the
existing classes by extending them just to reuse the existing code and adding the
additional features as needed.
Encapsulation: It is the mechanism of combining the information and providing the
abstraction.
Polymorphism: As the name suggest one name multiple form, Polymorphism is the way
of providing the different functionality by the functions having the same name based on
the signatures of the methods.
Dynamic binding: Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.
As the languages like Objective C, C++ fulfills the above four characteristics yet they are not
fully object oriented languages because they are structured as well as object oriented languages.
But in case of java, it is a fully Object Oriented language because object is at the outer most level
of data structure in java. No stand alone methods, constants, and variables are there in java.
Everything in java is object even the primitive data types can also be converted into object by
using the wrapper class.
3. Java is distributed- Commonly used Internet protocols such as HTTP and FTP as well as
calls for network access are built into Java. Internet programmers can call on the functions
through the supplied libraries and be able to access files on the Internet as easily as writing to
a local file system.
4. Portable- The feature Write-once-run-anywhere makes the java language portable provided
that the system must have interpreter for the JVM. Java also have the standard data size
irrespective of operating system or the processor. These features makes the java as a portable
language.
5. Dynamic- While executing the java program the user can get the required files dynamically
from a local drive or from a computer thousands of miles away from the user just by
connecting with the Internet.
6. Secure- Java does not use memory pointers explicitly. All the programs in java are run under
an area known as the sand box. Security manager determines the accessibility options of a
class like reading and writing a file to the local disk. Java uses the public key encryption
system to allow the java applications to transmit over the internet in the secure encrypted
form. The bytecode Verifier checks the classes after loading.
Performance- Java uses native code usage, and lightweight process called threads. In the
beginning interpretation of bytecode resulted the performance slow but the advance version
of JVM uses the adaptive and just in time compilation technique that improves the
performance.
7. Multithreaded- As we all know several features of Java like Secure, Robust, Portable,
dynamic etc; you will be more delighted to know another feature of Java which
is Multithreaded.
Java is also a Multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time. Multiple threads execute
instructions according to the program code in a process or a program. Multithreading works
the
similar
way
as
multiple
processes
run
on
one
computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs
not even a single thread disturbs the execution of other thread. Threads are obtained from the
pool of available ready to run threads and they run on the system CPUs. This is how
Multithreading works in Java which you will soon come to know in details in later chapters.
8. Interpreted- We all know that Java is an interpreted language as well. With an interpreted
language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages.
The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to
this any error occurring in the program gets traced. This is how it is different to work with
Java.
9. Architecture Neutral- The term architectural neutral seems to be weird, but yes Java is an
architectural neutral language as well. The growing popularity of networks makes developers
think distributed. In the world of network it is essential that the applications must be able to
migrate easily to different computer systems. Not only to computer systems but to a wide
variety of hardware architecture and Operating system architectures as well. The Java
compiler does this by generating byte code instructions, to be easily interpreted on any
machine and to be easily translated into native machine code on the fly. The compiler
generates an architecture-neutral object file format to enable a Java application to execute
anywhere on the network and then the compiled code is executed on many processors, given
the presence of the Java runtime system. Hence Java was designed to support applications on
network. This feature of Java has thrived the programming language.
What is JDK (Java Development Kit)
JDK is a software development program provided by Sun Microsystems. Java Development Kit
or JDK comes in various version and can be downloaded free from the Sun Microsystems. JVM
compiler, debugger and other tools are used with JDK for developing java based application &
java applets. So make sure that your JVM compiler & JDK versions are same.
JDK also known as Java 2 platform, which comes in three editions J2ME, J2SE & J2EE. If you
are beginner or learning Java then start by downloading J2SE.
Acronyms:
JDK Java Development Kit
JVM Java virtual machine
Latest version of JDK
JDK 5.0 Update 6
The full internal version number for this update release is 1.5.0_06-b05 (where "b" means
"build").
Program to print “Hello world” in Java
Java is a high level programming language and it is used to develop the robust application. Java
application program is platform independent and can be run on any operating System.
To write the Hello world program you need simple text editor like note pad and jdk must be
install in your machine for compiling and running.
Note- Java is a case sensitive programming language.
Write the following code into your notepad to run the “Hello World” program .
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Ist step- Save the file. In this example we have saved the file in the "D:\java\example" directory.
The file name should be match the class name and to save the file give the .java extension.
e.g. HelloWorld.java
IInd step- Now open the command prompt to compile the HelloWorld.java program. Go to the
directory where you have saved the file ( in our case D:\java\example>) and issue the following
command to compile the program:
D:\java\example>javac HelloWorld.java
javac is a compiler in the java Language. Java compiler change the programming Language into
machinery language. So that the java virtual can understand it. Once the compilation is
successful a new file will be created with the name HelloWorld.class. To run the program issue
the following command on command prompt:
D:\java\example>java HelloWorld
You will see the following result on the command prompt.
Hello World!
Here is the screen shot of the above steps:
Compilation Using Java and execution using Java
In Java, programs are not compiled into executable files, they are compiled into Bytecode which
the JVM then executes at runtime. Java source code is compiled into bytecode when we use
the javac compiler. The bytecode gets saved on the disk with the file extension .class. When the
program is to be run, the bytecode is converted, using the Just-In-Time(JIT) compiler. The result
is machine code which is then fed to the memory and is executed.
So Java has two step compilations:

Step one to create byte-code

Step two to create machine level code
The Java classes/Byte Codes are compiled to machine code and loaded into memory by the JVM
when needed the first time. This is different than other languages like C/C++ where the whole
program had to be compiled to machine code and linked to create an executable file, before the
program could start.
JIT compilers compile byte-code once and the compiled machine code are re-used again and
again, to speed up execution. Early Java compilers compiled the byte-code to machine code each
time it was used, but more modern compilers cache this machine code for reuse on the machine.
Even then, java's JIT compiling was still faster than an "interpreter-language", where code is
compiled from high level language, instead of from byte-code each time it was used.
Bytecode also known as p-code (portable code), is a term which has been used to denote various
forms of instruction sets designed for efficient execution by a software interpreter as well as
being suitable for further compilation into machine code.
Execution
A bytecode program may be executed by parsing and directly executing the instructions, one at a
time. This kind of bytecode interpreter is very portable. Some systems, called dynamic
translators, or "just-in-time" (JIT) compilers, translate bytecode into machine language as
necessary at runtime: this makes the virtual machine unportable, but doesn't lose the portability
of the bytecode itself. For example, Java and Smalltalk code is typically stored in bytecoded
format, which is typically then JIT compiled to translate the bytecode to machine code before
execution.
Unit 2: Data types, Tokens in java
Java Tokens
The tokens of a language are the basic building blocks which can be put together to construct
programs. A token can be a reserved word (such as int or while), an identifier (such
as b or sum), a constant (such as 25 or "1.33"), a delimiter (such as { or ;) or an operator (such
as + or =).
For example, consider the following portion of the program –
public class PrintSum
{
public static void main(String[] args)
{
int a, b, sum;
a = 14;
b = 25;
sum = a + b;
}
}
public - reserved word
class - reserved word
PrintSum - user identifier
{ - left brace, delimiter
public - reserved word
static - reserved word
void - reserved word
main - user identifier
( - left parenthesis, delimiter
String - class name identifier
[ - left square bracket, delimiter
] - right square bracket, delimiter
args - user identifier
) - right parenthesis, delimiter
{ - left brace, delimiter
int - reserved word
a - user identifier
, - comma, delimiter
b - user identifier
, - comma, delimiter
sum - user identifier
; - semicolon, delimiter
a - user identifier
= - equals sign, operator
14 – constant
; - semicolon, delimiter
Java Data Types
Java programming language is a language in which all the variables must be declared first and
then to be used. That means to specify the name and the type of the variable. This specifies that
Java is a strongly-typed programming language. Like
int num = 1;
This shows that there exists a field named ' num' that holds a data as a numerical value '1'. The
values contained by the variables determines its data type and to perform the operations on it.
There are seven more primitive data types which are supported by Java language programming
in addition to int. A primitive data type is a data type which is predefined in Java. Following are
the eight primitive data types:
int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to
2,147,483,647. This data type is used for integer values. However for wider range of values
use long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127
(inclusive). We can save memory in large arrays using byte. We can also use byte instead of int
to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to
32,767. Short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range
of values.
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float
(instead of double) to save memory in large arrays. We do not use this data type for the exact
values such as currency. For that we have to use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data
type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data type for
conditional statements. True and false are not the same as True and False. They are defined
constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not same as ints, shorts etc.
The following table shows the default values for the data types:
Keyword
Description
Size/Format
Byte
Byte-length
integer
8-bit two's
complement
short
Short integer
16-bit two's
complement
Int
Integer
32-bit two's
complement
long
Long integer
64-bit two's
complement
Float
Single-precision
floating point
32-bit IEEE
double
Double-precision
floating point
64-bit IEEE
char
A single
character
16-bit Unicode
character
boolean
A boolean value
(true or false)
true or false
When we declare a field it is not always essential that we initialize it too. The compiler sets a
default value to the fields which are not initialized which might be zero or null.
Casting (Type Conversion)
It is sometimes necessary to convert a data item of one type to another type. Conversion of data
from one type to another type is known as type casting. In java one object reference can be type
cast into another object reference. This casting may be of its own type or to one of its subclass
or superclass types or interfaces. Some compile time or runtime type casting rules are there in
java. Some circumstances require automatic type conversion, while in other cases it must be
"forced" manually (explicitly).
Why it is required?
Because, sometimes data is in a form that is unrecognizable to the program. Example:
int a = 2;
int b = 3;
double c = a / b;
We cast c as a double. If it was not, then the data would not have a decimal value.
Automatic Conversion
Java performs automatic type conversion when the type of the expression on the right hand side
of an assignment operator safely promotes to the type of the variable on the left hand side of the
assignment operator. Thus we can safely assign: byte -> short -> int -> long -> float -> double.
Symbol (->) used here interprets to "to a".
Example// 64 bit long integer
long myLongInteger;
// 32 bit standard integer
int myInteger;
myLongInteger = myInteger;
In the above example, extra storage associated with the long integer, simply results in padding with extra zeros.
The Narrowing Conversion
The narrowing conversion occurs from a type to a different type that has a smaller size, such as from a long (64 b
to an int (32 bits).
In general, the narrowing primitive conversion can occur in these cases:
1. short to byte or char
2. char to byte or short
3. int to byte, short, or char
4. long to byte, short, or char
5. float to byte, short, char, int, or long
6. double to byte, short, char, int, long, or float
1. The narrowing primitive conversion must be explicit.
2. You need to specify the target type in parentheses.
Example
public class mainclass
{
public static void main(String [ ] args)
{
long a=10;
int b=(int)a;
//narrowing conversion
System.out.printIn(a);
System.out.printIn(b);
}
}
Narrowing conversion with information loss
Narrowing conversion may incur information loss, if the converted value is larger than the capacity of the target
In the following conversion, there is some information loss because 9876543210L is too big for an int.
public class MainClass {
public static void main(String[] args) {
long a = 9876543210L;
int b = (int) a;
System.out.println(b);
}
}
Output
1286608618
An automatic type conversion
An automatic type conversion will take place if the following two conditions are met:
1. The two types are compatible.
2. The destination type is larger than the source type.
Variables
As you learned in the previous lesson, an object stores its state in fields.
int cadence = 0;
int speed = 0;
int gear = 1;
The What Is an Object? discussion introduced you to fields, but you probably have still a few
questions, such as: What are the rules and conventions for naming a field? Besidesint, what other
data types are there? Do fields have to be initialized when they are declared? Are fields assigned
a default value if they are not explicitly initialized? We'll explore the answers to such questions
in this lesson, but before we do, there are a few technical distinctions you must first become
aware of. In the Java programming language, the terms "field" and "variable" are both used; this
is a common source of confusion among new developers, since both often seem to refer to the
same thing.
The Java programming language defines the following kinds of variables:




Instance Variables (Non-Static Fields) Technically speaking, objects store their
individual states in "non-static fields", that is, fields declared without the statickeyword.
Non-static fields are also known as instance variables because their values are unique to
each instance of a class (to each object, in other words); thecurrentSpeed of one bicycle is
independent from the currentSpeed of another.
Class Variables (Static Fields) A class variable is any field declared with
the static modifier; this tells the compiler that there is exactly one copy of this variable in
existence, regardless of how many times the class has been instantiated. A field defining
the number of gears for a particular kind of bicycle could be marked as staticsince
conceptually the same number of gears will apply to all instances. The code static int
numGears = 6; would create such a static field. Additionally, the keyword final could be
added to indicate that the number of gears will never change.
Local Variables Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0;). There is no special keyword
designating a variable as local; that determination comes entirely from the location in
which the variable is declared — which is between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class.
Parameters You've already seen examples of parameters, both in the Bicycle class and in
the main method of the "Hello World!" application. Recall that the signature for
the main method is public static void main(String[] args). Here, the args variable is the
parameter to this method. The important thing to remember is that parameters are always
classified as "variables" not "fields". This applies to other parameter-accepting constructs
as well (such as constructors and exception handlers) that you'll learn about later in the
tutorial.
Having said that, the remainder of this tutorial uses the following general guidelines when
discussing fields and variables. If we are talking about "fields in general" (excluding local
variables and parameters), we may simply say "fields". If the discussion applies to "all of the
above", we may simply say "variables". If the context calls for a distinction, we will use specific
terms (static field, local variables, etc.) as appropriate. You may also occasionally see the term
"member" used as well. A type's fields, methods, and nested types are collectively called
its members.
Naming
Every programming language has its own set of rules and conventions for the kinds of names
that you're allowed to use, and the Java programming language is no different. The rules and
conventions for naming your variables can be summarized as follows:

Variable names are case-sensitive. A variable's name can be any legal identifier — an
unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar
sign "$", or the underscore character "_". The convention, however, is to always begin
your variable names with a letter, not "$" or "_". Additionally, the dollar sign character,


by convention, is never used at all. You may find some situations where auto-generated
names will contain the dollar sign, but your variable names should always avoid using it.
A similar convention exists for the underscore character; while it's technically legal to
begin your variable's name with "_", this practice is discouraged. White space is not
permitted.
Subsequent characters may be letters, digits, dollar signs, or underscore characters.
Conventions (and common sense) apply to this rule as well. When choosing a name for
your variables, use full words instead of cryptic abbreviations. Doing so will make your
code easier to read and understand. In many cases it will also make your code selfdocumenting; fields named cadence, speed, and gear, for example, are much more
intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name
you choose must not be a keyword or reserved word.
If the name you choose consists of only one word, spell that word in all lowercase letters.
If it consists of more than one word, capitalize the first letter of each subsequent word.
The names gearRatio and currentGear are prime examples of this convention. If your
variable stores a constant value, such as static final int NUM_GEARS = 6, the
convention changes slightly, capitalizing every letter and separating subsequent words
with the underscore character. By convention, the underscore character is never used
elsewhere.
Constants: Constants are declared using the final keyword. The values of the constant can't be
changed once its declared.
Declarationfinal int hours = 24;
Now if we try to change the value of hoursfinal int hours = 24;
hours = 36;
we will get the following error from the compiler:
cannot assign a value to final variable hours
Define a constant value and use it
1. Using the final keyword to declare a variable.
2. The final keyword specifies that the value of a variable is final and cannot be changed.
3. It is a convention in Java to write constants in uppercase letters.
public class MainClass {
public static void main(String[] arg) {
final int FEET_PER_YARD = 3;
// Constant values
final double MM_PER_INCH = 25.4;
// that cannot be changed
System.out.println(FEET_PER_YARD);
System.out.println(MM_PER_INCH);
}
}
Output
3
25.4
Unit 3: Java Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Examples
Operator Description
Example
+
Addition - Adds values on either side of
the operator
A + B will give 30
-
Subtraction - Subtracts right hand
operand from left hand operand
A - B will give -10
*
Multiplication - Multiplies values on
either side of the operator
A * B will give 200
/
Division - Divides left hand operand by
right hand operand
B / A will give 2
%
Modulus - Divides left hand operand by
B % A will give 0
right hand operand and returns remainder
++
Increment - Increase the value of operand B++ gives 21
by 1
--
Decrement - Decrease the value of
operand by 1
B-- gives 19
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
Examples
Operator Description
Example
==
Checks if the value of two operands are
equal or not, if yes then condition
becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are
equal or not, if values are not equal then
condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is
greater than the value of right operand, if
(A > B) is not true.
yes then condition becomes true.
<
Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes then
condition becomes true.
>=
Checks if the value of left operand is
greater than or equal to the value of right
operand, if yes then condition becomes
true.
<=
Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right operand,
if yes then condition becomes true.
(A >= B) is not true.
The Bitwise Operators:
Java defines several bitwise operators which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
----------------a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Examples
Operator Description
Example
&
Binary AND Operator copies a bit to the
result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
|
Binary OR Operator copies a bit if it exists (A | B) will give 61 which is 0011 1101
in eather operand.
^
Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is 0011 0001
set in one operand but not both.
~
Binary Ones Complement Operator is
unary and has the efect of 'flipping' bits.
(~A ) will give -60 which is 1100 0011
<<
Binary Left Shift Operator. The left
operands value is moved left by the
number of bits specified by the right
operand.
A << 2 will give 240 which is 1111 0000
>>
Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.
A >> 2 will give 15 which is 1111
>>>
Shift right zero fill operator. The left
operands value is moved right by the
number of bits specified by the right
operand and shifted values are filled up
with zeros.
A >>>2 will give 15 which is 0000 1111
The Logical Operators:
The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Examples
Operator Description
Example
&&
Called Logical AND operator. If both the (A && B) is false.
operands are non zero then then condition
becomes true.
||
Called Logical OR Operator. If any of the (A || B) is true.
two operands are non zero then then
condition becomes true.
!
Called Logical NOT Operator. Use to
reverses the logical state of its operand. If
a condition is true then Logical NOT
operator will make false.
!(A && B) is true.
The Assignment Operators:
There are following assignment operators supported by Java language:
Examples
Operator Description
Example
=
Simple assignment operator, Assigns C = A + B will assigne value of A + B into C
values from right side operands to
left side operand
+=
Add AND assignment operator, It
C += A is equivalent to C = C + A
adds right operand to the left operand
and assign the result to left operand
-=
Subtract AND assignment operator,
It subtracts right operand from the
left operand and assign the result to
left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator,
It multiplies right operand with the
left operand and assign the result to
left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator,
C %= A is equivalent to C = C % A
It takes modulus using two operands
and assign the result to left operand
<<=
Left shift AND assignment operator
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment operator
^=
bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2
operator
|=
bitwise inclusive OR and assignment C |= 2 is same as C = C | 2
operator
C &= 2 is same as C = C & 2
Misc Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as :
variable x = (expression) ? value if true : value if false
Example:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
This would produce following result:
Value of b is : 30
Value of b is : 20
instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type (class type or interface type). instanceOf operator is wriiten as:
( Object reference variable ) instanceOf (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side then the result will be true. Following is the example:
String name = = 'James';
boolean result = s instanceOf String;
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with
the type on the right.
Example:
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
This would produce following result:
true
Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category
Operator
Associativity
Postfix
() [] . (dot operator)
Left to right
Unary
++ - - ! ~
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
>> >>> <<
Left to right
Relational
> >= < <=
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
^
Left to right
Bitwise OR
|
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *= /= %=>> = <<= &= ^= |=
Right to left
Comma
,
Left to right
Unit 4: Control Statement in Java
Loops or iteration
There may be a situation when we need to execute a block of code several number of times, and
is often referred to as a loop.
Java has very flexible three looping mechanisms:
 while Loop
 do...while Loop
 for Loop
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example:
public class Test
{
public static void main(String args[])
{
int x= 10;
while( x < 20 )
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
Syntax:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test
{
public static void main(String args[])
{
int x= 10;
do
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
for(initialization; Boolean_expression; update)
{
//Statements
}
Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next statement past
the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
Example:
public class Test
{
public static void main(String args[])
{
for(int x = 10; x < 20; x = x+1)
{
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Enhanced for loop in Java:
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
for(declaration : expression)
{
//Statements
}
Declaration : The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
Expression : This evaluate to the array you need to loop through. The expression can be an array
variable or method call that returns an array.
Example:
public class Test
{
public static void main(String args[])
{
int [ ] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [ ] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names )
{
System.out.print( name );
System.out.print(",");
}
}
}
Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line
of code after the block.
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output
10
20
40
50
Java Decision Making
There are two types of decision making statements in Java. They are:
 if statements
 switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
public class Test
{
public static void main(String args[])
{
int x = 10;
if( x < 20 )
{
System.out.print("This is if statement");
}
}
}
Output
This is if statement
The if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
else
{
//Executes when the Boolean expression is false
}
Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
if( x < 20 )
{
System.out.print("This is if statement");
}
else
{
System.out.print("This is else statement");
}
}
}
Output
This is else statement
The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if, else if, else statements there are few points to keep in mind.



An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
if( x == 10 )
{
System.out.print("Value of X is 10");
}
else if( x == 20 )
{
System.out.print("Value of X is 20");
}
else if( x == 30 )
{
System.out.print("Value of X is 30");
}
else
{
System.out.print("This is else statement");
}
}
}
Output
Value of X is 30
Nested if...else Statement:
It is always legal to nest if-else statements, which means you can use one if or else if statement
inside another if or else if statement.
Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
Note:You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
Output
X = 30 and Y = 10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:





The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch, and it must
be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.


Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example:
public class Test
{
public static void main(String args[])
{
char grade = args[0].charAt(0);
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
break;
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Output
$ java Test a
Invalid grade
Your grade is a a
$ java Test A
Excellent!
Your grade is a A
$ java Test C
Well done
Your grade is a C
$
Arrays
An array is a group of variables of the same data type and referred to by a common name. An
array is contiguous block of memory locations referred by a common name.
Array is the static memory allocation. It allocates the memory for the same data type in
sequence.
types of arrays –
one - dimensional, two - dimensional or can say multi - dimensional.
An array is a container object that holds a fixed number of values of a single type. The length of
an array is established when the array is created. After creation, its length is fixed.
An array of ten elements
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the above illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
Syntax
dataType[] variableName;

you can read the [] as the word "array"
To declare a variable for an array of integers:
int[] nums;

which you can read as "int array nums"
To declare a variable for an array of String objects:
String[] names;

which you can read as "String array names" - the array holds String references
You may also put the brackets after the variable name (as in C/C++), but that is less clearly
related to how Java actually works
int nums[]; // not recommended, but legal
Exampleint num[]; or int num = new int[2]; or int [] num;
Allocating Memory to Arrays
The new operator is used to allocate memory to an array.
Syntax to allocate memory
array_name = new type[size];
For e.g.
designations = new String[10]; //size of the array is 10.
Another exampleint[] moreNums;
int size = 7;
moreNums = new int[size];

you can declare and instantiate all at once
String[] names = new String[3];

the elements of the array, String references, are initialized to null
As objects, arrays also have a useful property: length
 in the above example, names.length would be 3
 the property is fixed (i.e., it is read-only)
You can reassign a new array to an existing variable
int[] nums;
nums = new int[10];
nums = new int[20];

the original ten-element array is no longer referenced by nums, since it now points
to the new, larger array
Initializing Arrays
An array can be initialized when it is created

the notation looks like this:
String[] names = { "Joe", "Jane", "Herkimer" };
or
String[] names = new String[] {"Joe", "Jane", "Herkimer" };

this automatically creates an array of length 3, because there were 3 items
supplied
int[] nums = new int[] { 2, 4, 6, 8, 10, 12 };
 this array will have a length of 6
If a new array is being assigned to an existing variable, you cannot use the shorter variant, you
must use the newkeyword and the data type:
String[] names;
names = new String[] {"Joe", "Jane", "Herkimer" };
Working With Arrays
Array elements are accessed through the array reference, by their array index


the index is the element number, placed within brackets
elements are numbered from 0 to one less than the specified size
String[] names = new String[3];

the valid elements are 0, 1, and 2, as in
names[0] = "Sam";
names[1] = "Sue";
names[2] = "Mary";

you could access array elements in a for loop with:
for (int i = 0; i < 3; i++) System.out.println(names[i]);

or, better programming practice would be to use the length property:
for (int i = 0; i < names.length; i++) System.out.println(names[i]);
The compiler does no checking to ensure that you stay within the bounds of the array

but the JVM does check at runtime - if you try to exceed the bounds of the array,
an exception will occur
Note that a zero-length array is valid:
Book[] titles = new Book[] { };
Book[] moreTitles = new Book[0];

you might create a zero-length array as the return value from a method typed as
returning an array, when there are no items to return (as opposed to returning null)
another exampleimport java.util.*;
public class array{
public static void main(String[] args){
int num[] = {50,20,45,82,25,63};
int l = num.length;
int i,j,t;
System.out.print("Given number : ");
for (i = 0;i < l;i++ ){
System.out.print(" " + num[i]);
}
System.out.println("\n");
System.out.print("Accending order number : ");
Arrays.sort(num);
for(i = 0;i < l;i++){
System.out.print(" " + num[i]);
}
}
}
Output of the program:
C:\chandan>javac array.java
C:\chandan>java array
Given number : 50 20 45 82 25 63
Ascending order number : 20 25 45 50 63 82
In this program the sort() function of the java.util.*; package is using to sort all the numbers
present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascending
order by default. This function held the argument which is the array name num.
Two-dimensional Arrays
In additions to one-dimensional arrays, you can create two-dimensional arrays. To declare twodimensional arrays, you need to specify multiple square brackets after the array name.
Syntax to declare a two dimensional array
type array_name = new type[rows][cols];
For e.g.
int multidim[] = new int[3][];
In a two-dimensional array,
1. You need to allocate memory for only the first dimension.
2. You can allocate the remaining dimensions separately.
3. When you allocate memory to the second dimension, you can also allocate different
number to each dimension.
For e.g.
int multidim[] = new int[3][];
multidim[0] = new int[1];
multidim[1] = new int[4];
Why array is needed?
You might come across a situation where you need to store similar type of values for a large
number of data items.
For e.g.
To store the marks of all the students of a university, you need to declare thousands of variables.
In addition, each variable name needs to be unique. To avoid such situations, you can use arrays.
An array consists of a name and the number of elements of the array. You can refer to a specific
array element by the array name and the element number, which is known as the index number.
Note: - Array index element number always starts with 0(zero).
Advantages of using Arrays
You can refer to a large number of elements by just specifying the index number and the
array name.
Arrays make it easy to do calculations in a loop.
Simple Java Application using Arrays
import java.io.*;
class student
{
int regno,total;
int mark[];
String name;
public student(int r,String n,int m[])
{
regno=r;
name=n;
mark=new int[3]; //new operator is used to allocate memory to an array.
for(int i=0;i<3;i++)
{
mark[i]=m[i];
if(mark[i]>50)
total+=mark[i];
else
{
total=0;
break;
}
}
}
public void displaystudent()
{
System.out.println("NAME:"+name);
System.out.println("REGNO:"+regno);
System.out.println("TOTAL:"+total);
}
}
class secondsample
{
public static void main(String args[])
{
int mk1[]={73,85,95}; // declare and initialize arrays in the same statement.
int mk2[]={71,85,95};
student st[]=new student[2];
st[0]=new student(1,"Ganguly",mk1);
st[1]=new student(2,"Sachin",mk2);
for(int i=0;i<2;i++)
st[i].displaystudent();
}
}
Output
javac secondsample.java
java secondsample
NAME:Ganguly
REGNO:1
TOTAL:253
NAME:Sachin
REGNO:2
TOTAL:251
Unit 5: Object Oriented Programming In Java
Class
A class is a user-define data type with a template for creating different objects which defines its
properties and behaviors. Java class objects exhibit the properties and behaviors defined by its
class. A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object. Java fields and
member functions names are case sensitive. Methods define the operations that can be performed
in java programming.
Syntax of class
class classname [extend superclassname]
{
[variable declaration;]
[method declaration;]
}
Everything inside the square brackets is optional. This means that the following would be a valid
class definition:
class empty
{
}
Because the body is empty, this class does not contain any properties and therefore cannot do
anything. We can compile it and even create objects using it.
The keyword extends indicates that the properties of the superclassname class are extended to
the classname class. This concept is known as inheritance.
Adding variables
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variables because they are created whenever an object of the
class is instantiated. We can declare the instance variable exactly the same way as we declare
local variables.
Exampleclass rectangle
{
int length;
int width;
}
The class rectangle contains two integer type instance variables. It is allowed to declare in one
line as
int length, width;
Note- These variables are only declared and therefore no storage space has been created in the
memory. Instance variable are also known as member variables.
Adding methods
Methods are declared inside the body of the class but immediately after the declaration of
instance variables.
Syntax
type methodname (parameter_list)
{
method-body;
}
Method declarations have four basic parts:
 The name of the method (methodname)
 The type of the value the method returns (type)
 A list of parameters (parameter-list)
 The body of the method
Method Name: This is the actual name of the method. The method name and the parameter list
together constitute the method signature.
Return Type: A method may return a value. The return value type is the data type of the value
the method returns. Some methods perform the desired operations without returning a value. In
this case, the return value type is the keyword void.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers
to the type, order, and number of the parameters of a method. Parameters are optional, that is, a
method may contain no parameters.
Method Body: The method body contains a collection of statements that define what the method
does.
Creating a class
Class name
class rectangle
{
Instance or data members
int len,width;
void getdata(int x, int y)
{
Method
len=x;
width=y;
}
}
Instance variable and methods in classes are accessible by all the methods in the class but a
method cannot access the variables declared in other methods.
class access
{
int x;
void one()
{
int y;
x=10;
y=x;
//legal
//legal
}
void two()
{
int z;
x=5;
z=12;
y=1;
}
//legal
//legal
//illegal
}
Creating objects
An object in java is essentially a block of memory that contains space to store all the instance
variables. Creating an object is also referred to as instantiating an object.
Objects in java are created using the new operator. The new operator creates an object of
specified class and returns a reference to that object.
Creating object
Rectangle rect;
//declare
Rect=new Rectangle( );
//instantiate
The first statement declares a variable to hold the object reference and the second one actually
assign the object reference to the variable.
Accessing class members
We cannot access the instance variables and the methods directly. To do this, we must use the
concerned object and the dot operators as shown below:
Objectname.variable name=value
Method1rect1.len=25;
rect1.width=10;
rect2.len=15;
rect2.width=12;
Note that the two objects rect1 and rect2 store different values as shown below:
rect1
rect2
rect1.len
25
rect2.len
15
rect1.width
10
rect2.width
12
Method2-Another way of assigning values to the instance variable is to use a method that is
declared inside the class.
Rectangle rect=new Rectangle( );
Rect1.getdata(25,10);
This method getdata will pass the values 25 and 10 to the x and y parameters then this method
assign these values to len and width variable respectively.
void getdata(int x, int y)
{
len=x;
width=y;
}
Example1- Using class and object
class number
{
int num=20;
void prn( )
{
System.out.println(“Value of num is ”+num);
}
}
class numb
{
public static void main(String args[ ])
{
number n=new number();
n.prn();
}
}
Output
Value of num is 20
Example 2- Assigning values outside class
class rectangle
{
int len, width;
void prn( )
{
System.out.println(“Area of rectangle= ”+len*width);
}
}
class rect
{
public static void main(String args[ ])
{
rectangle rect1=new rectangle();
rect1.len=25;
rect1.width=10;
rect1.prn();
}
}
Output
Area of rectangle=250
Example 3- Passing parameters
class rectangle
{
int len, width;
void getdata(int x, int y)
{
len=x;
width=y;
}
void prn( )
{
System.out.println(“Area of rectangle= ”+len*width);
}
}
class rect
{
public static void main(String args[ ])
{
rectangle rect1=new rectangle();
rect1.getdata(25,10);
}
}
Output
Area of rectangle=250
Example 4- Use of return keyword
class rectangle
{
int len, width;
void getdata(int x, int y)
{
len=x;
width=y;
}
void output( )
{
int area;
area=len*width;
return area;
}
}
class rect
{
public static void main(String args[ ])
{
int area1,area2;
rectangle rect1=new rectangle();
rectangle rect2=new rectangle();
rect1.len=25;
rect1.width=10;
area1= rect1.len* rect1.width;
rect2.getdata(15,10);
area2=rect2.output();
System.out.println(“Area1= ”+area1);
System.out.println(“Area2= ”+area2);
}
}
Output
Area1=250
Area2=150
Method overloading (Function overloading)
In java it is possible to create methods that have the same name, but different parameter lists and
different definitions. This is called method overloading. Method overloading is used when
objects are required to perform similar tasks but using different input parameters. When we call a
method in an object, java matches up the method name first and then the number and type of
parameters to decide which one of the definitions to execute. This process is known as
polymorphism.
Note: Each parameter list should be unique.
The method’s return type does not play any role in this.
class OverloadDemo
{
void test( )
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}
Output
No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test (123.2): 15178.24
Constructor
A java constructor has the same name as the name of the class to which it belongs. Constructor
are declared just like as we declare methods. Constructors are used to assign initial values to
instance variables of the class. A default constructor with no arguments will be called
automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator.
Characteristics of constructor


They are called only once when the class is being instantiated.
They must have the same name as the class itself.
They do not return a value and you do not have to specify the keyword void.
Exampleclass Demo
{
int value1;
int value2;
Demo( )
//Defining constructor
{
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display( )
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
}
class democons
{
public static void main(String args[])
{
Demo d1 = new Demo( );
//calling constructor
d1.display();
}
}
Constructor overloading(using multiple constructor)
Constructor overloading is a technique in java in which a class can have any number of
constructors which differ in types of parameters list. Constructor can be overloaded they should
have different arguments because JVM differentiates constructors on the basis of arguments
passed in the constructor. A default constructor with no arguments will be called automatically
by the Java Virtual Machine (JVM).
Examples of valid constructors for class Account are
Account(int a);
Account (int a, int b);
Account (String a, int b);
class Demo
{
int value1;
int value2;
Demo( )
// constructor 1
{
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}
Demo(int a)
// constructor 2
{
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a, int b)
// constructor 3
{
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display( )
{
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
}
class overcons
{
public static void main(String args[])
{
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Another exampleclass Room
{
double length, breadth, height;
Room(double l, double b, double h) // constructor 1
{
length=l;
breadth=b;
height=h;
}
Room( )
// constructor 2
{
length=-1;
breadth=-1;
height=-1;
}
Room(double len)
// constructor 3
{
length=breadth=height=len;
}
double volume( )
{
return length*breadth*height;
}
}
class OverloadCons
{
public static void main(String args[])
{
Room a=new Room(20,30,40);
Room b=new Room();
Room c=new Room(10);
double vol;
vol=a.volume( );
System.out.println("Volume of room a is " + vol);
vol=b.volume ( );
System.out.println("Volume of room b is " + vol);
vol=c.volume( );
System.out.println("Volume of room c is " + vol);
}
Static Members
Member that is common to all the objects and accessed without using a particular object. That is,
the member belongs to the class as a whole rather than the objects created from the class. Such
members can be defined as follows:
Static int count;
Static in prn(int m, int n);
The members that are declared static as shown above are called static members. Since these
members are associated with the class itself rather than individual objects, the static variables
and static methods are often referred to as class variable and class methods.
Why do we need Static members?
Static variable are used when we want to have a variable common to all instances of a class. One
of the most common example is to have a variable that could keep a count of how many objects
of a class have been created. Java creates only one copy for a static variable which can be used
even if the class is never actually instantiated.
Note- Static variables and static methods can be called without using the objects.
Example- Use of static variable
class Animal
{
static int animalCount=0;
public Animal()
{
animalCount+=1;
}
public static int getCount()
{
return animalCount;
}
}
class TestAnimal
{
public static void main(String[] args)
{
Animal a1=new Animal();
Animal a2=new Animal();
Animal a3=new Animal();
System.out.println(“The Number of Animals are: “+ Animal.getCount( ));
}
}
Output
The Number of Animals are: 3
Example- Use of static method
class StaticMethod
{
static int j = 0;
static void getVariable( )
{
j++;
System.out.println("Value of static variable j is"+j);
}
}
class TestStatic
{
public static void main(String args[])
{
StaticMethod.getVariable( );
}
}
Output:
Value of static variable j is 1
Unit 6: Inheritance & Multithreading in Java
Inheritance
Inheritance is the capability of a class to use the properties and methods of another class while
adding its own functionality. The old class is known as “base” class, “super” class or “parent”
class and the new class is known as “sub” class, “derived” class, or “child” class.
Parent
Child
The concept of inheritance greatly enhances the ability to reuse code as well as making design a
much simpler and cleaner process.
Inheritance in Java
Java uses the extends keyword to set the relationship between a parent class and a child class.
For example-A class box, the box has length, width and height properties as well as methods for
setting dimensions and displaying its volume.
public class Box
{
private int length, width, height;
public void setLength(int p)
{
length=p;
}
public void setWidth(int p)
{
width=p;
}
public void setHeight(int p)
{
height=p;
}
public void showVolume()
{
System.out.println(length*width*height);
}
}
To inherit the Box class –
public class GraphicsBox extends Box
The GraphicsBox class assumes or inherits all the properties of the Box class and can now add
its own properties and methods as well as override existing methods.
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super
class. It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by
the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B
is the subclass that also contains its own data members named a and b. then we can access the
super class (class A) variables a and b inside the subclass class B just by calling the following
command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to
handle situations where the local members of a subclass hides the members of a super class
having the same name. The following example clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){
B subobj = new B(1, 5);
subobj.Show();
}
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Types of Inheritance
There are 4 types of inheritance
1. Single inheritance or Simple inheritance(only one super class)
2. Multilevel inheritance (Derived from a derived class)
3. Multiple inheritance (Several super class)
4. Hierarchical inheritance (one super class, many subclasses)
A
A
A
B
B
B
C
C
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
A
B
C
D
Hierarchical Inheritance
Simple Inheritance-When a subclass is derived simply from it's parent class then this
mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class
and it's parent class. It is also called single inheritance or one level inheritance.
Exampleclass A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Output
Multilevel Inheritance
When a subclass is derived from a derived class then this mechanism is known as the multilevel
inheritance. The derived class is called the subclass or child class for it's parent class and this
parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can
go up to any number of level.
Exampleclass A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}
Output
Multiple Inheritance
In multiple inheritance, one class extends multiple classes. Java does not support multiple
inheritance but C++ supports.
Example
calss Aves { }
class Bird { }
public class Parrot extends Aves, Bird { }
In the above code, Parrot extends both Aves and Bird. This is not supported by Java and the above
code raises compilation error. Following is the schematic representation.
Note: Java supports multiple inheritance partially through interfaces.
Hierarchical Inheritance
In hierarchical type of inheritance, one class is extended by many subclasses. It is one-tomany relationship.
Example
class Aves
{
public void fly()
{
System.out.println("Generally, aves fly");
}
}
class Parrot extends Aves
{
public void eat()
{
System.out.println("Parrot eats fruits and seeds");
}
}
class Vulture extends Aves
{
public void vision()
{
System.out.println("Vulture can see from high altitudes");
}
}
public class FlyingCreatures
{
public static void main(String args[])
{
// all the following code is composition for FlyingCreatures
Parrot p1 = new Parrot();
p1.eat();
// calling its own member
p1.fly();
// calling super class member by inheritance
Vulture v1 = new Vulture();
v1.vision();
// calling its own member
v1.fly();
// calling super class member by inheritance
}
}
Output
Parrot eats fruits and seeds
Generally, aves fly
Vulture can see from high altitudes
Generally, aves fly
Overriding method
Overriding means creating a new set of method statements for the same method signature (name,
number of parameters and parameter types).
When extending a class constructor you can reuse the superclass constructor and overridden
superclass methods by using the reserved word super. Note that this reference must come first in
the subclass constructor. The reserved word this is used to distinguish between the object's
property and the passed in parameter.
Example
class super
{
int x;
super(int x)
{
This.x=x;
}
void display( )
{
System.out.println(“Super x=”+x);
}
}
class sub extends super
{
int y;
sub(int x int y)
{
super(x);
this.y=y;
}
void display( )
{
System.out.println(“Super x=”+x);
System.out.println(“Sub y=”+y);
}
}
class override
{
public static void main(Stribg args[])
{
sub s1=new sub(100,200);
s1.display();
}
}
Final variable and methods
If we wish to prevent the subclasses from overriding the members of the superclass, we can
declare them as final using the keyword final as a modifier. Example:
final int SIZE=100;
final void show()
{
……..
}
A method final ensure that the functionality in this method will never be altered in any way. The
value of a final variable can never be changed. Final variables behave like class variable and they
do not take any space on individual objects of the class.
// super class final method sub class non-final method
package oops;
class Superclass
{
final void m1()
{
System.out.println("Super class method");
}
}
public class Subclass extends Superclass {
void m1() // compile time error
//can not overide the final method from superclass
{
System.out.println("Sub class method");
}
public static void main(String[] args) {
Subclass s=new Subclass();
s.m1();
}
}
// super class non-final method, sub class final method
package oops;
class Superclass
{
void m1()
{
System.out.println("Super class method");
}
}
public class Subclass extends Superclass {
final void m1() //no error
{
System.out.println("Sub class method");
}
public static void main(String[] args) {
Subclass s=new Subclass();
s.m1(); // sub class
}
}
Final classes
A class that cannot be subclassed is called a final class. This is achieved by using keyword final.
public final class student
final class bclass extends other {….}
any attempt to inherit these classes will cause an error and the compiler will not allow it.
Abstract method and classes
An abstract class is a class that is declared by using the abstract keyword. It may or may not
have abstract methods. We cannot use abstract classes to instantiate objects directly. An abstract
class can be extended into sub-classes, these sub-classes usually provide implementations for all
of the abstract methods.
The key idea with an abstract class is useful when there is common functionality that's like to
implement in a superclass and some behavior is unique to specific classes. So you implement the
superclass as an abstract class and define methods that have common subclasses. Then you
implement each subclass by extending the abstract class and add the methods unique to the class.
Points of abstract class :
1.
2.
3.
4.
Abstract class contains abstract methods.
Program can't instantiate an abstract class.
Abstract classes contain mixture of non-abstract and abstract methods.
If any class contains abstract methods then it must implements all the abstract methods of
the abstract class.
Exampleabstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B( );
b.callme( );
b.callmetoo( );
}
}
Example2abstract class ract
{
public void prn()
{
System.out.println("From abstract class");
}
abstract void printme( ) // abstract method has no body
}
class test extends ract
{
public void printme()
{
System.out.println("Implementing abstract class");
}
public static void main(String arg[])
{
test t1=new test();
t1.prn( );
t1.printme( );
}
}
Output
From abstract class
Implementing abstract class
Access Specifiers or visibility controls
An access specifier controls the access of class members and variables by other objects. The
various types of access specifiers in Java are:
1.
2.
3.
4.
public
private
protected
friendly or package
The public Access Specifier
Class members with public specifier can be accessed anywhere in the same class. The public
keyword is used to declare a member as public. The following statement shows how to declare a
data member of a class as public:
public int num ;
public vois sum( )
public class Account
The private Access Specifier
A data member of class declared as private is accessible at the class level only in which it is
defined. You can use the private access specifier to declare members that should be available to
the class within which they are declared. The private keyword is used to declare a member as
private.
In Java, you implement the concept of encapsulation by using the private keyword. The
following syntax shows how to declare a data member of a class as private:
private int accountno ;
private methodName( );
The protected Access Specifier
The variables and methods that are declared protected are accessible only to the subclasses of the
class in which they are declared. The protected keyword is used to declare a member as
protected. The following statement shows how to declare a member as protected:
protected String date;
protected void showData( )
The friendly or package Access Specifier
If you do not specify any access specifier, the scope of data members and methods is friendly.
Java provides a large number of classes, which are organized into groups in a package. A class,
variable, or method that has friendly access is accessible only to the classes of a package.
Int pageNumbers; //The default friendly access is provided to the data memners
void showdata( )
In Java, friendly is not a keyword. It is a term that is used for the access level when no access
specifier has been specified. You cannot declare a class, variable, or method with the friendly
specifier.
Difference between public and friendly
Difference between the “public” access and the and “friendly” access is that the public modifier
makes fields visible in all classes , regardless of their packages while the friendly access makes
fields visible only in the same package, but not in other packages (a package is a group of related
classes stored separately).
Interfaces: Multiple Inheritance
Java cannot have more than one superclass. ExampleClass A extends b extends c
{
---------}
is not permitted in java. Java provides an alternate approach known as interfaces to support the
concept of multiple inheritance. A java class cannot be a subclass of more than one superclass, it
can implement more than one interface.
Defining interfaces
A interface is basically a kind of class but with a major difference. The difference is that
interfaces define only abstract methods and final fields. This means that interfaces do not specify
any code to implement these methods and data fields contain only constants. It is the
responsibility of the class that implements an interface to define the code for implementation of
these methods.
Syntaxinterface interfacename
{
variable declaration;
methods declaration;
}
Variables are declared as follows:
static final type variablename=value;
Note- All variables are declared as constants.
Methods declarations will contain only a list of methods without any body statements.
return-type methodname1(parameter_list);
Exampleinterface item
{
static final int num=500;
static final String name= “Yes”;
void display();
}
Extending interfaces
Like classes interfaces can also extended. Interface can be subinterfaced from other interfaces.
interface abc extends xyz
{
body of abc
}
ExampleInterface item
{
int code=123;
string name= “Oil”;
}
interface selectitem extends item
{
void display();
}
Note 1- The variables name and code are declared like simple variables. It is allowed because
all the variables in an interface are treated as constants although the keywords final and static
are not present.
Note 2- An interface cannot extend classes.
Implementing Interfaces
Interfaces are used as “superclasses” whose properties are inherited by classes.
Syntax
class classname implements interfacename
{
body of classname
}
A class can extend another class while implementing interfaces.
class classname extends superclass implements interface1, interface2
{
body of classname
}
Exampleinterface area
{
final static float pi=3.12f;
float compute (float x, float y);
}
class rectangle implements area
{
public float compute(float x, float y)
{
return (x*y);
}
}
class circle implements area
{
public float compute(float x, float y)
{
return (pi*x*y);
}
}
class interfacetest
{
public static void main(String args[ ])
{
rectangle rect=new rectangle( );
circle cir=new circle( );
area ar;
ar=rect;
System.out.println(“Area of Rectangle=”+ar.compute(10,20));
ar=circle;
System.out.println(“Area of Circle=”+ar.compute(10,0));
}
}
Output
Area of Rectangle=200
Area of Circle=314
Example -Program using multiple inheritance to find area of a rectangle and triangle
class dc
//base class
{
int a, l, b;
void set(int x, int y)
{
l=x;
b=y;
System.out.println("val of l="+l);
System.out.println("val of b="+b);
}
void areaOfRectangle()
{
a=l*b;
}
}
class cd extends dc
//derived class
{
int a,h,w;
void set(int x,int y)
{
super.set(x,y);
h=x;
w=y;
System.out.println("val of h="+h);
System.out.println("val of w="+w);
}
void areaOfTriangle()
{
super.areaOfRectangle();
System.out.println("area of rect="+super.a);
this.a=(h*w)/2;
System.out.println("area of triangle="+this.a);
}
}
class idemo6
{
public static void main(String[] args)
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
cd c=new cd();
c.set(x,y);
c.areaOfTriangle();
}
}
Output
Thread
Introduction to thread
A process is a self-contained running program with its own address space. A multitasking
operating system is capable of running more than one process (program) at a time. A thread is a
single sequential flow of control within a process. A single process can thus have multiple
concurrently executing threads.
There are many possible uses for multithreading, but in general, you'll have some part of your
program tied to a particular event or resource, and you don't want to hang up the rest of your
program because of that. So you create a thread associated with that event or resource and let it
run independently of the main program. A good example is a "quit" button - you don't want to be
forced to poll the quit button in every piece of code you write in your program and yet you want
the quit button to be responsive, as if you were checking it regularly. In fact, one of the most
immediately compelling reasons for multithreading is to produce a responsive user interface.
Creating a thread
Creating threads in java is simple. Threads are implemented in the form of objects that contain a
method called run( ). It makes up the entire body of a thread and is the only method in which the
thread’s behavior can be implemented.
Syntaxpublic void run( )
{
……………..
……………..
}
The run( ) method should be invoked by an object of the concerned thread. This can be achieved
by creating the thread and initiating it with the help of another thread method called start( ).
A new thread can be created in two ways:
1. By creating a thread class: Define a class that extends Thread class and override
its run ( ) method with the code required by the thread.
2. By converting a class to a thread: Define a class that implements Runnable
interface,. The runnable interface has only one method( ), run(), that is to be
defined in the method with the code to be executed by the thread.
Extending the thread class
We can make our class runnable as a thread by extending the class java.lang.Thread. This gives
us access to all the thread methods directly.
1. Declare the class as extending the thread class.
2. Implement the run( ) method that is responsible for executing the sequence of code that
the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
Declaring the class
Class Thread1 extends Thread
{……
}
Now we have a new type of thread Thread1.
Implementing the run method
The run( ) method has been inherited by the class thread1. We have to override this method in
order to implement the code to be executed by our thread. The basic implementation of run( )
will look like this:
public void run( )
{….…………..
……………….
}
When we start the new thread, java calls the thread’s run( ) method, so it is the run( ) where all
the action takes place.
Starting the new thread
To create and run an instance thread class
Thread1 athread=new thread1( );
athread.start( );
Note- that this statement just create the object. The thread that will run this object is not yet
running. The thread is in newborn state.
The start( ) method causing the thread to move into the runnable state.
Creating threads using the thread class
class A extends Thread
{
public void run( )
{
for(int i=1;i<=5;i++)
{
System.out.println(“\t From Thread A :i=”+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
for(int j=1;j<=5;j++)
{
System.out.println(“\t From Thread B :j=”+j);
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
for(int k=1;k<=5;k++)
{
System.out.println(“\t From Thread C :k=”+k);
}
System.out.println(“Exit from C”);
}
}
class threadtest
{
public static void main(String args[])
{
new A( ).start( );
new B( ).start( );
new C( ).start( );
}
}
Output
Stopping A Thread
To stop a thread from running further, we may do so by calling its stop( ) method, like:
athread.stop( );
This statement causes the thread to move to the dead state. A thread will also move to the dead
state automatically when it reaches the end of its method. The stop( ) method may be used when
the premature death of a thread is desired.
Blocking a thread
A thread can also be temporarily suspended or blocked from entering into the runnable state by
using either of the following thread methodssleep( )
//blocked for a specific time
suspend( )
// blocked until further orders
wait( )
// blocked until certain condition occurs
These methods cause the thread to go into the blocked state. The thread will return to the
runnable state when the specified time is elapsed in the case of sleep( ), the resume method is
invoked in the case of suspend method( ), and the notify method is called in the case of wait( ).
Life cycle of thread or thread model
When you are programming with threads, understanding the life cycle of thread is very valuable.
While a thread is alive, it is in one of several states. By invoking start( ) method, it doesn’t mean
that the thread has access to CPU and start executing straight away. Several factors determine
how it will proceed.
1. Newborn state – when we create a thread object, the thread is born and is said to be in
newborn state. The thread is not yet scheduled for running. At this stage we can do only
two things:
 Schedule it for running using start( ) method.
 Kill it using stop( ) method.
If scheduled, it moves to the runnable state. If we attempt to use any other method at this
stage, an exception will be thrown.
Runnable (Ready-to-run) state - A runnable state means that . A thread first entershe
thread is ready for execution and is waiting for the availability of the processor. That is, the
thread has joined the queue of threads that are waiting for execution. If all thread has equal
priority, then they are given time slots for execution in round robin fashion, i.e., first come,
first serve manner. This process of assigning time to thread is known as time-slicing. Thread
priorities are controlled by yield method( ).
yield
Running
Thread
Runnable Threads
Running state – Running means that the processor has given its time to the thread for its
execution. The thread runs until a higher priority thread doesn’t come. A running thread stops
in one of the following situation.

It has been suspended using suspend( ) method. A suspend thread can be revived by


using the resume( ) method. This approach is useful when we want to suspend a thread
for some time due to certain reasons, but do not want to kill it.
It has been made to sleep. We can put a thread to sleep for a specified time period using
the method sleep (time) where time is in milliseconds. This means that the thread is out
of the queue during this time period. The thread re-enters the runnable state as soon as
this time period is elapsed.
It has been told to wait some event occurs. This is done using the wait( ) method. The
thread can be scheduled to run again using the notify( ) method.
notify
2. Blocked - A thread to the runnable state and subsequently the running state. This happens
when the thread is suspended, sleeping, or waiting in order to satisfy certain requirement.
A blocked thread is considered “not runnable” but not dead and therefore fully qualified
to run again.
3. Dead state – Every thread has a life cycle. A running thread ends its life when it has
completed executing its run() method. We can kill it by sending the stop message to it at
any state thus causing a premature death to it. A thread can be killed as soon as it is born,
or while it is running , or even when it is in “not runnable” (blocked) condition.
Applet
Applet is java program that can be embedded into HTML pages. Java applets runs on the java
enables web browsers such as mozilla and internet explorer. Applet is designed to run remotely
on the client browser, so there are some restrictions on it. Applet can't access system resources
on the local computer. Applets are used to make the web site more dynamic and entertaining.
Advantages of Applet:






Applets are cross platform and can run on Windows, Mac OS and Linux platform
Applets can work all the version of Java Plugin
Applets runs in a sandbox, so the user does not need to trust the code, so it can work
without security approval
Applets are supported by most web browsers
Applets are cached in most web browsers, so will be quick to load when returning to a
web page
User can also have full access to the machine if user allows
Disadvantages of Java Applet:




Java plug-in is required to run applet
Java applet requires JVM so first time it takes significant startup time
If applet is not already cached in the machine, it will be downloaded from internet and
will take time
Its difficult to desing and build good user interface in applets compared to HTML
technology
Local and Remotes applet
We can embed applets into webpages in two ways. One, we can write our own applets an embed
them into webpages.
Second, we can download an applet from a remote computer system and them embed it into a
web page.
An applet developed locally and stored in a local system is known as a local applet. When a
webpage is trying to find a local applet, it does not need to use the Internet and therefore the
local system does not require any Internet connection.
A remote applet is that which is developed by someone else and stored on a remote computer
connected to Internet. In order to locate and load remote applet, we must know the applet’s
address on the web. The address is known as Uniform Resource Locator.
Applet differ from applications
There are significant difference between applets and stand alone java applications. Applets are
not full featured applications programs. They are designed for use on the internet, they impose
certain limitations and restrictions in their design.
Main method is not used in any Applet as it is not required for initiating the execution of the
code , whereas , Applets when loaded ,automatically call certain methods of Applet class to start
and execute the applet code.
Applets are run from inside a web page using a special feature known as HTML tag.
Files that are located in the local computer cannot be read or write by the applets.
Applets cannot communicate with other servers on the network.
Applets cannot run any program from the local computer.
Applets are restricted from using libraries from other language such as C or C++.
Building applet code
Java applets are like Java applications, their creation follows the same three step process of
write, compile and run. The difference is, instead of running on your desktop, they run as part of
a web page.
The goal is to create a simple Java applet. This can be achieved by following these basic steps:
1. Write a simple applet in Java
2. Compile the Java source code
3. Create a HTML page that references the applet
4. Open the HTML page in a browser
First exampleIn this example you will see, how to write an applet program. Java source of applet is then
compiled into java class file and we specify the name of class in the applet tag of html page. The
java enabled browser loads class file of applet and run in its sandbox.
Here is the java code of program :
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet{
public void paint(Graphics g){
g.drawString("Welcome in Java Applet.",40,20);
}
}
Save file as FirstApplet.java
It’s an instruction to call the applet class “FirstApplet”. The filename must match this class
name, and have an extension of “.java”. If your file is not saved as "FirstApplet.java", the Java
compiler will complain and not compile your applet.
Open cmd
Set path=
Compile java
javac FirstApplet.java
Here is the HTML code of the program:
<html>
<body>
<APPLET ALIGN="CENTER" CODE="FirstApplet.class" WIDTH="800"HEIGHT="5
00"></APPLET>
</body>
</html>
The applet contain only 1 executable statement
g.drawString("Welcome in Java Applet.",40,20);
when executed, draws the string
Welcome in Java Applet.
At the position 40, 20 (pixels) of the applet’s reserved space.
Note 1- The applet code should be saved with the file name welcome.java, in a java
subdirectory.
Note 2-The public keyword for the class welcome.java.
Applet class itself is a subclass of the panel class, which is again a subclass of the container class
and so on. This shows that the main applet class inherit properties from a long chain of classes.
An applet can use variables and methods from all these classes.
Life cycle of an applet
Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and
destroyed. Here are the lifecycle methods of an Applet:
init ( ) method: The life cycle of an applet is begin on that time when the applet is first loaded
into the browser and called the init() method. The init() method is called only one time in the life
cycle on an applet. The init() method is basically called to read the PARAM tag in the html file.
The init () method retrieve the passed parameter through the PARAM tag of html file using get
Parameter() method All the initialization such as initialization of variables and the objects like
image, sound file are loaded in the init () method .After the initialization of the init() method user
can interact with the Applet and mostly applet contains the init() method.
Start () method: The start method of an applet is called after the initialization method init().
This method may be called multiples time when the Applet needs to be started or restarted. For
Example if the user wants to return to the Applet, in this situation the start Method() of an Applet
will be called by the web browser and the user will be back on the applet. In the start method
user can interact within the applet.
Stop () method: The stop() method can be called multiple times in the life cycle of applet like
the start () method. Or should be called at least one time. There is only miner difference between
the start() method and stop () method. For example the stop() method is called by the web
browser on that time When the user leaves one applet to go another applet and the start() method
is called on that time when the user wants to go back into the first program or Applet.
destroy() method: The destroy() method is called only one time in the life cycle of Applet like
init() method. This method is called only on that time when the browser needs to Shut down.
Exceptions
An exception is a problem that arises during the execution of a program. During the program
execution if any error occurs and you want to print your own message or the system message
about the error then you 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. Error that occurs during the program
execution generate a specific object which has the information about the errors occurred in the
program. An exception can occur for many different reasons, including the following:



A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications, or the JVM has run
out of memory.
The three categories of exceptions:
 Checked exceptions: A checked exception is an exception that is typically a user error or
a problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.
 Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.
 Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Some common exceptions that we must watch out for catching areArithmeticException
Caused by match errors such as division by zero
ArrayIndexOutOfBoundsException Caused by bad array indexes
Caused when a program tries to store the wrong type of
ArrayStoreException
data in an array.
FileNotFoundException
Caused by an attempt to access a nonexistent file.
IOException
Caused by general I/O failure, such as inability to read
from a file.
NumberFormatException
Caused when a conversion between string and number
fails.
ClassNotFoundException
Related Class not found
Syntax of exception handling code
try/catch Statement
The try/catch statement encloses some code and is used to handle errors and exceptions that
might occur in that code. Here is the general syntax of the try/catch statement:
Try
{
body-code
}
catch (exception-classname variable-name)
{
handler-code
}
The try/catch statement has four parts. The body-code contains code that might throw the
exception that we want to handle. The exception-classname is the class name of the exception we
want to handle. The variable-name specifies a name for a variable that will hold the exception
object if the exception occurs. Finally, the handler-code contains the code to execute if the
exception occurs. After the handler-code executes, execution of the thread continues after the
try/catch statement. Here is an example of code that tries to create a file in a non-existent
directory which results in an IOException.
Program Dividing a number by 0
Class zero
{
Public static void main(String args[])
{
int a=10;
int b=0, x, y;
Try
{
X=a/b;
}
catch( divide d)
{
System.ot.println(“Division by zero”);
}
Y=a/(b+1);
System.ot.println(“y=”+y);
}
Output
Program catching invalid command line arguments
class cline
{
public static void main(String args[])
{
Int invalid=0;
Int num, count=0;
For(int i=0; i<args.length;i++)
{
Try
{
Num=integer.parseInt(args[i]);
}
catch(numformat e)
{
Invalid=invalid+1;
System.out.println(“Invalid number:”+args[i]);
Continue;
}
Count=count+1;
}
System.out.println(“Valid number=”+count);
System.out.println(“Invalid number=”+invalid);
}
}
Output
Multiple catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
try
{
body-code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
If an exception occurs in the protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there
and the remaining will skipped.
Program
class Nested_Try
{
public static void main (String args [ ] )
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int quot = 0;
try
{
quot = a / b;
System.out.println(quot);
}
catch (ArithmeticException e)
{
System.out.println("divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect argument type");
}
}
}
Output
Using Finally statement
Finally block are the block, that executed when the try block exits. This block executed even
after the unexpected exception occured.The Run time always execute the expression in finally
block irrespective of the try block. This block is known for recovering and preventing from
resources leak. On closing of the file and recovering of a file, you need to place the expression in
the finally block.
Syntaxtry {
statements;
} catch (exceptionType1 identifier1) {
// one or multiple
statements;
} catch (exceptionType2 identifier2) {
statements;
}
...
} finally {
// one or none
statements;
}
Examplepublic class Tester
{
public static void main(String[] args)
{
System.out.print("1");
try
{
return;
}
catch (Exception e)
{
System.out.print("2");
}
finally
{
System.out.print("3");
}
System.out.print("4");
}
}
Output
13
public class Tester
{
public static void main(String[] args)
{
System.out.print("1");
try
{
System.out.print("2");
System.exit(0);
}
finally
{
System.out.print("3");
}
}
}
Throwing our own exception
Before catching an exception it is must to be thrown first. This means that there should be a code
somewhere in the program that could catch the exception. We use throw statement to throw an
exception or simply use the throw keyword with an object reference to throw an exception. A
single argument is required by the throw statement i.e. a throwable object.As mentioned
earlier Throwable objects are instances of any subclass of the Throwable class.
throw new VeryFastException();
Note: The reference should be of type Throwable or one of its subclasses.
Download