Oops Module1 Chapter1
Oops Module1 Chapter1
Module 1
Chapter 1
An overview of Java
• The use of structured languages enabled programmers to write, for the first time,
moderately complex programs fairly easily. However, even with structured
programming methods, once a project reaches a certain size, its complexity exceeds what
a programmer can manage.
• By the early 1980s, many projects were pushing the structured approach past its limits.
To solve this problem, a new way to program was invented, called object-oriented
programming (OOP). Object- oriented programming
• OOP is a programming methodology that helps organize complex programs through the
use of inheritance, encapsulation, and polymorphism.
• C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell
Laboratories in Murray Hill, New Jersey. Stroustrup initially called the new language “C
with Classes.” However, in 1983, the name was changed to C++.
➢ Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridanat Sun Microsystems, Inc. in 1991.
➢ It took 18 months to develop the first working version. This language was initially called
“Oak,” butwas renamed “Java” in 1995.
➢ Between the initial implementation of Oak in the fall of 1992 and the public announcement
of Java inthe spring of 1995, many more people contributed to the design and evolution of
the language.
➢ Java derives much of its character from C and C++.
➢ The computer languages evolves java for two reasons:
• To adapt to changes in environment and to implement advances in
the art ofprogramming.
• The environmental change that prompted Java was the need for
platform-independent programs destined for distribution on the
Internet.
Security
• Java achieved this protection by confining an applet to the Java execution environment
andnot allowing it access to other parts of the computer.
• The ability to download applets with confidence that no harm will be done and that no
securitywill be breached is considered by many to be the single most innovative aspect
of Java.
Portability
• Portability is a major aspect of the Internet because there are many different types of
computers and operating systems connected to it.
• If a Java program were to be run on virtually any computer connected to the Internet,
there needed to be some way to enable that program to execute on different systems.
• For example, in the case of an applet, the same applet must be able to be downloaded
and executed by the wide variety of CPUs, operating systems, and browsers connected
to the Internet.
• It is not practical to have different versions of the applet for different computers.
• The same code must work on all computers.
Because the JVM is in control, it can contain the program and prevent it from generating
sideeffects outside of the system.
• The result was the servlet. A servlet is a small program that executes on the server.
• Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend
the functionality of a web server
• By using servlet, Java spanned both sides of the client/server connection.
• The Servlets are used to create dynamically generated content that is then served to the client.
• For example, an online store might use a servlet to look up the price for an item in a database. The
price information is then used to dynamically generate a web page that is sent to the browser.
Although dynamically generated content is available through mechanisms such as CGI (Common
Gateway Interface), the servlet offers several advantages, including increased performance.
• Because servlets (like all Java programs) are compiled into bytecode and executed by the JVM,
they are highly portable.
• Tthe same servlet can be used in a variety of different server environments.
• The only requirements are that the server support the JVM and a servlet container.
1) Simple
• Java was designed to be easy for the professional programmer to learn and use effectively.
• If you already understand the basic concepts of object-oriented programming, learning Java will be
even easier.
• An experienced C++ programmer, moving to Java will require very little effort.
• Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most
programmers have little trouble learning Java.
2) Secure
• Java achieved this protection by confining an applet to the Java execution environment and not
allowing it access other parts of the computer.
• The ability to download applets with confidence that no harm will be done and that no security will be
breached considered by many to be the single most innovative aspect of Java.
• The code we download might contain virus, Trojan horse, or other harmful code that can gain
unauthorized access system resources.
• For example, a virus program might gather private information, such as credit card numbers, bank
account balance and passwords, by searching the contents of computer.
• Java achieved protection by confining an applet to the Java execution environment and not allowing
it access to other parts of the computer.
2) Portability
• Portability is a major aspect of the Internet because there are many different types of computers and
operating systems connected to it. If a Java program were to be run on virtually any
computer connected to the Internet, there needed to be some way to enable that program to execute on
different systems.
• For example, in the case of an applet, the same applet must be able to be downloaded and executed by
the wide variety of CPUs, operating systems, and browsers connected to the Internet.
• It is not practical to have different versions of the applet for different computers.
• The same code must work on all computers.
• Different types of computers and operating systems connected to internet.
• Java program must be able to run on any computer connected to the Internet,
• The same applet must be able to be downloaded and executed by the wide variety of CPUs, operating
systems, and browsers connected to the Internet.
• It is not practical to have different versions of the applet for different computers. The same code must
work on all computers.
• Therefore, some means of generating portable executable code was needed.
• The same mechanism which ensure security also helps in portability.
2) Object-Oriented
• Java was not designed to be source-code compatible with any other language.
• One outcome of this was a clean, usable, pragmatic approach to objects.
• The object model in Java is simple and easy to extend, while primitive types, such asintegers, are kept
as high-performance nonobjects.
5) Robust
The multi-platformed environment of the Web places extraordinary
demands on a program, because the program must execute reliably in a
variety of systems.
The ability to create robust programs was given a high priority in the design of
Java.
The program must execute reliably in a variety of systems.
To gain reliability, Java restricts us to find mistakes early in program development.
As Java is a strictly typed language, it checks code at compile time. also checks
code at run time. Java programmers behave in a predictable way under diverse conditions is a key
feature of Java. Programs fail in 2 conditions, memory management mistakes and mishandled
exceptional condition.
Java virtually eliminates memory management problems by managing
memory allocation and deallocation automatically.
Exceptional conditions(run time errors) in Java is handled well by providing object- oriented
exceptionhandling(that is, run-time errors).
6) Multithreaded
Java was designed to meet the real-world requirement of creating interactive,
networked programs. To accomplish this, Java supports multithreaded
programming, which allows you to write programs thatdo many things
simultaneously.
The Java run-time system comes with an elegant yet sophisticated solution
for multiprocesssynchronization that enables you to construct smoothly running interactive
systems.
Java’s easy-to-use approach to multithreading allows you to think about the specific behavior of
yourprogram, not the multitasking subsystem.
7) Architecture-Neutral
• A central issue for the Java designers was that of code longevity and portability.
• One of the main problems facing programmers is that no guarantee exists that if you write a program
today,it will run tomorrow—even on the same machine.
• Operating system upgrades, processor upgrades, and changes in core system resources can all
combine to make a program malfunction.
• The Java designers made several hard decisions in the Java language and the Java Virtual Machine in
anattempt to alter this situation.
• Their goal was “write once; run anywhere, any time, forever.” To a great extent, this goal
wasaccomplished.
9) Distributed
• Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols.
• Accessing a resource using a URL is not much different from accessing a file.
• Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke
methods across a network.
10) Dynamic
• Java programs carry with them substantial amounts of run-time type information that is used to
verify and
• resolve accesses to objects at run time.
• This makes it possible to dynamically link code in a safe and expedient manner.
• The robustness of the Java environment, in which small fragments of bytecode may be dynamically
updated on running system.
• They can ignore the details of how the engine, transmission, and braking systems work. Instead, they
are freeto utilize the object as a whole.
• From the outside, the car is a single object. Once inside, you see that the car consists of several
subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so on.
• Each of these subsystems is made up of more specialized units.
• Hierarchical abstractions of complex systems can also be applied to computer programs.
• Therefore, any other code that is not a member of the class cannot access a private method or
variable.
FIGURE :Encapsulation: public methods can be used to protect private data
2) 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.
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.
It can inherit its general attributes from its parent.
If you wanted to describe a more specific class of animals, such as mammals, they would have
more specific attributes, such as type of teeth, and mammary glands. This is known as a
subclass of animals, where animals are referred to as mammals’ superclass.
Since mammals are simply more precisely specified animals, they inherit all of the attributes from
animals.
A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class
hierarchy.
Figure: Inheritance
OOPS WITH JAVA – BCS306A Module1
[Link]
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.
The name of the source file should be [Link]. Let’s see why.
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.
As you can see by looking at the program, the name of the class defined by
the program isalso Example. This is not a coincidence.
In Java, all code must reside inside a class.
By convention, the name of that class should match the name of the file that
holds the program. You should also make sure that the capitalization of the
filename matches the class name.
The reason for this is that Java is case-sensitive.
Compiling the Program
To compile the Example program, execute the compiler, javac, specifying the name of
thesource file on the command line, as shown here:
C:\>javac [Link]
The javac compiler creates a file called [Link] that contains the bytecode version
of theprogram.
OOPS WITH JAVA – BCS306A Module1
The program that contains instructions the Java Virtual Machine will execute.
The output of javac is not code that can be directly executed.
To actually run the program, you must use the Java application launcher, called
java.
/*
This is a simple Java [Link]
this file "[Link]". */
• 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.
• In this case, the comment describes the program and reminds you that the source file should be called
[Link].
• Of course, in real applications, comments generally explain how some part of the program works or what
aspecific feature does.
• Java supports three styles of comments.
• The one shown at the top of the program is called a multiline comment.
• This type of comment must begin with /* and end with */.
• Anything between these two comment symbols is 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:
OOPS WITH JAVA – BCS306A Module1
The keyword static allows main( ) to be called without having to instantiate a particular instance of
theclass.
This is necessary since main( ) is called by the Java Virtual Machine before any objects are
made.
The keyword void simply tells the compiler that main( ) does not return a value.
As stated, main( ) is the method called when a Java application begins.
Java is case-sensitive. Thus, Main is different from main.
It is important to understand that the Java compiler will compile classes that do not contain a
main( ) method.
Any information that you need to pass to a method is received by variables
specified within the set ofparentheses that follow the name of the method.
These variables are called parameters.
In main( ), there is only one parameter i.e. String args[ ] declares a parameter
named args, which is anarray of instances of the class String.
The next line of code is shown here. Notice that it occurs inside main( ).
This line outputs the string “This is a simple Java program.” followed by a new line on the screen. The
built-in println( ) method ,println( ) can be used to display other types of information, too.
OOPS WITH JAVA – BCS306A Module1
The first } in the program ends main( ), and the last } ends the Example class definition.
type var-name;
num = 100; // this assigns num the value 100
2 .Two Control Statements
1) The if Statement
• The Java if statement works much like the IF statement in any other language.
Syntax:
if(condition) statement;
OOPS WITH JAVA – BCS306A Module1
• [Link] is an example:
The operators which may be used in a conditional expression. Here are a few:
Operator Meaning
< Less than
> Greater than
Equal to
/*
Demonstrate the if.
• In its most common form, the initialization portion of the loop sets a loop controlvariable to
an initial value.
• The condition is a Boolean expression that tests the loop control variable.
• If the outcome of that test is true, the for loop continues to iterate. If it is false, the
loopterminates.
• The iteration expression determines how the loop control variable is changed each time
theloop iterates. for loop example:
/*
Demonstrate the for loop.
Call this file "[Link]".
*/
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
OOPS WITH JAVA – BCS306A Module1
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
2) Identifiers
• Identifiers are used for class names, method names, and variable names.
• 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.
• Some examples of valid identifiers are
3) Literals
A constant value in Java is created by using a literal representation of it. For example, here
aresome literals:
4) Comments
• You have already seen two: single-line and multiline. The third type is called a 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 */.
5) 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:
• In addition to the keywords, Java reserves the following: true, false, and null. These are values
defined by Java.
As mentioned, these methods are members of the System class,which is a class predefined by Java that is
automatically included in your programs.
In the larger view, the Java environment relies on several built-in class libraries that contain many
builtin methods that provide support for such things as I/O, string handling, networking,and graphics.
The standard classes also provide support for windowed output. Thus, Java as a totality is a
combination of the Java language itself, plus its standard classes.
As you will see, the class libraries provide much of the functionality that comes with Java. Indeed,part of
becoming a Java programmer is learning to use the standard Java classes.
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. Let’s see what this means. First, every variable has a
type, every expression has a type, and every type is strictly defined. Second,all assignments, whether
explicit or via parameter passing in method calls, are checked for type compatibility. There are no
automatic coercions or conversions of conflicting types as in some languages. The Java compiler
checks all expressions and parameters to ensure that the types are compatible. Any type mismatches
are errors that must be corrected before the compiler will finish compiling the class.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not
large enoughto hold the desired value.
The range of a long is quite large.
Compute distance light travels using long variables
Width Range
64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
32 –2,147,483,648 to 2,147,483,647
16 –32,768 to 32,767
8 –128 to 127
byte
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
float
The type float specifies a single-precision value that uses 32 bits of storage.
Variables of type float are useful when you need a fractional component, but don’t require
a large degreeof precision.
For example, float can be useful when representing dollars
and cents.
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 for high-speed mathematical calculations. All
transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. Many iterative
calculations, or are manipulating large-valued numbers, double is the bestchoice.
Here is a short program that uses double variables to compute the area of a circle:
3.5 Characters
In Java, the data type used to store characters is char. char is 8 bits
wide. This is not the case in Java.
It is a dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew,
Katakana, Hangul, andmany more. For this purpose, it requires 16 bits.
Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536.
There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127. Here is a
program that demonstrates char variables:
}
Output: ch1 and ch2: X Y
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds
to theletter X.
The ASCII character set occupies the first 127 values in the Unicode character set.
3.6 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 < [Link] is a program that demonstrates the
boolean type:
class BoolTest
{ public static void main(String args[])
{ boolean b; b =
false;
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 theaddition and subtraction operators.
• A literal character is represented inside a pair of single quotes. All of the visible ASCII characters can
be directlyentered 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
ofcharacters between a pair of double quotes.
• Examples of string literals are
“Hello
World”
“two\nlines”
“\”This is in quotes\”“
3.8 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.
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:
type identifier [ = value][, identifier [= value] ...] ;
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.
Here are several examples of variable declarations of various types. Note that some
include aninitialization.
Dynamic Initialization
• Although the preceding examples have used only constants as initializers.
• 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
thelengths of its two opposing sides:
//Demonstrate dynamic initialization
class DynInit
{ public static void main(String args[])
{ double a = 3.0, b = 4.0;
//c is dynamically initialized double c
=[Link](a * a + b * b);
However, not all types are compatible, and thus, not all type conversions are implicitly
allowed.
For instance, there is no automatic conversion defined from double to byte.
It is still possible to obtain a conversion between incompatible types.
To do so, you must use a cast, which performs an explicit conversion between
incompatible types.
Here, target-type specifies the desired type to convert the specified value to.
For example, the following fragment casts an int to a byte.
If the integer’s value is larger than the range of a byte, it will be reduced modulo
(the remainder of an integerdivision by the) byte’s range.
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type:
truncation.
When a floating-point value is assigned to an integer type, the fractional component is lost. For
example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1.
The 0.23 will have been truncated.
If the size of the whole number component is too large to fit into the target integer type, then that value
will bereduced modulo the target type’s range.
Example:
Demonstrate casts. class
Conversion
{ public static void main(String args[])
{ byte b; int i = 257;
double d = 323.142;
[Link]("
\nConversion of int
to byte."); b = (byte)
i;
[Link]("i and b " + i + " " + b);
Output:
Conversion of int to byte.i and b
257 1
Conversion of double to int. d and
i 323.142 323 Conversion of
double to byte.d and b 323.142 67
byte b = 50;
The following program demonstrates how each value in the expression gets promoted to match the second
argument toeach binary operator:
class Promote
{ public static void main(String args[])
{ byte b = 42; char c
= 'a'; short s =
1024; int i =
50000; float f
= 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
Then the resultant float minus the last double is promoted to double, which is the type for the final
result of theexpression.
3.6 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.
Arrays offer a convenient means of grouping related information.
1) 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
Syntax:
type var-name[ ];
Here, type declares the base
type of the array. Example:
int month_days[];
The month_days is an array variable, no array actually exists.
The value of month_days is set to null, which represents an array with
no value. To link month_days with an actual, physical array of integers,
you must allocate one using new andassign it to month_days.
The new is a special operator that allocates memory.
The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the
number of elements in the array,and array-var is the array variable
that is linked to the array.
The new to allocate an array, you must specify the type and number of elements to
allocate.
The elements in the array allocated by new will automatically be initialized to zero.
This exampleallocates a 12-element array of integers and links them to month_days.
month_days = new int[12];
month_days[1] = 28;
[Link](month_days[3]);
Example1:
//Demonstrate a one-dimensional array.
class Array
{ public static void main(String args[])
{
int monthdays[ ];
monthdays=new int[12];
monthdays[0]=31;
monthdays[1]=28;
monthdays[2]=31;
monthdays[3]=30;
monthdays[4]=31;
monthdays[5]=30;
monthdays[6]=31;
monthdays[7]=31;
monthdays[8]=30;
monthdays[9]=31;
monthdays[10]=30;
monthdays[11]=31;
[Link](“April has “+monthdays[3] +”days.”);
}
}
E
xa
m
pl
e2
:
int month_days[];
month_days = new int[12];
//An improved version of the previous program.
class AutoArray
{ public static void main(String args[])
{ int month_days[]={31,28,31,30,31,30,31,31,30,31,30,31 };
[Link]("April has " + month_days[3] + " days.");
}
}
Example3:
//Average an array of values
class Average
{ public static void main(String args[])
{ double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double
result = 0;
int i; for(i=0; i<5; i++)
result = result + nums[i];
[Link]("Average is " + result / 5);
}
}
2) Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.
To declare a multidimensional array variable, specify each additional index using another set
of squarebrackets.
For example, the following declares a two-dimensional array variable called twoD.
Example:
//Demonstrate a two-dimensional array.
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++; }
for(i=0; i<4; i++)
{ for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
You can allocate the remaining dimensions
For example, this following code allocates memory for the first dimension of twoD when it is
declared. Itallocates the second dimension manually.
Example:
Example:
//Initialize a two-dimensional array.
class Matrix
{ public static void main(String args[])
{
double m[][]={{0*0,1*0,2*0,3*0},{0*1,1*1,2*1,3*1},{0*2,1*2,2*2,3*2},{0*3,1*3,2*3,3*3}}; int
i, j;
for(i=0; i<4; i++)
{ for(j=0; j<4; j+
+)
[Link](m[i][j] + " ");
}
}
}
Output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
✓ 3.0 6.0 9.0
Example:
//Demonstrate a three-dimensional array.
class ThreeDMatrix
{ public static void main(String args[])
{ int threeD[][][] = new int[3][4][5];int i, j,
k;
for(i=0; i<3; i++) for(j=0;
j<4; j++) for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++)
{ for(j=0; j<4; j++)
{ for(k=0; k<5; k++)
[Link](threeD[i][j][k] + " ");
[Link]();
}
OOPS WITH JAVA – BCS306A Module1
[Link]();
}
}
}
This program generates the following output:
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16 0 6
12 18 24
It is just that Java’s string type, called String, is not a simple type. Nor is it simply an array of
[Link]. Rather,String defines an object, and a full description of it requires an understanding of
several objectrelated features. However, so that you can use simple strings in example programs,the
following brief introduction is in [Link] String type is used to declare string variables. You can also
declare arrays of strings.A quoted string constant can be assigned to a String variable. A variable of type
String can be assigned to another variable of type String. You can use an object of type String as an
argument to println(
).