0% found this document useful (0 votes)
2 views40 pages

Oops Module1 Chapter1

The document provides an overview of Java, detailing its evolution from C and C++ and the introduction of object-oriented programming to manage complexity. It highlights Java's key features such as security, portability, and the use of bytecode for execution on various platforms, which allows for dynamic and distributed programming. Additionally, it discusses Java applets and servlets, emphasizing their roles in enhancing web functionality and the importance of Java's design in ensuring reliability and performance.

Uploaded by

vijetha.cbit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views40 pages

Oops Module1 Chapter1

The document provides an overview of Java, detailing its evolution from C and C++ and the introduction of object-oriented programming to manage complexity. It highlights Java's key features such as security, portability, and the use of bytecode for execution on various platforms, which allows for dynamic and distributed programming. Additionally, it discusses Java applets and servlets, emphasizing their roles in enhancing web functionality and the importance of Java's design in ensuring reliability and performance.

Uploaded by

vijetha.cbit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

OOPS WITH JAVA – BCS306A Module1

Module 1
Chapter 1
An overview of Java

The Birth of Modern Programming: C


The C language shook the computer world. Its impact should not be underestimated,
because it fundamentally changed the way programming was approached and thought
about.
As you probably know, when a computer language is designed, trade-offs are often
made, such as the following:
➢ Ease-of-use versus power
➢ Safety versus efficiency
➢ Rigidity versus extensibility
Prior to C, programmers usually had to choose between languages that optimized
one set of traits or the other. For example, although FORTRAN could be used to
write fairly efficient programs for scientific applications, it was not very good for
system code.
while BASIC was easy to learn, it wasn’t very powerful, and its lack of structure made
its usefulness questionable for large programs.
Assembly language can be used to produce highly efficient programs, but it is not
easy to learn or use effectively. Further, debugging assembly code can be quite
difficult.
Another compounding problem was that early computer languages such as BASIC, COBOL, and
FORTRAN were not designed around structured principles.
The creation of C is considered by many to have marked the beginning of the modern age of computer
languages.

C++: The Next Step


• During the late 1970s and early 1980s, C became the dominant computer programming
language, and it is still widely used today.
• Since C is a successful and useful language, you might ask why a need for something
else existed. The answer is complexity.
• Throughout the history of programming, the increasing complexity of programs has
driven the need for better ways to manage that complexity.
• C++ is a response to that need. To better understand why managing program complexity
is fundamental to the creation of C++, consider the following.
• The first widespread language was, of course, FORTRAN. While FORTRAN was an
impressive first step, it is hardly a language that encourages clear and easy-to-
understand programs. The 1960s gave birth to structured programming.

Dept. of AI & ML, CBIT-Kolar Page 1


OOPS WITH JAVA – BCS306A Module1

• 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

Dept. of AI & ML, CBIT-Kolar Page 2


OOPS WITH JAVA – BCS306A Module1

• 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++.

The Creation of Java

➢ 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.

How Java Changed the Internet


Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the Internet
andautomatically executed by a Java-compatible web browser.
An applet is downloaded on demand, without further interaction with the user. If
the user clicks a link that contains an applet, the applet will be automatically
downloaded and run inthe browser. Applets are intended to be small programs.
They are typically used to display data provided by the server, handle user input, or provide
simplefunctions, such as a loan calculator, that execute locally, rather than on the server.
In essence, the applet allows some functionality to be moved from the server to the client.
The creation of the applet changed Internet programming because it expanded the universe of
objects thatcan move about freely in cyberspace.
In general, there are two very broad categories of objects that are transmitted between the server
and the
cEAs desirable as dynamic, networked programs are, they also present serious problems in the
areas of security and portability.
A program that downloads and executes automatically on the client computer must be prevented
fromdoing harm.
It must also be able to run in a variety of different environments and under different operating
systems.

Dept. of AI & ML, CBIT-Kolar Page 3


OOPS WITH JAVA – BCS306A Module1

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.

Java’s Magic: The Bytecode


The key that allows Java to solve both the security and the
portability problems just described isthat 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 executedby the Java run-time
system, which is called the Java Virtual Machine (JVM).
In essence, the original JVM was designed as an interpreter for bytecode.
This may come as a bit of a surprise since many modern
languages are designed to be compiledinto executable code
because of performance concerns. Translating a Java
program into bytecode makes it much easier to run a
program in a widevariety of environments because only the
JVM needs to be implemented for each platform.
Once the run-time package exists for a given system, any Java program can run on it.
The JVM will differ from platform to platform, all understand the same Java
bytecode. If a Java program were compiled to native code, then different versions of
the same programwould have to exist for each type of CPU connected to the
Internet.
The execution of bytecode by the JVM is the easiest way to create truly portable programs.
The fact that a Java program is executed by the JVM also helps to make it secure.

Because the JVM is in control, it can contain the program and prevent it from generating
sideeffects outside of the system.

Dept. of AI & ML, CBIT-Kolar Page 4


OOPS WITH JAVA – BCS306A Module1

Although Java was designed as an interpreted language,


there is nothing about Java thatprevents on-the-fly
compilation of bytecode into native code in order to boost
performance.
Java supports provides a Just-In-Time (JIT) compiler for
bytecode. When a JIT compiler is part of the JVM,
selected portions of bytecode are compiled intoexecutable code in real time, on a
piece-by-piece, demand basis.

By using JIT compiler java code will execute fastly.

Servlets: Java on the Server Side


• As useful as applets can be, they are just one half of the client/server equation.

• 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.

Dept. of AI & ML, CBIT-Kolar Page 5


OOPS WITH JAVA – BCS306A Module1

• The only requirements are that the server support the JVM and a servlet container.

The Java Buzzwords/Features


The key considerations were summed up by the Java team in the following list of
buzzwords:
1) Simple
2) Secure
3)Portable
4)Object
oriented
5)Robust
6)Multithread
7)Architecture
neutral
8)Interpreted
9)High
performance
10)Distributed
11)Dynamic

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.

Dept. of AI & ML, CBIT-Kolar Page 6


OOPS WITH JAVA – BCS306A Module1

• 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.

Dept. of AI & ML, CBIT-Kolar Page 7


OOPS WITH JAVA – BCS306A Module1

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.

8) Interpreted and High Performance


• Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode.
• This code can be executed on any system that implements the Java Virtual Machine.
• Most previous attempts at cross-platform solutions have done so at the expense of
performance.
• The Java bytecode was carefully designed so that it would be easy to translate directly into
nativemachine code for very high performance by using a just-in-time compiler.
• Java run-time systems that provide this feature lose none of the benefits of the platform-
independentcode.

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.

Dept. of AI & ML, CBIT-Kolar Page 8


OOPS WITH JAVA – BCS306A Module1

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.

Dept. of AI & ML, CBIT-Kolar Page 9


Module1

OOPS WITH JAVA – BCS306A

1.1 Object-Oriented Programming


1) Abstraction
• An essential element of object-oriented programming is abstraction.
• For 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
thecomplexity of the parts that form the car

• 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.

The Three OOP Principles


They are encapsulation, inheritance, and polymorphism.
1) Encapsulation
• Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both
safe from outside interference and misuse.
• One way to think about 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.
• A class defines the structure and behavior (data and code) that will be shared by a set of objects.
• Each object of a given class contains the structure and behavior defined by the class,objects are
sometimes referred toas instances of a class.
• A class is a logical construct
• An object has physical reality.
• When you create a class, you will specify the code and data that constitute that class.
• These elements are called members of the class.
• The data defined by the class are referred to as member variables or instance variables.
• 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
mayknow.
• The private methods and data can only be accessed by code that is a member of the class.
OOPS WITH JAVA – BCS306A Module1

• 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.

1.2 A First Simple Program


Let’s start by compiling and running the short sample program shown here.
/*
This is a simple Java [Link]
this file "[Link]".
*/ class
Example
{
//Your program begins with a call to main().
public static void main(String args[])
{
[Link]("This is a simple Java program.");
}
}

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.

C:\>java Example The following output is displayed:

This is a simple Java program.


• When Java source code is compiled, each individual class is put into its own output file named after the
classand using the .class extension.
• This is why it is a good idea to give your Java source files the same name as the class they contain—the name
of the source file will match the name of the .class file.
When you execute java as just shown, you are actually specifying the name of the class that you want to
execute.
• It will automatically search for a file by that name that has the .class extension.
• If it finds the file, it will execute the code contained in the specified class.

The program begins with the following lines:

/*
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

// Your program begins with a call to main().

This is the second type of comment supported by Java.


A single-line comment begins with a // and ends at the end of the line.
As a general rule, programmers use multiline comments for longer remarks and single-
linecomments for brief, line-by-line descriptions.
The third type of comment, a documentation comment, will be discussed in the
“Comments”. The next line of code is shown here:

public static void main(String args[]) {

This line begins the main( ) method.


All Java applications begin execution by calling main( ).
The public keyword is an access specifier, which allows the programmer to control the
visibility of classmembers.
When a class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared. (The opposite of
public is private, which prevents a member from being used by code defined
outside of its class.)
In this case, main( ) must be declared as public, since it must be called by code
outside of its class when the program is started.

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( ).

[Link]("This is a simple Java program.");

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 line begins with [Link].


System is a predefined class that provides access to the system, and out is the output
stream that isconnected to the console.
Notice that println( ) statement ends with semicolon.

The first } in the program ends main( ), and the last } ends the Example class definition.

1.3 A Second Short Program


/*
Here is another short example. Call this
file "[Link]".
*/
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);
}
}

You will see the following output:

This is num: 100


The value of num * 2 is 200
Let’s take a close look at why this output is generated. The first new line in the program
isshown here:
int num; // this declares a variable called num

Following is the general form of a variable declaration:

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

• Here, condition is a Boolean expression.


• If condition is true, then the statement is executed.
• If condition is false, then the statement is

• [Link] is an example:

if(num < 100)


[Link]("num is less than 100");

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.

Call this file "[Link]".


*/
class IfSample
{ public static void main(String args[])
{
int x, y;
x = 10;
y = 20;
if(x < y)
[Link]("x is less than y");
x = x * 2; if(x == y)
[Link]("x now equal to y");
x = x * 2; if(x > y)
[Link]("x now greater than y");
// this won't display anything
if(x == y)
[Link]("you won't see this");
}
}
OOPS WITH JAVA – BCS306A Module1

Output: x is less than yx now


equal to y x now
greater than y

2) The for Loop


• The loop statements are an important part of nearly any programming language.
• Java supplies a powerful assortment of loop constructs.
• The simplest form of the for loop is shown here:

Syntax: for(initialization; condition; iteration) statement;

• 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

2.1 Using Blocks of Code


Java allows two or more statements to be grouped into blocks of code,also called code [Link]
is done by enclosing the statements between opening and closing curly braces. Once a block of
code has been created, it becomes a logical unit that can be used any place that a single statement
can.
For example, a block can be a target for Java’s if and for statements.
Consider this if statement: if(x < y){ // begin a block x = y; y = 0;
} // end of block
Here, if x is less than y, then both statements inside the block will be executed. Thus, the two
statements inside the block form a logical unit, and one statement cannot execute without the other
also executing. The key point here is that whenever you need to logically link two or more
statements, you do so by creating a block. Let’s look at another example.

The following program uses a block of code as the target of a for


loop. /*Demonstrate a block of [Link] this file "[Link]"*/
class BlockTest
{
public static void main(String args[])
{ int x,
y;
y = 20;// the target of this loop is a block
for(x=0;x<10;x++)
{
[Link]("This is x: " + x);
[Link]("This is y: " + y); y
= y - 2;
}
}
}
Output: This is x: 0
This is y: 20
This is x: 1
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
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.3 Lexical Issues


• Java programs are a collection of whitespace, identifiers, literals, comments,
operators,separators, and keywords.
• The operators are described in the next chapter.
1) Whitespace
• Java is a free-form language.
• This means that you do not need to follow any special indentation rules.
• There was at least one whitespace character between each token that was not
alreadydelineated by an operator or separator.
• In Java, whitespace is a space, tab, or newline.

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

AvgTemp count a4 $test this_is_ok


Invalid identifier names include these:

2count high-temp Not/ok

3) Literals
A constant value in Java is created by using a literal representation of it. For example, here
aresome literals:

100 98.6 'X' "This is a test"

• Left to right, the first literal specifies an integer.


OOPS WITH JAVA – BCS306A Module1

• The next is a floating-point value.


• The third is a character constant
• The last is a string. A literal can be used anywhere a value of its type is allowed.

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:

Symbo Name Purpose


l
() Parentheses Used to contain lists of parameters in method definition and
invocation.
Also used for defining precedence in expressions,
containing expressions in control statements, and
surrounding cast types.
{} Braces Used to contain the values of automatically initialized arrays.
Also used to define a block of code, for classes, methods, and
local scopes.
[] Brackets Used to declare array types. Also used when dereferencing
array values.
; Semicolon Terminates statements.
, Comma Separates consecutive identifiers in a variable declaration.
Also used to chain statements together inside a for statement.
. Period Used to separate package names from subpackages and classes.
Also

used to separate a variable or method from a reference variable.

6) The Java Keywords


OOPS WITH JAVA – BCS306A Module1

• There are 50 keywords currently defined in the Java language.


• These keywords, combined with the syntax of the operators and separators, form thefoundation
of the Java language.
• These keywords cannot be used as names for a variable, class, or method.

• In addition to the keywords, Java reserves the following: true, false, and null. These are values
defined by Java.

Abstract continue for new Switch


Assert default goto package Synchronized
Boolean do if private This
Break double implements protected Throw
Byte else import public Throws
Case enum instanceof return Transient
Catch extends int short Try
Char final inter face static Void
Class finally long strictfp Volatile
Const float native super While

TABLE Java Keywords

2.4 The Java Class Libraries


The sample programs shown in this chapter make use of two of Java’s built-in methods:println( ) and print(
).

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.

3. Data Types,Variables and Arrays


OOPS WITH JAVA – BCS306A Module1

3.1 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. 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.

3.2 The Primitive Types


• 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, and both terms will be used in
this [Link] 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
fractionalprecision.
• 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.
3.3 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.
Many other computer languages support both signed and unsigned integers. \
The width and ranges of these integer types vary widely, as shown in this table:
OOPS WITH JAVA – BCS306A
OOPS WITH JAVA – BCS306A Module1

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

• The smallest integer type is byte.


• This is a signed 8-bit type that has a range from –128 to 127.
• 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.
class Light
{ public static void main(String args[])
{ int lightspeed;
long days;
long seconds;
long distance;
//approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds distance
= lightspeed * seconds; // compute distance
[Link]("In " + days);
[Link](" days light will travel about ");

Dept. of AI & ML, CBIT-Kolar Page 22


Module1

[Link](distance + " miles.");


}
}

This program generates the following output:

In 1000 days light will travel about 16070400000000 miles.

3.4 Floating-Point Types


Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractionalprecision.
For example, calculations such as square root, or transcendentals such as sine and cosine, result in
a value whoseprecision requires a floating-point type.
There are two kinds of floating-point types, float and double, which represent single- and double-
precisionnumbers, respectively. Their width and ranges are shown here:

Name Width in Bits Approximate Range


Double 64 4.9e–324 to 1.8e+308
Float 32 1.4e–045 to 3.4e+038

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:

float hightemp, lowtemp;


OOPS WITH JAVA – BCS306A Module1

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:

Compute the area of a circle. class Area


{ public static void main(String args[])
{ double pi, r, a;
r = 10.8; // radius of circle pi = 3.1416; // pi,
approximately a = pi * r * r; // compute area
[Link]("Area of circle is " + a);
}
}

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:

//Demonstrate char data type.


class CharDemo

Dept. of AI & ML, CBIT-Kolar Page 24


OOPS WITH JAVA – BCS306A Module1

{ public static void main(String args[]) {


char ch1, ch2;
ch1ch2 == 'Y';88; // code for X
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}

}
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.

//char variables behave like integers.


class CharDemo2
{ public static void main(String args[]) {
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1); ch1+
+; // increment ch1
[Link]("ch1 is now " + ch1);
}
}

The output generated by this program is shown here:

ch1 contains X ch1


is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented.
This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.

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:

//Demonstrate boolean values.

class BoolTest
{ public static void main(String args[])
{ boolean b; b =
false;

Dept. of AI & ML, CBIT-Kolar Page 25


OOPS WITH JAVA – BCS306A Module1

[Link]("b is " + b);


b = true;
[Link]("b is " + b);
// a boolean value can control the if statement
if(b)
[Link]("This is executed.");
b = false;
if(b)
[Link]("This is not executed.");
//outcome of a relational operator is a boolean value
[Link]("10 > 9 is " + (10 > 9));
}
}

The output generated by this program is shown here:


b is false b is true This is executed.
10 > 9 is true

3.7 A Closer Look at Literals


Integer Literals
Integers are probably the most commonly used type in the typical program.
Any whole number value is an integer literal.
Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a
base 10number.
Octal values are denoted in Java by a leading zero.
Integer literals create an int value, which in Java is a 32-bit integer value.
An integer literal can always be assigned to a long variable.
However, to specify a long literal, you will need to explicitly tell the compiler that the literal value is
of type long.
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component.
They can be expressed in either standard or scientific notation.
Standard notation consists of a whole number component followed by a decimal point followed by
a fractionalcomponent.
For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers.
Floating-point literals in Java default to double precision.
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 theaddition and subtraction operators.

Dept. of AI & ML, CBIT-Kolar Page 26


OOPS WITH JAVA – BCS306A Module1

• 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] ...] ;

The type is one of Java’s data types,


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.
Here are several examples of variable declarations of various types. Note that some
include aninitialization.

int a, b, c; // declares Three ints, a, b, and c.


int d = 3, e, f = 5; // declares Three more ints, initializing
// d and f. byte z = 22; // initializes z. double pi = 3.14159; //
declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

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);

Dept. of AI & ML, CBIT-Kolar Page 27


OOPS WITH JAVA – BCS306A Module1

[Link]("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 computethe square root of its argument.

The Scope and Lifetime of Variables A


block defines a scope.
Each time you start a new block, you are creating a new scope.
A scope determines what objects are visible to other parts of your program. It also
determines the lifetime ofthose objects.
Many other computer languages define two general categories of scopes: global and
local.
The scope defined by a method begins with its opening curly brace.
As a general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is definedoutside that scope.
Scopes can be nested. For example, each time you create a block of code, you are
creating a new, nested scope.

//Demonstrate block scope.


class Scope
{ public static void main(String args[])
{ int x; // known to all code within mainx = 10; if(x
== 10)
{
// start new scope
int y = 20; // known only to this block
//x and y both known here.

[Link]("x and y: " + x + " " + y); x = y * 2;


} y = 100; // Error! y not known here x is still known
here. [Link]("x is " + x); }
}
As the comments indicate, the variable x is declared at the start of main( )’s scope and
is accessible to allsubsequent code within main( ).
Within the if block, y is declared. Since a block defines a scope, y is only visible to
other code within its block.
This is why outside of its block, the line y = 100; is commented out.

3.9 Type Conversion and Casting


If the two types are compatible, then Java will perform the conversion automatically.
For example, it is always possible to assign an int value to a long variable.

Dept. of AI & ML, CBIT-Kolar Page 28


OOPS WITH JAVA – BCS306A Module1

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.

Java’s Automatic Conversions


When one type of data is assigned to another type of variable, an automatic type conversion
will takeplace if the following two conditions are met:
✓ The two types are compatible.
✓ The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place.
For example, the int type is always large enough to hold all valid byte values, so
no explicit caststatement is required.
For widening conversions, the numeric types, including integer and
floating-point types, arecompatible 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.
Casting Incompatible Types
For example, what if you want to assign an int value to a byte variable?
This conversion will not be performed automatically, because a byte is
smaller than an int. This kind of conversion is sometimes called a
narrowing conversion, since you are explicitly making thevalue narrower
so that it will fit into the target type. To create a conversion between two
incompatible types, you must use a cast. A cast is simply an explicit type
conversion. It has this general form:
Syntax:
(target-type) value

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.

Integers do not have fractional components.

Dept. of AI & ML, CBIT-Kolar Page 29


OOPS WITH JAVA – BCS306A Module1

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);

[Link]("\nConversion of double to int.");


i = (int) d;
[Link]("d and i " + d + " " + i);
[Link]("\nConversion of double to byte.");
b = (byte) d;
} [Link]("d and b " + d + " " + 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

3.5 Automatic Type Promotion in Expressions


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 sub expression 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 [Link] useful as the automatic promotions are, they can cause confusing
compile-time [Link] example, this seemingly correct code causes a problem:

Dept. of AI & ML, CBIT-Kolar Page 30


OOPS WITH JAVA – BCS306A Module1

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 [Link],
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 [Link] 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.

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);

[Link]((f * b) +" + " + (i / c) + " - " + (d*s));


[Link]("result = " + result);
}
}
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the
subexpression is float.
Next, in the subexpression i / c, c is promoted to int, and the result is of type int.
Then, in d * s, the value of s is promoted to double, and the type of the
subexpression is double. Finally, these three intermediate values, float,
int, and double, are considered. The outcome of float plus an int is a float.

Dept. of AI & ML, CBIT-Kolar Page 31


OOPS WITH JAVA – BCS306A Module1

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.

Two types of Arrays


1) One-Dimensional Arrays
2)Multi- Dimensional Arrays

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[])
{

Dept. of AI & ML, CBIT-Kolar Page 32


OOPS WITH JAVA – BCS306A Module1

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.

Dept. of AI & ML, CBIT-Kolar Page 33


OOPS WITH JAVA – BCS306A Module1

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.

int twoD[][] = new int[4][5];

• 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.

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

Dept. of AI & ML, CBIT-Kolar Page 34


OOPS WITH JAVA – BCS306A Module1

15 16 17 18 19
You can allocate the remaining dimensions

FIGURE :A conceptual view of a 4 by 5, two-dimensional array

Dept. of AI & ML, CBIT-Kolar Page 35


OOPS WITH JAVA – BCS306A Module1

For example, this following code allocates memory for the first dimension of twoD when it is
declared. Itallocates the second dimension manually.

int twoD[][] = new int[4][]; twoD[0] = new


int[5]; twoD[1] = new int[5]; twoD[2] = new
int[5]; twoD[3] = new int[5];

Example:

//Manually allocate differing size second dimensions.


class TwoDAgain
{ public static void main(String args[])
{ int twoD[][] = new int[4][];
twoD[0] = newint[1];
twoD[1] = new int[2];
twoD[2] = newint[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++)
{
twoD[i][j] = k; k+
+;
}
for(i=0; i<4; i++)
{ for(j=0; j<i+1; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
This program generates the following output:
0
2
45
789
The array created by this program looks like this:
- 2020-21 Page 37

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

OOPS WITH JAVA – BCS306A Module2

00000
00000

00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16 0 6
12 18 24

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:
type[ ]var-name;
Here, the square brackets follow the type specifier, and not the name of the array [Link] example, the
following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4]; char[]
[] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the same time.

For example, int[] nums, nums2, nums3; // create


three arrays
creates three array variables of type int. It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type for a method
Here,str is an object of type String. It is assigned the string “this is a test”. This string is displayed by the
println( ) statement
3.7 A Few Words About Strings

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(
).

For example, consider the following fragment: String


str = "this is a test";
[Link](str);

You might also like