Module 1 Java Notes
Module 1 Java Notes
Module -1
Introduction to Java
Java is a high level, robust, object-oriented, platform independent and secured
programming language.
The term WORA, write once and run everywhere is often associated with Java language. It
means whenever we compile a Java code, we get the byte code (.class file), and that can
be executed (without compiling it again) on different platforms provided they support
Java.
In the year 1995, Java language was developed. It is mainly used to develop web,
desktop, and mobile devices.
JVM (Java Virtual Machine): JVM is the specification that facilitates the runtime
environment in which the execution of the Java bytecode takes place
Byte Code: Java compiler compiles the Java code to generate the .class file or the
byte code. One has to use the javac command to invoke the Java compiler.
Java Development Kit (JDK): It is the complete Java Development Kit that
encompasses everything, including JRE(Java Runtime Environment), compiler, java
docs, debuggers, etc. JDK must be installed on the computer for the creation,
compilation, and execution of a Java program.
Java Runtime Environment (JRE): JRE is part of the JDK. If a system has only JRE
installed, then the user can only run the program. In other words, only
the java command works. The compilation of a Java program will not be possible
(the javac command will not work).
Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs
are to at least some extent object-oriented. Object-oriented concepts form the heart of
Java just as they form the basis for human understanding. object-oriented programming
is a powerful and natural paradigm for creating programs.
Two Paradigms
All computer programs consist of two elements: code and data.
These are the two paradigms that govern how a program is constructed.
1. process- oriented model: This approach characterizes a program as a series of linear steps
(that is, code). The process-oriented model can be thought of as code acting on data.
2. object-oriented programming: To manage increasing complexity, the second approach,
called object-oriented programming, was conceived. Object-oriented programming
organizes a program around its data (that is, objects) and a set of well-defined
interfaces to that data. An object-oriented program can be characterized as data
controlling access to code.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
Encapsulation is as a protective wrapper that prevents the code and data from
being arbitrarily accessed by other code defined outside the wrapper. Access to the
code and data inside the wrapper is tightly controlled through a well-defined
interface.
In Java, the basis of encapsulation is the class.
When you create a class, you will specify the code and data that constitute that
class.
Collectively, these elements are called members of the class.
Specifically, the data defined by the class are referred to as member variables or
instance variables. In properly written Java programs, the methods define how
the member variables can be used. This means that the behavior and interface of a
class are defined by the methods that operate on its instance data.
Since the purpose of a class is to encapsulate complexity, there are mechanisms for
hiding the complexity of the implementation inside the class. Each method or
variable in a class may be marked private or public.
The public interface of a class represents everything that external users of the class
need to know, or may know.
The private methods and data can only be accessed by code that is a member of the
class. Therefore, any other code that is not a member of the class cannot access a
private method or variable. Since the private members of a class may only be
accessed by other parts of your program through the class’ public methods, you can
ensure that no improper actions take place. this means that the public interface
should be carefully designed not to expose too much of the inner workings of a
class.
Figure 2-1 Encapsulation: public methods can be used to protect private data.
Inheritance
Inheritance is the process by which one object acquires the properties of another
object.
For example, a Golden Retriever is part of the classification dog, which in turn is part
of the mammal class, which is under the larger class animal. Without the use of
hierarchies, each object would need to define all of its characteristics explicitly. It
can inherit its general attributes from its parent.
Most people naturally view the world as made up of objects that are related to
each other in a hierarchical way, such as animals, mammals, and dogs. If you
wanted to describe animals in an abstract way, you would say they have some
attributes, such as size, intelligence, and type of skeletal system. Animals also have
certain behavioral aspects; they eat, breathe, and sleep.
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be
used for a general class of actions. The specific action is determined by the exact nature of the
situation.
This helps reduce complexity by allowing the same interface to be used to specify a general class
of action. It is the compiler’s job to select the specific action (that is, method) as it applies to each
situation. You, the programmer, do not need to make this selection manually.
Extending the dog analogy, a dog’s sense of smell is polymorphic. If the dog smells a cat, it will
bark and run after it. If the dog smells its food, it will salivate and run to its bowl.
The same sense of smell is at work in both situations. The difference is what is being smelled, that
is, the type of data being operated upon by the dog’s nose! This same general concept can be
Operator Meaning
< Less than
> Greater than
== Equal to
class IfSample {
public static void main(String[] args) {
int x, y;
x = 10;
y = 20;
if(x < y) System.out.println("x is less than y"); x = x * 2;
if(x == y) System.out.println("x now equal to y");
x = x * 2;
if(x > y) System.out.println("x now greater than y");
Part I
// this won't display anything
if(x == y) System.out.println("you won't see this");
}
}
The output generated by this program is shown here:
x is less than y
x now equal to y
x now greater than y
class ForTest {
public static void main(String[] args) { int x;
for(x = 0; x<10; x = x+1) System.out.println("This is x: " + x);
}
}
class BlockTest {
public static void main(String[] args) {
int x, y;
y = 20;
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y); y = y - 2;
}
}
}
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, comments, operators, separators, and
keywords.
Whitespace
Java is a free-form language.
This means that you do not need to follow any special indentation rules.
For instance, the Example program could have been written all on one line or in any other strange way you
felt like typing it, as long as there was at least one whitespace character between each token that was not
already delineated by an operator or separator. In Java, whitespace includes a space, tab, newline, or form
feed.
Identifiers
Identifiers are used to name things, such as classes, variables, and methods.
An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
They must not begin with a number, lest they be confused with a numeric literal.
Again, Java is case- sensitive, so VALUE is a different identifier than Value.
Some examples of valid identifiers are
Literals
A constant value in Java is created by using a literal representation of it.
For example, here are some literals:
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character
constant, and the last is a string. A literal can be used anywhere a value of its type is allowed.
Comments
There are three types of comments defined by Java: single-line and multiline and documentation
comment. This type of comment is used to produce an HTML file that documents your program. The
documentation comment begins with a /** and ends with a */. Documentation comments are explained in
PI
Appendix A.
Separators
In Java, there are a few characters that are used as separators. The most commonly used separator in Java is
the semicolon. The separators are shown in the following table:
Integers
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values.
The width of an integer type should not be thought of as the amount of storage it consumes, but
rather as the behavior it defines for variables and expressions of that type.
The width and ranges of these integer types vary widely, as shown in this table.
byte
The smallest integer type is byte.
This is a signed 8-bit type that has a range from –128 to 127.
They are also useful when you’re working with raw binary data that may not be directly compatible with
Java’s other built-in types.
Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c:
Part I
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767.
It is the least- used Java type.
Here are some examples of short variable declarations:
short s; short t;
int
The most commonly used integer type is int.
It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647.
The reason is that when byte and short values are used in an expression, they are promoted to int when the
expression is evaluated.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold
the desired value.
The range of a long is quite large.
This makes it useful when big, whole numbers are needed
For example, here is a program that computes the number of miles that light will travel in a specified
number of days:
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days = 1000;
seconds = days * 24 * 60 * 60; // convert to seconds distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about "); System.out.println(distance + " miles.");
}
output:
In 1000 days light will travel about 16070400000000 miles.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision.
For example, calculations such as square root, or transcendentals such as sine and cosine, result in a
value whose precision requires a floating- point type.
There are two kinds of floating-point types, float and double, which represent single- and double-precision
numbers, respectively.
float
o The type float specifies a single-precision value that uses 32 bits of storage.
o Single precision is faster on some processors and takes half as much space as double precision, but will
become imprecise when the values are either very large or very small.
o Variables of type float are useful when you need a fractional component,
o Here are some example float variable declarations:
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations.
All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to
maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the
best choice.
Here is a short program that uses double variables to compute the area of a circle:
class Area {
public static void main(String[] args) { double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
Part I
}
}
Characters
In Java, the data type used to store characters is char.
A key point to understand is that Java uses Unicode to represent characters.
class CharDemo {
public static void main(String[] args) {
char ch1, ch2;
ch1 = 88; // code for X ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Booleans
Java has a primitive type, called boolean, for logical values.
It can have only one of two possible values, true or false.
This is the type returned by all relational operators, 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.
class BoolTest {
public static void main(String[] args) { boolean b;
b = false;
System.out.println("b is " + b); b = true;
System.out.println("b is " + b);
System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
System.out.println("10 > 9 is " + (10 > 9));
}
Part I
int x = 0b1010;
You can embed one or more underscores in an integer literal. Doing so makes it easier to read large integer
literals. When the literal is compiled, the underscores are discarded.
For example, given
int x = 123_456_789;
the value given to x will be 123,456,789. The underscores will be ignored. Underscores can only be used to
separate digits. They cannot come at the beginning or the end of a literal. It is, however, permissible for
more than one underscore to be used between two digits.
For example, this is valid:
int x = 123 456 789;
The use of underscores in an integer literal is especially useful when encoding such things as telephone
numbers, customer ID numbers, part numbers, and so on. For example, binary values are often visually
int x = 0b1101_0101_0001_1010;
o Standard notation consists of a whole number component followed by a decimal point followed by a
fractional component.
o For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers.
Hexadecimal floating-point literals are also supported, but they are rarely used.
They must be in a form similar to scientific notation, but a P or p, rather than an E or e, is used.
The value following the P, called the binary exponent, indicates the power-of-two by which the number is
Boolean Literals
Boolean literals are simple.
There are only two logical values that a boolean value can have, true and false.
The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0
Character Literals
Characters in Java are indices into the Unicode character set.
They are 16-bit values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction operators.
A literal character is represented inside a pair of single quotes.
All of the visible ASCII characters can be directly entered inside the quotes, such as 'a', 'z', and
'@'.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing a sequence
of characters between a pair of double quotes.
Examples of string literals are
"Hello World" "two\nlines"
" \"This is in quotes\""
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
In Java, all variables must be declared before they can be used.
The basic form of a variable declaration is
type identifier [ = value ][, identifier [= value ] …];
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is
declared.
For example, here is a short program that computes the length of the hypotenuse of a right triangle
given the lengths of its two opposing sides:
class DynInit {
public static void main(String[] args) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized by constants.
However, c is initialized dynamically to the length of the hypotenuse The program uses another of Java’s
built-in methods, sqrt( ), which is a member of the Math class, to compute the square root of its
argument.
A method’s scope ends with its closing curly brace. This block of code is called the method body.
To understand the effect of nested scopes, consider the following program:
DEEPIKA G, DEPT. OF CSE, SVIT , BENGALURU
OOP with Java
class Scope {
public static void main(String[] args) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
For example, the int type is always large enough to hold all valid byte values, so no explicit cast
statement is required.
For widening conversions, the numeric types, including integer and floating-point types, are compatible
with each other. However, there are no automatic conversions from the numeric types to char or boolean.
Also, char and boolean are not compatible with each other.
Java also performs an automatic type conversion when storing a literal integer constant into
variables of type byte, short, long, or char.
If a variable declaration includes an initializer, then that variable will be reinitialized each time the block
in which it is declared is entered. For example
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 System.out.println("y is: " + y); // this always prints -1 y = 100;
System.out.println("y is now: " + y);
}
}
}
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Arrays
An array is a group of like-typed variables that are referred to by a common name. 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.
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 is
type[ ] var-name;
class Array {
month_days[10] = 30;
month_days[11] = 31;
Multidimensional Arrays
In Java, multidimensional arrays are implemented as arrays of arrays. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For example, the
following declares a two-dimensional array variable called twoD:
This allocates a 4 by 5 array and assigns it to twoD. Internally, this matrix is implemented as an array of
arrays of int. Conceptually, this array will look like the one shown in Figure 3-1.
The following program numbers each element in the array from left to right, top to bottom, and then
displays these values:
class TwoDArray {
public static void main(String[] args) { int[][] twoD= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++) for(j=0; j<5; j++) {
twoD[i][j] = k; k++;
}
012 34
567 89
10 11 12 13 14
15 16 17 18 19
Operators
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:
Operator Result
+ Addition (also unary plus)
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement
The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean
types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.
class BasicMath {
public static void main(String[] args) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
class Modulus {
public static void main(String[] args) { int x = 42;
double y = 42.25;
output:
x mod 10 = 2
y mod 10 = 2.25
Java provides special operators that can be used to combine an arithmetic operation with an
assignment.
class OpEquals {
public static void main(String[] args) {
int a = 1;
int b = 2; int c = 3;
a += 5;
b *= 4;
c += a * b; c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The output of this program is shown here:
a=6
b=8
c=3
class IncDec {
public static void main(String[] args) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
a=2
b=3
c=4
d=1
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
class BitLogic {
public static void main(String[] args) {
String[] binary = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111","1000", "1001", "1010", "1011", "1100", "1101",
"1110", "1111"};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary int c = a | b;
int d = a & b; int e = a ^ b;
int f = (~a & b)|(a & ~b); int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
Part I
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
class HexByte {
public static void main(String[] args) {
char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
}
}
b = 0xf1
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Control Statements
while
The while loop is Java’s most fundamental loop statement.
It repeats a statement or block while its controlling expression is true.
Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. 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. The curly braces are unnecessary if only a single statement is being
repeated.
Here is a while loop that counts down from 10, printing exactly ten lines of "tick":
class While {
public static void main(String[] args) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n); n--;
}
}
}
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
do-while
The do-while loop always executes its body at least once, because its conditional expression is at the
bottom of the loop.
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.
class DoWhile {
public static void main(String[] args) { int n = 10;
do {
System.out.println("tick " + n); n--;
} while(n > 0);
}
class ForTick {
public static void main(String[] args) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
class ForEach {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values for(int x : nums) {
System.out.println("Value is: " + x); sum += x;
}
System.out.println("Summation: " + sum);
}
}
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
Part I
another. For example, here is a program that nests for loops:
// 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++)
System.out.print("."); System.out.println();
}
}
}
The output produced by this program is shown here:
..........
.........
........
.......
......
.....
....
...
..
.
Jump Statements
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program. Each is examined here.
Using break
In Java, the break statement has three uses.
First, as you have seen, it terminates a statement sequence in a switch statement.
Second, it can be used to exit a loop.
Third, it can be used as a “civilized” form of goto.
By using break, you can force immediate termination of a loop, bypassing the conditional expression
and any remaining code in the body of the loop. When a break statement is encountered inside a loop,
the loop is terminated and program control resumes at the next statement following the loop. Here is a
simple example:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
class Break {
public static void main(String[] args) { boolean t = true;
first: { second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Using continue
In while and do-while loops, a continue statement causes control to be transferred directly to
the conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and then to the
conditional expression. For all three loops, any intermediate code is bypassed.
Here is an example program that uses continue to cause two numbers to be printed on each
line:
// Demonstrate continue.
class Continue {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
01
23
45
67
89
return
The last control statement is return. The return statement is used to explicitly return from a
Part I
method. That is, it causes program control to transfer back to the caller of the method.
At any time in a method, the return statement can be used to cause execution to branch back
to the caller of the method. Thus, the return statement immediately terminates the method in
which it is executed.
The following example illustrates this point. Here, return causes execution to return to the Java
run-time system, since it is the run-time system that calls main( ):