Introduction
Java programming language was originally developed by Sun
Microsystems, which was initiated by James Gosling was released in 1995.
As of July 2011 the latest release of the Java Standard
Edition is 7 (J2SE). With the advancement of Java and its wide spread
popularity, multiple configurations were built to suite various types of platforms.
J2EE targeted enterprise applications
and the greatly stripped-down version J2ME
for mobile applications (Mobile Java). J2SE
designated the Standard Edition. In 2006, for marketing purposes, Sun renamed
new J2 versions as Java EE, Java ME, and Java SE,
respectively.
One characteristic of Java is portability, which means that
computer programs written in the Java language must run similarly on any
hardware/operating-system platform. This is achieved by compiling the Java
language code to an intermediate representation called Java bytecode,
instead of directly translating to platform-specific machine code. Java
bytecode instructions are analogous to machine code, but they are intended to
be interpreted by a virtual machine (VM) written specifically for
the host hardware. Java is guaranteed to be Write Once, Run Anywhere
Features of Java
·
Object Oriented: In java everything
is an Object. Java can be easily extended since it is based on the Object
model.
·
Platform independent: Unlike many other
programming languages including C and C++ when Java is compiled, it is not
compiled into platform specific machine, rather into platform independent byte
code. This byte code is distributed over the web and interpreted by virtual
Machine (JVM) on whichever platform it is being run.
·
Simple: Java is designed to
be easy to learn. If you understand the basic concept of OOP java would be easy
to master.
·
Secure: With Java's secure
feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
·
Architectural-neutral:
Java
compiler generates an architecture-neutral object file format which makes the
compiled code to be executable on many processors, with the presence Java
runtime system.
·
Portable: being architectural
neutral and having no implementation dependent aspects of the specification
makes Java portable. Compiler and Java is written in ANSI C.
·
Robust: Java makes an effort
to eliminate error prone situations by emphasizing mainly on compile time error
checking and runtime checking.
·
Multi-threaded: With Java's
multi-threaded feature it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
·
Interpreted: Java byte code is
translated on the fly to native machine instructions and is not stored
anywhere.
·
High Performance: With the use of
Just-In-Time compilers Java enables high performance.
·
Distributed: Java is designed for
the distributed environment of the internet.
·
Dynamic: Java is considered
to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of run-time information
that can be used to verify and resolve accesses to objects on run-time.
·
Automatic Memory
management:
Java uses an automatic garbage collector to manage memory in the object
lifecycle. The programmer determines when objects are created, and the Java
runtime is responsible for recovering the memory once objects are no longer in
use. Once no references to an object remain, the unreachable memory becomes
eligible to be freed automatically by the garbage collector.
Java Environment
Java environment consists of JDK
(Java Development Kit), which is used for writing, compiling and debugging Java
programs as well as APIs which are classes and methods which help in running
the application developed.
JDK
contains javac (compiler), java (loader and interpreter), javadoc
(documentation generator), jdb (the debugger) appletviewer (to run and debug
applets without using a browser) etc.Data types
The Java programming language is
statically-typed, which means that all variables must first be declared (stated)
before they can be used. A variable's data type determines the values it may contain,
plus the operations that may be performed on it. A data type that is predefined
by the language and is named by a reserved keyword is known as a primitive
data type. The eight primitive data types supported by the Java programming
language are:
·
byte: The byte data type is an
8-bit signed two's complement integer. It has a minimum value of -128 and a
maximum value of 127 (inclusive). The byte data type can be
useful for saving memory in large arrays, where the memory savings actually
matters.
·
short: The short data type is a
16-bit signed two's complement integer. It has a minimum value of -32,768 and a
maximum value of 32,767 (inclusive). As with byte, the same guidelines
apply: you can use a short to save memory in
large arrays, in situations where the memory savings actually matters.
·
int: The int data type is a
32-bit signed two's complement integer. It has a minimum value of
-2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral
values, this data type is generally the default choice unless there is a reason
(like the above) to choose something else. This data type will most likely be
large enough for the numbers your program will use, but if you need a wider
range of values, use long instead.
·
long: The long data type is a 64-bit
signed two's complement integer. It has a minimum value of
-9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807
(inclusive). Use this data type when you need a range of values wider than
those provided by int.
·
float: The float data type is a
single-precision 32-bit floating point. As with the recommendations for byte and short, use a float (instead of double) if you need to save
memory in large arrays of floating point numbers.
·
double: The double data type is a
double-precision 64-bit floating point. For decimal values, this data type is
generally the default choice.
·
boolean: The boolean data type has only
two possible values: true and false.
·
char: The char data type is a
single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum
value of '\uffff' (or 65,535 inclusive).
In addition to the eight
primitive data types listed above, the Java programming language also provides
special support for character strings via the java.lang.String class.
Default Values
It's not always necessary to assign a value when a field is
declared. Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default will be
zero or null, depending on the
data type. Relying on such default values, however, is generally considered bad
programming style.
The following chart summarizes the default values for the
above data types.
| Data Type |
Default Values
|
byte
|
0
|
short
|
0
|
int
|
0
|
long
|
0L
|
float
|
0.0f
|
double
|
0.0d
|
char
|
'\u0000'
|
String (or any object)
|
null
|
boolean
|
false
|
Variables
In Java, all variables must be declared before they can be
used. The basic form of a variable declaration is shown here:
type identifier [ = value][,
identifier [= value] ...] ;
The type is one of
Java's datatypes. The identifier is
the name of the variable. To declare more than one variable of the specified
type, use a comma-separated list.
Here are several examples of variable declarations of
various types. Note that some include an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints,
initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x' // the
variable x has the value 'x'.
There are three variable types available in Java Language.
They are:
·
Local variables
·
Instance variables
·
Static variables
Local variables
Local variables are those declared
in methods, constructors, or blocks. They are created when the method,
constructor or block is entered and the variable will be destroyed once it
exits the method, constructor or block. Access modifiers cannot be used for
local variables. They are visible only within the declared method, constructor
or block.
They are implemented
at stack level internally. There is no default value for local variables so
local variables should be declared and an initial value should be assigned
before the first use.
Instance variables
Instance variables are declared
in a class, but outside a method, constructor or any block. When an object gets
created, space is allocated in the heap. Instance variables also get created
along with it and a slot for each instance variable value is created in the
heap. They get destroyed when the object is destroyed.
Instance variables
hold values that may be referenced by more than one method, constructor or
block. Access modifiers can be given for instance variables.
Instance variables
have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can also be assigned during
the declaration or within the constructor.
Static variables
Static variables are declared
with the static keyword in a class,
but outside a method, constructor or a block. There would only be one copy of
each static variable per class, regardless of how many objects are created from
it.
Static variables are stored in
static memory. They are created when the program starts and destroyed when the
program stops. They also have default values.
Arrays
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 is
used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
Declaring Array Variables
To use an array in a program, you must declare a variable to
reference the array, and you must specify the type of array the variable can
reference. Here is the syntax for declaring an array variable:
dataType[]
arrayRefVar; // preferred way.
or
dataType
arrayRefVar[]; // works but not
preferred way.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays
You
can create an array by using the new operator with the following syntax:
arrayRefVar =
new dataType[arraySize];
The above statement does two things:
·
It creates an array using new dataType[arraySize];
·
It assigns the reference of the newly created array to the
variable arrayRefVar.
Constants
There are several values in the
real world which will never change. A square will always have four sides, PI to
three decimal places will always be 3.142, and a day will always have 24 hours.
These values remain constant.
The pre-processor #define is
used in C to define constants. Java gets rid of this method and introduces the
keyword modifier final.
Example: final float PI = 3.14;
If we try to change the value of
PI inside the program it will give a compiler error ‘cannot assign a value to final variable PI’.
Constants have similar scope of
other variables.
Operators
Operators are special symbols
that perform specific operations on one, two, or three operands, and then return a result.
The Simple Assignment Operator
One of the most common operators that you'll encounter is
the simple assignment operator "=". You saw this
operator in the Bicycle class; it assigns the value on its right to the operand
on its left:
int speed = 10;
int
gear = 1;
This operator can also be used on objects to assign object reference.
The Arithmetic Operators
The Java programming language
provides operators that perform addition, subtraction, multiplication, and
division. There's a good chance you'll recognize them by their counterparts in
basic mathematics. The only symbol that might look new to you is "%", which divides
one operand by another and returns the remainder as its result.
+ additive operator (also used for String
concatenation)
- subtraction operator
* multiplication operator
/ division operator
% remainder operator
The Unary Operators
The unary operators require only one operand; they perform
various operations such as incrementing/decrementing a value by one, negating
an expression, or inverting the value of a boolean.
+ Unary
plus operator; indicates positive value (numbers are positive without this,
however)
- Unary
minus operator; negates an expression
++ Increment operator; increments a value
by 1
-- Decrement
operator; decrements a value by 1
! Logical
complement operator; inverts the value of a Boolean.
The Equality and Relational Operators
The equality and relational operators determine if one
operand is greater than, less than, equal to, or not equal to another operand.
The majority of these operators will probably look familiar to you as well.
Keep in mind that you must use "==", not "=", when testing
if two primitive values are equal.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Looping
Compiling
and running the program
The Conditional Operators
The && and || operators perform Conditional-AND
and Conditional-OR operations on two boolean expressions. These
operators exhibit "short-circuiting" behavior, which means that the
second operand is evaluated only if needed.
&&
Conditional-AND
||
Conditional-OR
Another conditional operator is ?:, which can be
thought of as shorthand for an if-then-else statement. This
operator is also known as the ternary
operator because it uses three operands.
Syntax: someCondition ? value1 : value2
In this format the operator
should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
The Type Comparison Operator instanceof
The instanceof operator compares an
object to a specified type. You can use it to test if an object is an instance
of a class, an instance of a subclass, or an instance of a class that
implements a particular interface.
Bitwise and Bit Shift Operators
The Java programming language also provides operators that
perform bitwise and bit shift operations on integral types.
The unary bitwise
complement operator "~" inverts a bit pattern;
It can be applied to any of the integral types, making every
"0" a "1" and every "1" a "0". For
example, a byte contains 8 bits; applying this operator to a value whose
bit pattern is "00000000" would change its pattern to
"11111111".
Signed left shift
operator "<<" shifts a bit pattern to
the left, and
Signed right shift
operator ">>" shifts a bit pattern to
the right.
The bit pattern is given by the left-hand operand and the
number of positions to shift by the right-hand operand. The unsigned right
shift operator ">>>" shifts a zero
into the leftmost position, while the leftmost position after ">>" depends on sign
extension.
The bitwise & operator performs a
bitwise AND operation.
The bitwise ^ operator performs a
bitwise exclusive OR operation.
The bitwise | operator performs a
bitwise inclusive OR operation.
Control Statements
Looping
Executing
a block of code several number of times is referred to as a loop. Java has very flexible four looping mechanisms. You can use
one of the following loops:
·
while Loop
·
do...while Loop
·
for Loop
·
enhanced for loop
(Introduced in java 5)
The while Loop
A while loop is
a control structure that allows you to repeat a task a certain number of times.
The syntax of a
while loop is:
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.
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.
The syntax of a
do...while loop is:
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 expression
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.
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.
The syntax of a
for loop is:
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.
·
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.
Enhanced for loop
As of java 5
the enhanced for loop was introduced. This is mainly used for Arrays.
The syntax of
enhanced for loop is:
for(decleration: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.
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.
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.
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;
}
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.
The if...else Statement
An if statement
can be followed by an optional else statement, which executes when the boolean_expression is false.
Syntax:
The syntax of an
if...else is:
if(boolean_expression){
// Executes when boolean_expression is
true
}else{
// Executes when boolean_expression is
false
}
The if...else if...else Statement
An if statement
can be followed by an optional else if...else statement, which is very usefull 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.
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.
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(boolean_expression){
case value:
// statements
case value:
// 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.
Classes
A
class is nothing but a blueprint or 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 data members
known as fields and member functions known as methods to describe
the behavior of an object. Methods are nothing but members of a class that provide a service
for an object or perform some business logic.
A class has the following general syntax:
<class
modifiers>class<class name>
<extends clause> <implements clause>{
<extends clause> <implements clause>{
<field
declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<constructor declarations>
<method declarations (Static and Non-Static)>
<constructor declarations>
}
Example:
public class Rectangle{
int length,
breadth;
int area(){
return length*breadth;
}
}
In the above example, a class called
Rectangle is created with fields length
and breadth. A method area() is also defined which calculates
and returns the area of the rectangle.
Constructors
A java
constructor has the same name as the name of the class
to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
A constructor is generally used to initialize fields of an object, hence its
name. It gets invoked when an object is created using the new operator.
Constructors that do not take any arguments
are known as default constructor. Java
provides a default constructor which takes no arguments and performs no special actions or
initializations, when no explicit constructors are provided.
Constructors may include parameters of various types. Such constructors are known
as parameterized constructor. When
the constructor is invoked using the new
operator, the types must match those that are specified in the constructor definition.
Example:
public class Rectangle{
int
length, breadth;
Rectangle(){ //
default constructor
length
=0;
breadth
= 0;
}
Rectangle (int l, int b){ // parameterized constructor
length
= l;
breadth
= b;
}
int
area(){
return
length*breadth;
}
}
The first Program
A simple
program that prints a line of text can be written in java as
class First{
public static void main(String[] args){
System.out.println(“Welcome to
the world of Java”);
}
}
In the sample
program given above the first line declares a class called First.
Inside the
class we have the main() method. As
java is true object oriented language everything must be inside a class, so the
main method should also be encapsulated inside a class. main() is similar to
the main() method in C/C++. This is the starting point for the interpreter to
begin the execution of the program. A program can contain any number of classes
but only one of them can have the main() method.. The java identifies the class
containing the main method using the name of the class. For this the program
needs to be saved as First.java i.e. the name of the class containing the main
method should be given as the name of the file in which the program is written.
In the sample
program above the main() method declaration has many keywords like public,
static and void. The keyword public is an access specifier that
declares the main method is accessible to all other classes. Keyword static says that the method belongs to
the whole class and is not part of any object. Static methods can be accessed
using the class name without creating any objects. main() is always declared static as the interpreter uses this
method before any objects are created. The void
keyword states that the method does not return any value.
args is declared as a
String array which is parameter to the function main(). This array holds the
values that are passes as command line argument when the program is run.
A program
containing the Rectangle class is given below.
First.java
class Rectangle{
int
length, breadth;
Rectangle(){
length
=0;
breadth
= 0;
}
Rectangle (int l, int b){
length
= l;
breadth
= b;
}
int
area(){
return
length*breadth;
}
}
class First{
public
static void main(String[] args){
Rectangle
r1= new Rectangle(10,20);
int
area = r1.area();
System.out.println(“Area
= ” + area);
}
}
Compiling
and running the program
After saving
the program as First.java it can be compiled using the command javac
javac
First.java
The compiled
program can be run by using the command java and the name of the file without
extension
java
First
The output
produced is
Area
= 200
String Handling
Manipulation of Strings is one
of the difficult tasks in programming. In common programming languages strings are a sequence of characters. In
the Java programming language, strings are not character arrays and is not null
terminated. They are objects.
Java provides String and StringBuffer classes for handling stings very easily.
Creating Strings
Strings may be
declared and created as follows:
String stringName = new String([“value”]);
E.g. String
lang = new String(“Java”);
Whenever it
encounters a string literal in your code, the compiler creates a String object.
Length of a string is obtained
by the length() method
int len = lang.length();
Concatenation of strings can be
done using + operator.
E.g. String fullname = firstName + lastName //where
firstName and lastName are Java strings
StringMethods
The String class defines a number of methods
that allow us to accomplish a variety of string manipulation tasks. Following
table lists the most commonly used:
Sl. No.
|
Method Call
|
Description
|
1
|
s2 = s1.toLowerCase
|
Converts s1 to all lowercase and assigns the result to s2
|
2
|
s2 = s1.toUpperCase
|
Converts s1 to all uppercase and assigns the result to s2
|
3
|
s2 = s1.replace(‘x’, ‘y’)
|
Replaces all x in s1 with y and assigns result to s2
|
4
|
s2 = s1.trim()
|
Removes white spaces before and after the string s1
|
5
|
s1.equals(s2)
|
Returns true if both s1 and s2 are equal
|
6
|
s1.equalsIgnoreCase(s2)
|
Returns true if both s1 and s2 are equal. The case of characters is not
considered for comparison
|
7
|
s1.length()
|
Returns the length of String s1
|
8
|
s1.charAt(i)
|
Returns the character at index i
|
9
|
s1.compareTo(s2)
|
Returns –ve if s1<s2, +ve if s1>s2 and 0 if
both are equal
|
10
|
s1.concat(s2)
|
Concatenates s1 and s2
|
11
|
s1.substring(n)
|
Returns the substring starting from index n
|
12
|
s1.substring(i, m)
|
Returns the substring of m characters stating from index i
|
13
|
s1.indexOf(‘x’)
|
Returns the index of the character x in s1
|
14
|
s1.indexOf(‘x’, i)
|
Returns the index of the character x after index i in s1
|
StringBufer class
While String class creates Strings of fixed
length, StringBuffer creates strings of flexible length. The length and content
of a StringBuffer object can be modified. Strings can be appended at the beginning, in the middle or at the end of the StringBuffer object.
The common methods used are:
Sl. No.
|
Method Call
|
Description
|
1
|
s1.setCharAt(i, x)
|
Modify ith character of s1 to x
|
2
|
s1.append(s2)
|
Appends s2 to s1 at the end
|
3
|
s1.insert(i, s2)
|
Insert s2 inside s1 starting from index i
|
4
|
s1.setLength(n)
|
Set the length of s1 to n. If length of s1<n
|

No comments:
Post a Comment