21OECS62 Module-1 Notes
21OECS62 Module-1 Notes
Computer language innovation and development occurs for two fundamental reasons:
The development of Java was driven by both elements in nearly equal measure.
Java is related to C++, which is a direct derivative of C. much of the properties of java is
inherited from these two languages.
Java programming language was introduced by James Gosling, Patrick Naughton, Chris
Warth and Ed Frank at Sun Microsystems in 1991. It took eighteen months to develop the
working version. This language was initially called „OAK‟ but was renamed as „Java‟ in
1995. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key
contributors to the maturing of the original prototype.
The original impetus for Java was not the Internet! Instead, the primary motivation was
the need for a platform-independent (that is, architecture-neutral) language that could be
used to create software to be embedded in various consumer electronic devices, such as
microwave ovens and remote controls.
The trouble with C and C++ is that they are designed to be compiled for a specific target.
Although it is possible to compile a C++ program for just about any type of CPU, to do so
requires a full C++ compiler targeted for that CPU. The problem is that compilers are
expensive and time-consuming to create. An easier—and more cost-efficient—solution was
needed. In an attempt to find such a solution, Gosling and others began work on a portable,
platform-independent language that could be used to produce code that would run on a
variety of CPUs under differing environments. This effort ultimately led to the creation of
Java.
Important factor that played a crucial role in the development of Java was, of course, the
World Wide Web.
The creation of the applet changed Internet programming because it expanded the universe
of objects that can move about freely in cyberspace. Every time you download a “normal”
program, you are taking a risk, because the code you are downloading might contain a
virus, Trojan horse, or other harmful code. At the core of the problem is the fact that
malicious code can cause its damage because it has gained unauthorized access to system
resources. Java achieved this protection by confining an applet to the Java execution
environment and not allowing it access to other parts of the computer.
Java’s Magic: The Bytecode: The key that allows Java to solve both the security and the
portability problems is that the output of a Java compiler is not executable code. Rather, it
is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by
the Java run-time system, which is called the Java Virtual Machine (JVM).
The JVM is the Java run-time system and is the main component of making the java a
platform independent language. For building and running a java application we need
JDK(Java Development Kit) which comes bundled with Java runtime environment(JRE) and
JVM. With the help of JDK the user compiles and runs his java program. As the compilation
of java program starts the Java Bytecode is created i.e. a .class file is created by JRE.
Bytecode is a highly optimized set of instructions designed to be executed by JVM. Now the
JVM comes into play, which is made to read and execute this bytecode. The JVM is linked
with operating system and runs the bytecode to execute the code depending upon operating
system. Therefore, a user can take this class file(Bytecode file) formed to any operating
systemwhich is having a JVM installed and can run his program easily without even touching
the syntax of a program and without actually having the source code. The .class file which
consists of bytecode is not user-understandable and can be interpreted by JVM only to build
it into the machine code.
Two approaches are there to solve the problem and in program writing: Procedure oriented
and object oriented.
Problems increases in procedure oriented as the program grows larger and more
complex.
Object Oriented:
Object oriented programs are written based on “Who is being affected” around,
which manages the increasing complexity.
Characterised as data controlling access to code. Ex: C++, JAVA, Small Talk etc
Abstraction
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of a car or applying brakes will stop the car, but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of the accelerator, brakes, etc
in the car. This is what abstraction is.
Encapsulation
Inheritence
Polymorphism
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical
o Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
o Methods
o Constructors
o Blocks
Encapsulation
Encapsulation is the mechanism to bind the data and code working on that data into
a single entity. It provides the security for the data by avoiding outside manipulations. In
Java, encapsulation is achieved using classes.
That is, several objects share a common structure (data) and behavior (code) defined
by that class.
Specifically, the data or variables inside the class are called as member variables or
instance variables or data members.
The code that operates on these data is referred to as member methods or methods
(In C++, we term this as member function).
The method operating on data will define the behavior and interface of a class.
Another purpose of the class is to hide the information from outside manipulation. Class
uses public and private interfaces. The members declared as private can only be accessed
by the members of that class, whereas, the public members can be accessed from outside
the class.
Inheritance
It is a process by which one object can acquire the properties of another object. It supports
the concept of hierarchical classification.
For example, consider a large group of animals having few of the abstract attributes like
size, intelligence, skeletal structure etc. and having behavioral aspects like eating, breathing
etc. Mammals have all the properties of Animals and also have their own specific features
like type of teeth, mammary glands etc. that make them different from Reptiles.
Similarly, Cats and Dogs have all the characteristics of mammals, yet with few features
which are unique for themselves. Though Doberman, German-shepherd, Labrador etc. have
the features of Dog class, they have their own unique individuality. This concept can be
depicted using following figure
If we apply the above concept for programming, it can be easily understood that a code
written is reusable. Thus, in this mechanism, it is possible for one object to be a specific
instance of a more general case. Using inheritance, an object need only define those
qualities that make it a unique object within its class. It can inherit its general attributes
from its parent. Hence, through inheritance, we can achieve generalization specialization
concept. The top-most parent (or base class or super class) class is the generalized class
and the bottom-most child (or derived class or subclass) class is a more specialized class
with specific characteristics.
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.
A superclass named “Shapes” has a method called “area()”. Subclasses of “Shapes” can be
“Triangle”, “circle”, “Rectangle”, etc. Each subclass has its way of calculating area. Using
Inheritance and Polymorphism means, the subclasses can use the “area()” method to find
the area’s formula for that shape.
Encapsulation allows to migrate the implementation without disturbing the code that
depends on class.
class Example {
In Java, a source file is officially called a compilation unit. It is a text file that contains
one or more class definitions. The Java compiler requires that a source file use the .java
filename extension.
In Java, all code must reside inside a class. By convention, the name of the main class
should match the name of the file that holds the program.
To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of
the program.
To actually run the program, you must use the Java application launcher called java. To do
so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
/*
This is a comment. Like most other programming languages, Java lets you enter a
remark into a program’s source file. The contents of a comment are ignored by the
compiler.
class Example { This line uses the keyword class to declare that a new class is being
defined. Example is an identifier that is the name of the class. The entire class
definition, including all of its members, will be between the opening curly brace ({)
and the closing curly brace (}).
The next line in the program is the single-line comment, shown here:
This line begins the main( ) method. This is the line at which the program will
begin executing. All Java applications begin execution by calling main( ).
The opposite of public is private, which prevents a member from being used
by code defined outside of its class.
The keyword void simply tells the compiler that main( ) does not return a
value
args receives any command-line arguments present when the program is executed
*/
class Example2 {
num = num * 2;
System.out.println(num);
When you run this program, you will see the following output:
There are many important fatures of java, they are also known as „Java buzzwords‟.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architectureneutral
8. Dynamic
9. Interpreted
10. HighPerformance
11. Multithreaded
12. Distributed
Simple : According to Sun Microsystems, Java language is simple because syntax is based
on C++ (easier to learn after C++) and removed many confusing features such as explicit
pointers, operator overloading etc and no need to remove unreferenced objects because
there is automatic garbage collection in java.
Objects
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Runtime environment
Java code can be run on multiple platforms such as Windows, Solaris, Linux, Mac/OS etc.
Java code is compiled by the compiler and converted into „byte code‟. The byte code is a
platform independent code because it can be run on multiple platform i.e „Write once and
run anywhere (WORA)‟.
Secured: Java is secured because “No explicit pointer” and “Program run inside virtual
machine sandbox‟. It is composed of the following:
Class loader: Adds security by separating the package for classes of local file system
from those that are imported from network sources.
Byte verifier: Checks the code fragments for illegal code that can violate access
rights to objects.
Security manager: Determines what resources a class can access such as reading
and writing to local disk.
Robust: Robust simply means its strong. Java uses strong memory management. There are
“lack of pointers‟ that avoids security problem. There is “Automatic garbage collection‟ in
Java. There is “Exception handling‟ and “Type checking‟ mechanisms in java.
High performance: Java is faster than traditional interpretation since byte code is close to
native code.
Distributed: We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the methods from any
machine on internet.
Soon after the release of Java 1.0, the designers of Java had already created Java 1.1
Java 1.1 added many new library elements, redefined the way events are handled, and
reconfigured many features of the 1.0 library. It also deprecated (rendered obsolete)
several features originally defined by Java 1.0.
The next major release of Java was Java 2, where the “2” indicates “second generation.”
The first release of Java 2 carried the version number 1.2. With Java 2, Sun repackaged the
Java product as J2SE (Java 2 Platform Standard Edition). Java 2 added support for a
number of new features, such as Swing and the Collections Framework, and it enhanced the
Java Virtual Machine and various programming tools.
J2SE 1.3 was the first major upgrade to the original Java 2 release. For the most part, it
added to existing functionality and “tightened up” the development environment
The release of J2SE 1.4 further enhanced Java. This release contained several important
upgrades, enhancements, and additions. For example, it added the new keyword assert,
chained exceptions, and a channel-based I/O subsystem. It also made changes to the
Collections Framework and the networking classes
The next release of Java was J2SE 1.5. list of its major new features:
Generics
Annotations
Enumerations
Formatted I/O
Concurrency utilities
The next release of Java was called Java SE 6. The Java Development Kit was called JDK 6.
The internal, developer version number is 1.6. Java SE 6 added no major features to the
Java language proper, but it did enhance the API libraries, added several new packages, and
offered improvements to the runtime.
Java SE 7 was the next release of Java, with the Java Development Kit being called JDK 7,
and an internal version number of 1.7. Java SE 7 was the first major release of Java since
Sun Microsystems was acquired by Oracle. Java SE 7 contained many new features,
including significant additions to the language and the API libraries. Upgrades to the Java
run-time system that support non-Java languages were also included.
• Type inference (via the diamond operator) when constructing a generic instance.
• Enhanced exception handling in which two or more exceptions can be caught by a single
catch (multi-catch) and better type checking for exceptions that are rethrown.
• Although not a syntax change, the compiler warnings associated with some types of
varargs methods were improved, and you have more control over the warnings.
JDK 8 represents a very significant upgrade to the Java language because of the inclusion of
a far-reaching new language feature: the lambda expression.
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 is a space, tab, or newline.
Identifiers
Literals
A constant value in Java is created by using a literal representation of it. For example, here
are some literals:
Comments
The third type is called a documentation comment. This type of comment is used to produce
an HTML file that documents your program. (documentation comment begins with a /** and
ends with a */).
Separators
The most commonly used separator in Java is the semicolon.
Data Types
Data types represent the different values to be stored in the variable. In java, there are two
types of data types:
Primitive datatypes
Non-primitive datatypes
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
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.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive
and negative values. Java does not support unsigned, positive-only
integers.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127. Variables of type byte are especially useful when you’re working with a stream of data
from a network or file. 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:
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably 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
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:
class Light {
long days;
long seconds;
long distance;
lightspeed = 186000;
Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.
import java.util.Scanner;
class Area {
double pi, r, a;
r=input.nextDouble();
a = pi * r * r; // compute area
O/P:
Characters This group includes char, which represents symbols in a character set, like
letters and numbers.
In Java char is a 16-bit type. The range of a char is 0 to 65,535. There are no negative
chars.
class CharArithDemo {
char ch;
ch = 'X';
ch++; // increment ch
O/P:
ch contains X
ch is now Y
ch is now Z
Boolean This group includes boolean, which is a special type for representing true/false
values.
class BoolDemo {
b = false;
b = true;
b = false;
O/P:
b is false b is true
This is executed.
10 > 9 is true
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 shown here:
// d and f.
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
class DynInit {
// c is dynamically initialized
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is
determined by the access specifier that is applied to these variables. The lifetime of these
variables is the same as the lifetime of the object to which it belongs. Object once created
do not exist for ever. They are destroyed by the garbage collector of Java when there are no
more reference to that object.
Argument variables
These are the variables that are defined in the header of constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The lifetime
is limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.
Local variables
Shobha Chandra K, Asst Professor, CSE, MCE Page 19
Introduction to Java Programming - Module-1
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers
can be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are
defined in bocks life an if block and an else block. The scope and is the same as that of the
block itself.
Arithmetic operators are used in mathematical expressions in the same way that they are
class BasicMath {
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
When you run this program, you will see the following output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
The Modulus Operator
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 example program demonstrates
the %:
class Modulus {
int x = 42;
double y = 42.25;
Shobha Chandra K, Asst Professor, CSE, MCE Page 22
Introduction to Java Programming - Module-1
System.out.println("x mod 10 = " + x % 10);
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25
a = a + 4;
a += 4;
This version uses the += compound assignment operator. Both statements perform the
same action: they increase the value of a by 4.
can be rewritten as
class OpEquals {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
a=6
b=8
c=3
The increment operator increases its operand by one. The decrement operator decreases its
operand by one.
x = x + 1;
x++;
x = x - 1;
is equivalent to
x--;
These operators are unique in that they can appear both in postfix form, where they follow
the operand, and prefix form, where they precede the operand.
In the prefix form, the operand is incremented or decremented before the value is obtained
for use in the expression. In postfix form, the previous value is obtained for use in the
expression, and then the operand is modified. For example:
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the increment occurs before x is
assigned to y. Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
However, when written like this,
x = 42;
y = x++;
the value of x is obtained before the increment operator is executed, so the value of y is 42.
y = x;
x = x + 1;
The following program demonstrates the increment operator.
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
The output of this program follows:
a=2
b=3
c=4
d=1
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types: long, int,
short, char, and byte. These operators act upon the individual bits of their operands. They
are summarized in the following table:
class BitLogic {
String binary[] = {
};
int c = a | b;
int d = a & b;
int e = a ^ b;
Here, num specifies the number of positions to left-shift the value in value. That is, the <<
moves all of the bits in the specified value to the left by the number of bit positions specified
by num. For each shift left, the high-order bit is shifted out (and lost), and a zero is brought
in on the right.
class ByteShift {
byte a = 64, b;
int i;
i = a << 2;
Original value of a: 64
i and b: 256 0
Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num.
int a = 32;
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they
operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and
!false == true. The following table shows the effect of each logical operation:
class BoolLogic {
boolean a = true;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean g = !a;
These are secondary versions of the Boolean AND and OR operators, and are commonly
known as short-circuit logical operators.
The difference between normal and short-circuit versions is that the normal operands will
always evaluate each operand, but short-circuit versions will evaluate the second operand
only when necessary.
When the right-hand operand depends on the value of the left one in order to function
properly. For example, the following code fragment shows how you can take advantage of
short-circuit logical evaluation to be sure that a division operation will be valid before
evaluating it:
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time
exception when denom is zero. If this line of code were written using the single &version of
AND, both sides would be evaluated, causing a run-time exception when denom is zero.
int n, d, q;
n = 10;
if(d != 0 && (n % d) == 0)
if(d != 0 && (n % d) == 0)
*/
if(d != 0 & (n % d) == 0)
Assignment operators:
var = expression;
Here, the type of var must be compatible with the type of expression. int x, y, z;
This fragment sets the variables x, y, and z to 100 using a single statement.
Java provides special operators that can be used to combine an arithmetic operation with an
assignment.
There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form var = var op expression; can be rewritten as var op=
expression;
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then
else statements. This operator is the ?. It can seem somewhat confusing at first, but the ?
can be used very effectively once mastered. The ? has this general form:
Here, expression1 can be any expression that evaluates to a boolean value. If expression1
is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the
? operation is that of the expression evaluated. Both expression2 and expression3 are
required to return the same (or compatible) type, which can’t be void.
// Demonstrate ?.
class Ternary {
int i, k;
i = 10;
i = -10;
Absolute value of 10 is 10
Operator Precedence
The following table shows the order of precedence for Java operators, from highest to
lowest. Operators in the same row are equal in precedence. In binary operations, the order
of evaluation is left to right (except for assignment, which evaluates right to left). Although
they are technically separators, the [ ], ( ), and . can also act like operators. In that
capacity, they would have the highest precedence.
Using Parentheses
Parentheses raise the precedence of the operations that are inside them.
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this
expression can be rewritten using redundant parentheses like this:
a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result, you
will need to parenthesize the expression like this:
(a >> b) + 3