Module 1
Module 1
Introduction to JAVA
Java is a general-purpose, object-oriented programming language. It is a blend of C & C++. It
was developed by Sun Microsystems of USA, by a team headed by James Gosling in the year
1991. It was first named as ‘Oak’.
C and C++ languages have problems in terms of reliability and portability. So the
language java was formed, by removing the sources of problems of C and C++ and making the
new language java simple, reliable , portable and powerful.
Java is also used in web applications, because of its portability and security. Applets and
servlet programs were developed, which acts as web browser and web server respectively. World
Wide Web emerged at about the same time that Java was being implemented. Internet wanted
portable programs, so Java was used in its programs. It was a perfect response to the demands of
the newly emerging, highly distributed computing universe.
It is the Java tool which contains all the classes , methods and variables used to develop and
build a Java program. It consists of –
JRE (Java Runtime Environment) consists of tools required to execute the java code, eg.
JVM. A program cannot take any action outside this boundary during runtime.
Java is interpreted
A Java source file is first compiled using Java compiler, this produces the bytecode. Byte code
is highly optimized set of instruction. It is an intermediate stage during the execution. The byte
code is than interpreted by the Java Virtual Machine (JVM), to produce the output in the
expected system.
Due to the interpretation behavior of Java, this language is platform independent and
portable .
A Java Virtual Machine (JVM) is a virtual machine capable of executing Java bytecode.
JVM enables Java to be both secure and portable.
bytecode
JAVA PROGRAM JAVA COMPILER JVM Program output
.java file .class file
(Compiles Source Code) (Interpretes ByteCode)
The Java compiler generates the bytecode, which is a highly optimized set of instructions. JVM
is an interpreter for bytecode and creates the executable file. Thus Java is called an interpreted
language.
There are different JVMs for different operating systems. So only JVM need to be
implemented for any other platform. Thus JVM helps in the portability of Java program. JVM
also helps to make Java secure. Java code is executed by JVM and thus JVM has the control to
prevent program from generating side effects to the system.
javac javac
Remote Remote
System System
In C or C++ , the preprocessor statements or header files are replaced with those large
header files and then the whole program is compiles. So it takes more time for compilation.
But Java doesnot contain header files or preprocessor statements. The compilation process
consists of just creating a bytecode. During interpretation by JVM, if any packages are included
the required functions are executed and only the result is sent to the calling java program.
The developers of Java wanted to design a language that solves all the problems of modern high-
level language. They not only wanted secure and portable language but also a simple, compact
and interactive language.
Simple – Java is a simple language to learn and program. Many features of C and C++ are used in
Java. It is very easy to familiarize Java as the same concepts of C, C++ and object – oriented
programming are used here. Java is a simplified version of C++.
Secure - Systems connected to Internet must be secure. There are more chances of virus attack while
downloading. Viruses may affect your system or take important information like account no,
password etc. from your system. Java achieved security by confining an applet to Java execution
environment and not allowing it access to other parts of the computer.
Portability – portability means the code written and executed in a system must be able to execute in
other systems of different environment also. This is achieved in Java by JVM. Changes and
upgrades in operating system, processors and system resources will not force any changes in Java
programs. Changes in the platform like windows, linux etc. will not stop the java program from
execution.
Object-oriented – Java is true object-oriented language. Everything in Java is an object. All the
program code resides in a class or object. The classes are arranged in packages and can be
inherited.
Robust – Java is a robust language. It provides many safeguards to ensure reliable code. It has strict
compile time and run time checking for data types. The major two reasons for any program
failure are memory management mistakes and mishandled exceptions. These are handled very
well in Java. It is designed as a garbage-collected language relieving the programmers from all
memory management problems. It incorporates exception handling – handles serious errors and
eliminates any risk of crashing the system.
Multithreaded – Java supports multithreading. Java program has the capability of handling multiple
tasks simultaneously. This means that we need not wait for the application to finish one task
before beginning another. Example - we can listen to an audio clip while scrolling a page and at
the same time download an applet from a distant computer.
Architectural-Neutral - The main issue of Java developers was t hat the code longevity and
portability. The code executed in a system, may not execute in the same system due to the
upgrades of OS, processors and change in core system resources. The Java designers made the
language and built JVM such that a code written once can run anytime, anywhere and forever.
Interpreted and High performance - A Java program is compiled to form an intermediate Java
bytecode. This can be executed in any system that has implemented JVM. JVM interprets the
bytecode to form an executable file. The bytecode is highly optimized and so there is high
performance.
Distributed – Java is designed as a distributed language, as it can share data and programs from
Internet. Java handles TCP/IP protocol. Java also supports RMI, which enables a program to
invoke remote methods.
Object
An Object is an instance of user-defined data type called Class. It can also be said that
object is a variable whose type is a user-defined Class.
Object is a real – time entity.
An object in Java is a representation of some physical, logical, or conceptual entity. For
example, an object can be a vehicle, bank-account, animal, machine etc.
Class
Class is a template for instantiating an object.
It encapsulates the attributes and behavior of an entity.
Similar objects belong to a class. For example, cat and dog belongs to animal class.
Object is a run-type entity in object-oriented programming where as Class is just a template for
generating an object.
Abstraction
Encapsulation
Encapsulation is bundling together the attributes and behaviors of an entity.
Object-oriented programming allows classes to inherit commonly used state and behavior
from other classes. In this example, Bicycle now becomes the superclass of MountainBike,
RoadBike, and TandemBike. In the Java programming language, each class is allowed to have
one direct superclass, and each superclass has the potential for an unlimited number of
subclasses:
A hierarchy of bicycle classes
This gives Mountain Bike all the same fields and methods as Bicycle, yet allows its code to focus
exclusively on the features that make it unique. This makes code for your subclasses easy to
read.
Polymorphism
A function can exhibit many forms depending on the class of which it is a part. For
example , we have a function called make_sound(). If is part of human object,
make_sound() returns 'speak' and if it is a part of dog object then it returns 'bark'
The line - class Sample uses the keyword class to declare that new class is being defined.
Sample is an identifier that is the name of the class. The class members are included in the ‘{’ &
‘}’.
The line public static void main(String args[ ]) begins the main() method. public keyword is
an access specifier, which allows the programmer to control the visibility of the class members.
The main method must be declared as public, since it must be called by code outside of its class
when the program is stated, JVM calls the main() function. static means that this variable or
method is for the class not for any objects in particular. The main() method must be static as it is
called without having to instantiate any class. void tells that main() does not return any value.
Any information needed to pass to the method is received by the array specified in
parenthesis of the main function. This is an array of strings.
The line [Link](“This is java”); is used to display a line specified within double
quotes.
Java source file is compiled using Java compiler at the prompt as,
This creates a file called [Link] that contains the bytecode version of the program. This
cannot be directly executed it has to be interpreted by JVM as follows to get the output.
C:\>java Sample
The Java compiler will create separate class file for each class in the program. Then the java
command is given with the name of the class which you want to execute.
Data Types
Every variable in Java has a data type. Data types specify the size and type of values that can be
stored. The variety of data types available, allow the programmer to select the type appropriate to
the needs of the application. Java data types are as follows –
Interface
Integer Floating-Point Character Boolean
Byte Float
Short Double
Int
Long
Note: All the data types have a strictly defined range, regardless of the execution environment,
ie. int is always 32 bits. This guarantees to achieve portability.
Integer Types
Java defines four integer types: byte, short, int, and long. They can hold only whole numbers
such as 123,-87. These integer data types differs in the size of the values that can be stored. The
memory size and range of all the four integer data types are shown in table below –
Type Size (in bytes) Minimum Value Maximum Value
byte 1 -128 127
short 2 -32,768 32,767
int 4 -2,147,483,648 2,147,483,647
long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Floating Point Types
Integer types can hold only whole numbers and therefore we use another type known as floating
point type to hold numbers containing fractional parts such as 27.45 and -1.345. There are two
kinds of floating point storage in Java – float type and double type. The float type values are
single-precision numbers while the double types represent double-precision numbers.
Character Type
The data type used to store characters is char. It has a size of 2 bytes. It uses Unicode to
represent characters. It holds a single character.
Boolean Type
Java has a primitive type, called Boolean, for logical values. It can have only one of two possible
values, true or false.
Default Values
Fields that are declared but not initialized will be set to a default by the compiler. This default
will be zero or null, depending on the data type. The default values for the above data types are -
Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Strings
Strings are created using two classes in Java, String and StringBuffer. An object of String class
is instantiated to store the value of strings. A Java string is not a character array and is not NULL
terminated.
Eg –
String firstName;
firstName = new String(“Sajeev”);
String Methods
The String class contains many methods to translate the string variables. Eg – toLowerCase(),
trim(), replace(), concat() etc. The table below shows the lists of string methods. Here i and j are
int indexes into a string, s and t are Strings, and c is a char. cs is a CharacterSequence.
class StringOrdering
{
static String name[ ] ={“Madras”,”Delhi”,”Ahmedbad”,”Calcutta”,”Bombay”};
public static void main(String mar[])
{
int size = [Link];
String temp = null;
for (int i = 0; i < size ; i++)
{
for( int j =i+1; j < size ; j++)
{
If(name[i].compareTo(name[j]) >0)
{
//swap the strings
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for (int i = 0; i < size ; i++)
{
[Link](name[i]);
}
}
}
Variables
The variable is the basic unit of storage in a Java program. A variable may take different values
at different times, unlike constants that remain unchanged during the execution of program. All
variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used.
here ‘type’ - one of Java's atomic datatypes, or the name of a class or interface,
‘varname’ - name of the variable.
The variable can be initialized by specifying an equal sign and a value. It must be of the same
type (or compatible) as that specified for the variable. Use a comma to declare more than one
variable of the specified type.
Eg -
int a, b, c; // declares three variables of int type a, b, and c.
int d = 3, e, f = 5; // declares three int type variable , d and f are initialized
byte z = 22; // declares one byte type variable z.
double pi = 3.14159; // declares and initializes a double variable.
char x = 'x'; // declares a character variable x and initializes to value 'x'.
Output –
x and y: 10 20
Variable y is not known here
x is 40
Type Casting
The conversion of a variable from one data type to another data type is called type casting.
Four integer types (byte,short,int and long )can be cast to any other data type except
Boolean.
Floating point datatypes(float and double) can also be casted to any other type except
Boolean.
Casting into a smaller type results in a loss of data.
Floating point values if type casted to integer, it losses the fractional part of the floating
value.
int type is always large enough to hold all valid byte values, so no explicit cast statement is required.
Eg: byte b=108; // b is of type byte
int a =b; // value of byte ‘b’ is automatically taken into integer ‘a’.
Access Specifiers
The access to the code and variables in the class is controlled by encapsulation. The access
specifier in the declaration determines the accessibility of its members. The access specifiers in
Java are – public, private, and protected.
When the member has a public specifier, then that member can be accessed by any other
code. When the member is specified as private, then that member can only be accessed by other
members of its class. protected applies only when inheritance is involved. So the main() function
is specified as public, as it has to be invoked by Java run-time system.
When no access specifier is used, then by default the member of a class is public within
its own package, but cannot be accessed outside of its package.
The Basic Arithmetic Operators
The basic arithmetic operations-addition, subtraction, multiplication, and division- all do the
same operations as in mathematic. The minus operator is also used as a unary operator, to negate
the single operand. Unary operator means it acts on single operator. The division operator when
applied to an integer type, there will be no fractional component attached to the result.
The modulus operator, %, returns the remainder of a division operation. It can be applied
to floating-point types as well as integer types.
The following simple example program demonstrates the arithmetic operators and modulus
operator. It also illustrates the difference between floating-point division and integer division.
class BasicMath
{
public static void main(String args[])
{
// arithmetic using integers
[Link]("Integer Arithmetic");
int a = 1 + 1;
int b = a *
3; int c = b /
4; int d = c -
a; int e = -d;
int x = 42
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
Control Statements
Control statements causes the flow of execution to advance or branch based on changes to the
state of a program. Program control statements can be put into the following categories:
selection, iteration, and jump.
Selection statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable. Iteration statements enable program
execution to repeat one or more statements (that is, iteration statements form loops). Jump
statements allow your program to execute in a nonlinear fashion. All of Java's control statements
are examined here.
Java supports two selection statements: if and switch. These statements allows to control
the flow of program's execution based upon conditions known only during run time.
if
The if statement is Java's conditional branch statement. It can be used to route program execution
through two different paths.
Syntax –
if (condition is true )
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces. The condition is any expression that returns a boolean value. The else clause is optional.
If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is
executed. In no case will both statements be executed.
Eg1 –
……
int a, b,res;
a=6;
b=0;
if( b != 0)
res = a/b;
……
….
Here, if b is not zero, then a is divided by b.
Eg 2–
String passwd = “sai”;
……
if( passwd == “vidya”)
[Link](“Valid Password”);
else
[Link](“In-valid Password”);
……….
……..
Nested if
A nested if is an if statement that comes in the statement of another if or else. The else statement
always refers to the nearest if statement that is within the same block as the else.
Eg –
if(i == 10)
{
if(j < 20) a = b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
The final else is not associated with if(j<20), because it is not in the same block. But, it is
associated with if(i==10). The inner else refers to if(k>100), because it is the closest if within the
same block.
The if-else-if Ladder
When a series of decisions are involved, a sequence of nested ifs and elses are required. The if
else-if ladder looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
When one of the if statement conditions is true, the statement associated with that if is executed,
and the rest of else if conditions are bypassed. If none of the conditions is true, then the final else
statement will be executed. The final else acts as a default condition; that is, if all other
conditional tests fail, then the last else statement is performed.
//A program to demonstrate if-else-if statements, to find the number of days in a month .
class IfElse
{
public static void main(String args[])
{
int month = 4; // April
int days;
String year = “leapyear”;
if(month =2)
{
if(year = “leapyear”)
days = 29;
else
days = 28;
}
else if(month == 1 || month == 3 || month == 5|| month == 7|| month == 8|| month
== 10|| month == 12)
days = 31;
else
days = 30;
[Link]("April has " + days + "days.");
}
}
Ouput is –
April has 30 days.
Iteration Statements
The iteration statements or loops of Java are for, while, and do-while. A loop repeatedly
executes the same set of instructions until a termination condition is met.
while
The while loop is the most fundamental looping statement of Java. It repeats a statement or
block while its controlling expression is true.
Syntax –
while(condition) {
// body of loop
}
The condition can be any Boolean expression(An expression which returns true or false). The
body of the loop will be executed as long as the conditional expression is true. When condition
becomes false, control passes to the next line of code immediately following the loop.
{
public static void main(String args[])
{
int n = 10;
while(n > 0)
{
[Link]("tick " +
n); n--;
}
}
}
Output is –
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
The body of the loop will not execute even once if the condition is false to begin with.
do-while
Sometimes it is required to execute the body of a while loop at least once, even if the conditional
expression is false to begin with. In do-while loop the test of expression is done at the end.
Syntax –
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the
loop terminates. The do-while loop condition must be a Boolean expression.
int n = 10; do {
[Link]("tick " +
n); n--;
} while(n > 0);
}
}
For loop
There are two for loops in Java. The first is the traditional form that is used in other languages
also. The second is the new “for-each” form.
When the loop first starts, the initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which acts as a counter that controls
the loop. The initialization expression is only executed once.
Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control
variable against a target value. If this expression is true, then the body of the loop is executed. If
it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually
an expression that increments or decrements the loop control variable. The loop then iterates,
first evaluating the conditional expression, then executing the body of the loop, and then
executing the iteration expression with each pass. This process repeats until the controlling
expression is false.
As the for loop contains only 1 statement, there is no need for the curly braces. Often the control
variable of the for loop is only used within that loop, So it is possible to declare the variable
inside the initialization portion of the for.
For example, the preceding program can be changed as follows as the control variable n is used
inside the for only.
……………
………
for(int n=10; n>0; n--)
[Link]("tick " + n);
}
}
For-Each Statement
From JDK 5, a second form of for was defined that implements ‘for-each’ style loop. The ‘for-
each’ loop moves through a collection of objects, such as an array, in strictly sequential fashion
from start to finish. In Java this is built as an enhancement to for loop, so this style is also calles
as enhanced for loop.
Syntax –
for(type itr-var : collection)
{
statements;
}
Here, type specifies the data type and itr-var is the name of an iteration variable that will receive
the elements from a collection, one by one from beginning to end of the collection.
This style of for loop eliminates the need to establish a loop counter and manually index the
array. It automatically cycles through the entire array, obtaining one element at a time.
Eg –
//A program to demonstrate the use of for-each style of for loop
class ForEach
{
public static void main(String args[])
{
int nums[ ] ={1,2,3,4,5,6,7,8,9,10};
int sum = 0;
for(int x : nums)
{
[Link]("Value is : " + x);
sum = sum + x;
}
[Link]("Summation: " + sum);
}
}
Output –
Value is : 1
Value is : 2
Value is : 3
Value is : 4
Value is : 5
Value is : 6
Value is : 7
Value is : 8
Value is : 9
Value is :10
Summation : 55
Nested Loops
Java allows loops to be nested. That is, one loop may be inside another loop.
Eg –
// Loops may be nested.
class Nested
{
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
[Link](".");
[Link]();
}
}
}
Output –
..........
.........
........
.......
......
.....
....
...
..
.