Java Module 1
Java Module 1
MODULE 1
[
Object-Oriented Programming
Java is a general-purpose object-oriented programming language developed at sun
Microsystems of USA by James Gosling and team in the year 1991. The language was initially
called “Oak”, but was renamed as “JAVA” in 1995. Object-oriented programming (OOP) is at
the core of Java. In fact, all Java programs are to at least some extent object-oriented. OOP
is so integral to Java that it is best to understand its basic principles before you begin writing
even simple Java programs.
1. Abstraction
An essential element of object-oriented programming is abstraction. Abstraction refers to,
providing only essential information to the outside word and hiding their background details
ie. to represent the needed information in program without presenting the details.
Example: people do not think of a car as a set of tens of thousands of individual parts. They
think of it as a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the grocery store without being overwhelmed by the
complexity of the parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work. Instead, they are free to utilize the object as a
whole.
2. Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.
Figure: Encapsulation
3. Inheritance
Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification and facilitates
reusability. Inheritance interacts with encapsulation as well.
Example: Automobiles inherits all of the attributes from Vehicles since Automobile is simply
more precisely specified vehicle. A deeply inherited subclass inherits all of the attributes
from each of its ancestors in the class hierarchy.
Figure: Inheritance
4. Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions or “The ability to use a method/function in different
ways in other words giving different meaning for method/ functions is called
polymorphism”.
Example: The Same method area() can perform different operations in different scenarios.
Figure: Polymorphism
2) Package statement: The first statement allowed in a Java file is a package statement.
This statement declares a package name and informs the compiler that the class defined
here belong to the package.
3) Import statements: Import statements instruct the compiler to load the specific class
belongs to the mentioned package.
5) Class definition: A Java program may contain multiple class definition. The class are used
to map the real world object.
6) Main method class: The main method creates objects of various classes and establishes
communication between them. On reaching to the end of main the program terminates
and the control goes back to operating system.
class Example
{
public static void main(String args[])
{
[Link]("This is a simple Java Program.");
}
}
Output: This is a Simple Java Program.
Description
Opening braces: Every class definition of Java starts with opening braces and ends with
matching one.
The main line: The line “public static void main(String args[])” defines a method name main.
Java application program must include this main. This is the starting point of the interpreter
from where it starts executing. A Java program can have any number of classes but only one
class will have the main method.
Public: This key word is an access specifier that declares the main method as unprotected
and therefore making it accessible to the all other classes.
Static: Static keyword defines the method as one that belongs to the entire class and not for
a particular object of the class. The main must always be declared as static.
Void: the type modifier void specifies that the method main does not return any value.
The println: It is a method of the object out of system class. It is similar to the printf or cout
of c or c++.
class Example2
{
public static void main(String args[])
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
Output: This is num: 100
The value of num * 2 is 200
Description
Int num; declares an integer variable called num. Java (like most other languages) requires
that variables be declared before they are used. The keyword int specifies an integer type.
The general form of a variable declaration is type var-name;
num = 100; assigns to num the value 100. In Java, the assignment operator is a single equal
sign.
[Link]("This is num: " + num); In this statement, the plus sign causes the value
of num to be appended to the string that precedes it, and then the resulting string is output.
Using the + operator, you can join together as many items as you want within a single
println( ) statement.
print( ) is used to display the string “The value of num * 2 is ”. This string is not followed by a
newline. This means that when the next output is generated, it will start on the same line.
The print( ) method is just like println( ), except that it does not output a newline character
after each call.
class IfTest
{
public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
class ForTest
{
public static void main(String args[])
{
int x;
for(x = 0; x<10; x = x+1)
[Link]("This is x: " + x);
}
}
output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
Lexical Issues
The keywords const and goto are reserved but not used. In the early days of Java, several
other keywords were reserved for possible future use. However, the current specification
for Java only defines the keywords as shown in the table. In addition to the keywords, Java
reserves the following: true, false, and null. These are values defined by Java. You may not
use these words for the names of variables, classes, and so on.
DATA TYPES
Java Is a Strongly Typed Language: It is important to state at the outset that Java is a
strongly typed language. Indeed, part of Java’s safety and robustness comes from this fact.
Every variable has a type, every expression has a type, and every type is strictly defined. All
assignments, whether explicit or via parameter passing in method calls, are checked for type
compatibility.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types. These can be
put in four groups:
Integers: This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
Characters: This group includes char, which represents symbols in a character set,
like letters and numbers.
Boolean: This group includes boolean, which is a special type for representing
true/false values.
Integers
The width and ranges of these integer types vary widely, as shown in the table
1. byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from –
128 to 127. Bytes are useful for working with stream or data from a network or file. They
are also useful for working with raw binary data. A byte variable is declared with the
keyword “byte”.
Example: byte b, c;
2. short: Short is a signed 16-bit type. It has a range from –32767 to 32767. This data type
is most rarely used specially used in 16 bit computers. Short variables are declared using
the keyword short.
Example: short a, b;
3. int: The most commonly used Integer type is int. It is signed 32 bit type has a range from
–2147483648 to 2147483648.
Example: int a, b, c;
4. long: Long is a 64 bit type and useful in all those occasions where Int is not enough. The
range of long is (–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) very large.
Example: long a, b;
/* Programming Example for integer to computes the number of miles that light will travel
in a specified number of days */
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60;
distance = lightspeed * seconds;
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}
Output: In 1000 days light will travel about 16070400000000 miles.
Floating-point numbers
The width and ranges of float and double is as shown in the table
1. float: The float type specifies a single precision value that uses 32-bit storage. Float
keyword is used to declare a floating point variable.
Example: float a, b;
2. double: Double DataTips is declared with double keyword and uses 64-bit value.
Example: double r, a;
// Programming Example for float and double to compute the area of a circle.
class Area
{
public static void main(String args[])
{
double pi, a; float r = 10.8f;
pi = 3.1416;
a = pi * r * r;
[Link]("Area of circle is " + a);
}
}
Output: Area of circle is 366.4362369429933
Characters
The Java data type to store characters is char. char data type of Java uses Unicode to
represent characters. Unicode defines a fully international character set that can have all
the characters of human language. Java char is 16-bit type (2 byte). The range is 0 to 65536.
Example: char d, p;
// programming Example to demonstrates char variables
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
}
Output: ch1 and ch2: X Y
class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1);
ch1++; // increment ch1
[Link]("ch1 is now " + ch1);
}
}
Output: ch1 contains X
ch1 is now Y
Booleans
Java has a simple type called boolean for logical values. It can have only one of two possible
values. They are true or false. This is the type returned by all relational operators, as in the
case of a < b. boolean is also the type required by the conditional expressions that govern
the control statements such as if and for.
Example: boolean b;
// Programming example to demonstrate boolean values.
class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
if(b) [Link]("This is executed.");
b = false;
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.
Declaring a Variable
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is
the name of the variable. You can initialize the variable by specifying an equal sign and a
value. To declare more than one variable of the specified type, use a comma separated list.
Example: int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, j, 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'.
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
// Programming example to demonstrate dynamic initialization.
class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
double c = (a+b); // c is dynamically initialized
[Link]("Sum is " + c);
}
}
Output: Sum is 7.0
Variables are created when their scope is entered, and destroyed when their scope is left.
This means that a variable will not hold its value once it has gone out of scope. Therefore,
variables declared within a method will not hold their values between calls to that method.
Also, a variable declared within a block will lose its value when the block is left. Thus, the
lifetime of a variable is confined to its scope. If a variable declaration includes an initializer,
then that variable will be reinitialized each time the block in which it is declared is entered.
//Programming Example to demonstrate lifetime of a variable.
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
[Link]("y is: " + y); // this always prints -1
y = 100;
[Link]("y is now: " + y);
}
}
}
Output: y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Although blocks can be nested, you cannot declare a variable to have the same name as one
in an outer scope.
class ScopeErr
{
public static void main(String args[])
{
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
It is often necessary to store a value of one type into the variable of another type. In these
situations the value that to be stored should be casted to destination type. Assigning a value
of one type to a variable of another type is known as Type Casting.
Type casting can be done in two ways.
1. Widening Casting (Implicit)
To create a conversion between two incompatible types, you must use a cast. A cast is
simply an explicit type conversion.
General form of cast is: (target-type) value. Here, target-type specifies the desired type to
convert the specified value to.
// Programming Example to demonstrate casts.
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
In an expression, the precision required of an intermediate value will sometimes exceed the
range of either operand.
For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. This means that the subexpression a * b
is performed using integers—not bytes. Thus, 2,000, the result of the intermediate
expression, 50 * 40, is legal even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable.
However, because the operands were automatically promoted to int when the expression
was evaluated, the result has also been promoted to int. Thus, the result of the expression is
now of type int, which cannot be assigned to a byte without the use of a cast. This is true
even if, as in this particular case, the value being assigned would still fit in the target type. In
cases where you understand the consequences of overflow, you should use an explicit cast,
such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described. Then, if one
operand is a long, the whole expression is promoted to long. If one operand is a float, the
entire expression is promoted to float. If any of the operands is double, the result is double.
ARRAYS
An array is a group of like-typed variables that are referred to by a common name. It is
often more useful to think of an array as a collection of variables of the same type. Arrays of
any type can be created and may have one or more dimensions. A specific element in an
array is accessed by its index. Arrays offer a convenient means of grouping related
information.
Creating Arrays
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type. The general form of a one-
dimensional array declaration and allocation of memory respectively is
type var-name[ ]; Example: int month_days[];
array-var = new type[size]; Example: month_days = new int[12];
Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory that will hold the array, using new, and
assign it to the array variable. Thus, in Java all arrays are dynamically allocated.
week_days[0] = "Sunday";
week_days[1] = "Monday";
week_days[2] = "Tuesday";
week_days[3] = "Wednesday";
week_days[4] = "Thursday";
week_days[5] = "Friday";
week_days[6] = "Saturday";
[Link]("Third day is " + week_days[2]);
}
}
Output: Third day is Tuesday.
It is possible to combine the declaration of the array variable with the allocation of the array
itself, as shown here:
String week_days[] = new String[7];
Arrays can be initialized when they are declared. An array initializer is a list of comma-
separated expressions surrounded by curly braces. The commas separate the values of the
array elements. The array will automatically be created large enough to hold the number of
elements you specify in the array initializer. There is no need to use new. For example, to
store the number of days in each month, the following code creates an initialized array of
integers:
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. The length of each array is
under your control (it can be equal or unequal). To declare a multidimensional array
variable, specify each additional index using another set of square brackets.
Two-dimensional array: int twoD[][] = new int[][];
Output: 01234
56789
10 11 12 13 14
15 16 17 18 19
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24