• No results found

JAVA

N/A
N/A
Protected

Academic year: 2021

Share "JAVA"

Copied!
175
0
0

Loading.... (view fulltext now)

Full text

(1)

SYLLABUS

Basic concepts of Object Oriented Programming, Genesis of java, History of java, Features of java, Java Virtual Machine (JVM), Difference between java and C++, Java Tokens, Variables and Operators, Array, Conditional Statements, Control Statements. Garbage Collector

Classes and Objects, Assess Specifier, Constructor, Subclasses, Inheritance, Abstract Class, Packages and Interfaces, Exception Handling, Applet Programming, AWT package, Layout, Swings, Java Streams, JDBC, Multithreading, Java.Util package

(2)

Table of Content UNIT 1: Concepts of Object Oriented Programming 1. Basics of OOP’s

1.1Introduction

1.2Object Oriented Paradigm

1.3Basic concepts of Object Oriented Programming 1.3.1 Object

1.3.2 Classes

1.3.3 Data Abstraction and Encapsulation 1.3.4 Inheritance

1.3.5 Polymorphism

UNIT 2: Fundamentals of Java Language 1. Introduction to Java 2.1 Genesis of Java 2.2 Why Java? 2.3 History of Java 2.4 Oak 2.5 Java Feature 2.5.1 Simple 2.5.2 Secure 2.5.3 Portable 2.5.4 Object Oriented 2.5.5 Interpreted 2.5.6 Robust 2.5.7 Multithreaded 2.5.8 Interpreted

2.5.9 Dynamic and Distributed

2.5.10 Architecture Nature and Portable 2.6 Difference between java and C++

2.7 The Java Virtual Machine 2.8 Java Program Structure 2.9 Java Token 2.9.1 Identifiers 2.9.2 Keywords 2.9.3 Literals 2.9.4 Operators 2.9.5 Separators 2.10Comments 2.11White Space 2.12Constants

2.13Backslash Character Constant UNIT 3: Variables and Operators

3.1Variables

3.2Data Types in java 3.3Scope of Variables

(3)

3.4Array 3.4.1 One-Dimensional Array 3.4.2 Two-Dimensional Array 3.5Strings 3.6Operators 3.6.1 Arithmetic Operators 3.6.2 Assignment Operators 3.6.3 Conditional Operators 3.6.4 Special Operators 3.6.5 Relational Operators 3.6.6 Boolean Logical Operators

3.6.7 Incrementing and Decrementing Operators 3.6.8 Bitwise Operators

3.7Operator Precedence UNIT 4: Control Statements

4.1Selection Statements 4.1.1 If

4.1.2 If ..Else

4.1.3 If..Else if .. else 4.2The Switch Statement 4.3Iteration Statement

4.3.1 The while Statement 4.3.2 The do Statement 4.3.3 The for Statement 4.4The Comma Operator

4.5The break Statement 4.6The continue Statement UNIT 5: Classes and Objects

5.1Classes

5.1.1 The class Declaration

5.1.2 Declaring a class’s Superclass

5.1.3 Listing the interface implemented by a class 5.1.4 Summary of a class Declaration

5.2Declaring Member Variables 5.3Declaring Constants

5.4The Method Declaration

5.5Object Creation and Constructors 5.5.1 Object Creation

4.5.2 Constructor

5.6Controlling access to member of a class 5.6.1 Private

5.6.2 Protected 5.6.3 Public

5.7Subclasses and Inheritance 5.7.1 Definition

5.7.2 Creating Subclasses 5.8Overriding Methods

5.9Final classes and Methods 5.9.1 Final Classes

(4)

5.9.2 Final Methods 5.10 Abstract classes and Methods

5.10.1 Abstract classes 5.10.2 Abstract Methods UNIT 6: Packages and Interfaces

6.1Packages

6.1.1 How to create your own packages 6.2Classpath

6.3The meaning of static

6.4Cleanup: Finalization and Garbage collection 6.5Forcing Finalization and Garbage collection 6.6Interfaces

6.6.1 What is an interface 6.6.2 The interface Declaration

6.6.3 Multiple Extension (Inheritance) 6.6.4 Implementing an interface 6.6.5 Using an interface as a type 6.6.6 Interfaces verses abstract classes UNIT 7: GUI Programming

7.1Introduction to Applet Programming 7.2What are Applets

7.2.1 What applet can do 7.2.2 What applet can not do 7.3Types of an Applet

7.3.1 Local Applet 7.3.1.1 Remote Applet 7.4Lifecycle of an Applet

7.5Passing parameters to an Applet

UNIT 8: Programming the Abstract Windowing Toolkit (AWT) 8.1Introduction of AWT

8.2AWT Component Hierarchy

8.3How to Add a Component to a Container 8.4AWT Component 8.4.1 Labels 8.4.2 Buttons 8.4.3 Checkbox 8.4.4 TextFields 8.4.5 TextAreas 8.4.6 Choice lists 8.4.7 Scrolling Lists 8.5Event Handling 8.5.1 Introduction

2.5.2 Event Listener Interfaces 8.6How to implement event handlers:

8.6.1 Buttons 8.6.2 Canvases 8.6.3 Checkboxes

(5)

8.6.4 Choices 8.6.5 Lists 8.6.6 ScrollPanes 8.6.7 TextComponent 8.6.8 Menus 8.7AWT Containers 8.7.1 Frames 8.7.2 Panels 8.7.3 Dialogs 8.8Layouts

8.8.1 The FlowLayout Class 8.8.2 The BoderLayout Class 8.8.3 The GridLayout Class 8.8.4 The GridBagLayout Class 8.8.5 The CardLayout class

8.8.6 Combining Layouts with Nested Panels 8.9Using Adapters to Handle Events

UNIT 9: JFC AND SWING COMPONENT 9.1Introduction

9.2Difference between AWT and Swing Components 9.3Overview of Jcomponent

9.4All about Controls (JComponents) 9.4.1 JApplet Example

9.4.2 JFrame

9.4.3 Changing the Look and Feel (LAF) 9.4.4 Jlabel 9.4.5 JButton 9.4.6 New Feature in JDK 1.2.2 9.4.7 JtoolTip 9.4.8 JtextField 9.4.9 JcheckBox 9.4.10 Jpanel 9.4.11 JSlider Basics

UNIT 10: Advance Programming Element Java Streams 10.1What is Stream 10.2Byte Stream 10.2.1 File Stream 10.2.2 Data Stream 10.3 Character Streams

10.3.1 Reading Text Files 10.3.2 Writing Text Files UNIT 11: Exception Handling

11.1Introduction

(6)

11.3Try/catch

11.4The finally clause 11.5The throws clause 11.6The throw clause 11.7User Define Exception

UNIT 12: Java Database Connectivity 12.1 Getting started with JDBC 12.2 What is JDBC

12.3 JDBC Architecture

12.4 JDBC API Interface in a Nutshell 12.4.1 Driver Manager 12.4.2 Connection 12.4.3 Statement 12.4.4 Resultset 12.4.5 CallabelStatement 12.4.6 DatabaseMetaData 12.4.7 Driver 12.4.8 PreparedStatement 12.4.9 ResultSetMetaData 12.4.10DriverPropertyInfo 12.4.11Date 12.4.12Time 12.4.13TimeStamp 12.4.14Types 12.4.15Numeric 12.4.16Driver Interface 12.5 Application Area 12.6 Getting to Work

12.6.1 How to configure ODBC Driver 12.6.2 Connecting to a database 12.6.3 Executing database Queries 12.7 The Statement clause

12.8 The ResultSet class

12.9 More Complex Uses of JDBC

12.9.1 The PreaparedStatement class 12.9.2 The CallableStatement class 12.10Working with Multiple Database

12.11“DNSLess” Connection with the JDBC-ODBC “Bridge” Driver 12.11.1.1 MS Access Example

12.11.1.2 ODBC Driver for Oracle(from Oracle) 12.11.1.3 ODBC Driver for Oracle(from Microsoft) 12.11.1.4 ODBC Driver for Excel

UNIT 13: Multithreaded Application 13.1Introduction of Multithreading 13.2What is a Thread

13.3Creating New Threads

13.3.1 Subclassing the Thread class 13.4Implementing the Runnable Interface 13.5Thread States

(7)

13.6The Thread API

13.7Scheduling and Priority

13.7.1 Setting Thread Priority 13.7.2 Waking up a Thread

13.7.3 Suspending and Resuming Thread Execution 13.7.4 Putting a Thread to Sleep

UNIT 14: The Java.util Package 14.1Introduction

14.2The Java collection Advantage: An Overview 14.3A good API

14.4Other Capabilities 14.5Sorting a Collection 14.6Unmodifiable collection 14.7Synchronized Collection

(8)

UNIT 1: BASICS OF OOP’S

1.1 Introduction

1.2 Object Oriented Paradigm

1.3 Basic concepts of Object Oriented Programming 1.3.1 Object

1.3.2 Classes

1.3.3 Data Abstraction and Encapsulation 1.3.4 Inheritance

1.3.5 Polymorphism

1.1 Introduction

The object-oriented paradigm was first conceived in the 1960's and implemented in languages such as SIMULA-67. One of the initial concerns with early object-oriented languages was their efficiency. Programs written using structured languages, such as Pascal and C, executed faster than programs written using early object-oriented languages. Although programs which used the object-oriented paradigm were more extensible and easier to maintain from a programmer's point of view, an unacceptable price had to be paid in the program's runtime behaviour. Recently, however, the runtime execution of object-oriented programs has improved considerably. This has been due in part to both the development of faster hardware and the creation of efficient languages and compilers which support object-oriented programming, such as C++. These facts, in addition to the ever-increasing accessibility of object-oriented languages to the common programmer has created a major evolution in the area of software development.

There is, as yet, no universally agreed upon definition of exactly what constitutes object-oriented programming. Booch suggests:

“Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.''

From this definition, one can infer that object-oriented programming consists of instantiating a number of objects which communicate with one another so as to achieve some desired behaviour. This paradigm is natural with how humans see the world; as a series of cause-effect relationships, where an action performed on one object has effects on the objects with which it communicates.

1.2 Object Oriented Paradigm

The major objectives of object-oriented approach are to eliminate some of the flaws encountered in the procedural approach. OOP treat data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it and protect it from unintentional

(9)

modification by other functions. OOP allows us to decompose a problem into a number of entities called Object and then build data and function (known as methods in java) around these entities. The combination of data and methods make up an object.

The data of an object can be accessed only by the methods associated with that object. However, methods of one object can access the methods of other objects. Some of the features of object-oriented paradigm are:

• Emphasis is on data rather than procedure.

• Programs are divided into what are known as Objects.

• Data structures are designed such that they characterized the objects.

• Methods that operate on the data of an object are tied together in the data structure.

• Data is hidden and cannot be accessed by external functions.

• Objects may communication with each other through methods.

• New data and methods can be easily added whenever necessary.

1.3 Basic concepts of Object Oriented Programming 1.3.1 Object

Objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: your dog, your desk, your television set, your bicycle.

These real-world objects share two characteristics: They all have state and behavior. For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Bicycles have state (current gear, current pedal cadence, two wheels, and number of gears) and behavior (braking, accelerating, slowing down, and changing gears). Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function (subroutine) associated with an object.

Definition: An object is a software bundle of variables and related methods.

You can represent real-world objects by using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as software object in the program that controls an electronic exercise bike. You can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.

(10)

Everything that the software object knows (state) and can do (behavior) is expressed by the variables and the methods within that object. A software object that modeled your real-world bicycle would have variables that indicated the bicycle's current state: its speed is 10 mph, its pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables are formally known as instance variables because they contain the state for a particular bicycle object, and in object-oriented terminology, a particular object is called an instance.

The following figure illustrates a bicycle modeled as a software object.

In addition to its variables, the software bicycle would also have methods to brake, change the pedal cadence, and change gears. (The bike would not have a method for changing the speed of the bicycle, as the bike's speed is just a side effect of what gear it's in, how fast the rider is pedaling, whether the brakes are on, and how steep the hill is.) These methods are formally known as instance methods because they inspect or change the state of a particular bicycle instance.

1.3.2 Classes

In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from that of other bicycles.

When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics, building many bicycles from the same blueprint. It would be very inefficient to produce a new blueprint for every individual bicycle manufactured.

In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects. A software blueprint for objects is called a

(11)

Definition: A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.

The class for our bicycle example would declare the instance variables necessary to contain the current gear, the current cadence, and so on, for each bicycle object. The class would also declare and provide implementations for the instance methods that allow the rider to change gears, brake, and change the pedaling cadence, as shown in the next figure.

After you've created the bicycle class, you can create any number of bicycle objects from the class. When you create an instance of a class, the system allocates enough memory for the object and all its instance variables. Each instance gets its own copy of all the instance variables defined in the class.

In addition to instance variables, classes can define class variables. A class variable contains information that is shared by all instances of the class. For example, suppose that all bicycles had the same number of gears. In this case, defining an instance variable to hold the number of gears is inefficient; each instance would have its own copy of the variable, but the value would be the same for every instance. In such situations, you can define a class variable that contains the number of gears. All instances share this variable. If one object changes the variable, it changes for all other objects of that type. A class can also declare class methods. You can invoke a class method directly from the class, whereas you must invoke instance methods on a particular instance.

(12)

1.3.3 Data Abstraction and Encapsulation

The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. These methods provide the interface between the object’s data and program. The insulation of data from direct access by the program is called data hiding. Encapsulation makes it possible for objects to be treated like ‘black boxes’, each performing a specific task without any concern for internal implementation.

Information “in” Information “out”

Encapsulation is like a capsule: the doctor tells you to take a medicinal capsule or pill. Far too small for you to see is the structure of the compound or molecule that does work in your bloodstream or organs to cure your disease. You don't even see the components of the mixture, which might be white medicine mixed with, say green flour. The complexity is hidden from you. Your orders are simple and external to the encapsulation: take one green pill each day with water.

Encapsulation is like a black box. When you purchase a television set, you do not need to know the details of the electronics inside (raster-scanning cathode ray tube with magnetic electron gun, alternating current transformer, hundreds of capacitors, thousands of transistors). Instead, you only need to know how to plug in the UNIT, attach the cable, turn the on switch, and press buttons on the remote control. You have a UNIT that sends visual and audio messages to you, and you do not care about the hidden actions within the unit.

Abstraction

Refers to the act of representing essential features without including the background details or explanations.

1.3.4 Inheritance

Data and Method

(13)

Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals.

Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, racing bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all

subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, racing bikes, and tandems. This relationship is shown in the following figure.

Each subclass inherits state (in the form of variable declarations) from the superclass. Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems share some behaviors: braking and changing pedaling speed, for example. However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio.

Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could use those new gears.

You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. In general, the farther down in the hierarchy a class appears, the more specialized its behavior. The Object class is at the top of class hierarchy, and each class is its descendant (directly or indirectly). A variable of type Object can hold a reference to any object, such as an instance of a class or an array. Object provides behaviors that are required of all objects running in the Java Virtual Machine. For example, all classes inherit Object's toString method, which returns a string representation of the object.

Inheritance offers the following benefits:

• Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.

• Programmers can implement superclasses called abstract classes that define "generic" behaviors. The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

(14)

1.3.5 Polymorphism

Polymorphism is the combination of the two Greek world, poly i.e. many and morphism i.e. forms, means the ability to take more than one form. For example, an operation may exhibit different behavior in different instance. The behavior depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are string, then the operation would produce a third string by concatenation.

(15)

UNIT 2 : INTRODUCTION TO JAVA Introduction to Java 2.1Genesis of Java 2.2Why Java? 2.3History of Java 2.4Oak 2.5Java Feature 2.5.1 Simple 2.5.2 Secure 2.5.3 Portable 2.5.4 Object Oriented 2.5.5 Interpreted 2.5.6 Robust 2.5.7 Multithreaded 2.5.8 Interpreted

2.5.9 Dynamic and Distributed

2.5.10 Architecture Nature and Portable 2.6Difference between java and C++

2.7The Java Virtual Machine 2.8Java Program Structure 2.9Java Token 2.9.1 Identifiers 2.9.2 Keywords 2.9.3 Literals 2.9.4 Operators 2.9.5 Separators 2.10Comments 2.11White Space 2.12Constants

2.13Backslash Character Constant

2.1 Genesis of Java

Java is related to C++, which is a direct descendent of C. Much of the character of Java is inherited from these two languages. From C, Java derives its syntax. Many of Java's object oriented features were influenced by C++.

By the end of the 1980's and early 1990's object oriented programming using C++ took hold. It seemed that programmers had finally found the perfect language but there were forces brewing that would drive the computer language evolution forward. These forces were the World Wide Web and the Internet.

As stated earlier in these notes, in 1990 a group at SUN Microsystems developed Java. In some sense Java is what C++ might have been if it was not required to be backward compatible with C. Java was originally called Oak but that turned out to be a copyrighted name so after some brainstorming they chose the name Java. It doesn't really mean Just another Vague Acronym.

(16)

The original motivation of Java was not the Internet but was the need for a platform independent language. This platform independence is exactly what is needed for Internet programming. The Internet helped push Java to the forefront of programming and Java in turn has a profound effect on the Internet.

Java has gone through two major upgrades from the original version 1.0.2 to version 1.1 and now to version 1.2 (also called Java 2). There are major changes in the language between the versions.

2.2 Why Java?

In one of their early papers about the language, Sun described Java as follows:

Java: a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language.

Even though this is quite a string of buzzwords, they aptly describe the language.

2.3 History of Java

At first glance, it may appear that Java was developed specifically for the World Wide Web. However, interestingly enough, Java was developed independently of the web, and went through several stages of metamorphosis before reaching its current status of de facto programming language for the World Wide Web. Below is a brief history of Java since its infancy to its current state.

2.4 Oak

Bill Joy, currently a vice president at Sun Microsystems, is widely believed to have been the person to conceive of the idea of a programming language that later became Java. In late 1970's, Joy wanted to design a language that combined the best features of MESA and C. In an attempt to re-write the UNIX operating system in 1980's, Joy decided that C++ was inadequate for the job. A better tool was needed to write short and effective programs. It was this desire to invent a better programming tool that swayed Joy, in 1991, in the direction of Sun's "Stealth Project" - as named by Scott McNealy, Sun's president.

In January of 1991, Bill Joy, James Gosling, Mike Sheradin, Patrick Naughton (formerly the project leader of Sun's OpenWindows user environment), and several other individuals met in Aspen, Colorado for the first time to discuss the ideas for the Stealth Project. The goal of the Stealth Project was to do research in the area of application of computers in the consumer electronics market. The vision of the project was to develop "smart" consumer electronic devices that could all be centrally controlled and programmed from a handheld-remote-control-like device. According to Gosling, "the goal was ... to build a system that would let us do a large, distributed, heterogeneous network of consumer electronic devices all talking to each other." With this goal in mind, the stealth group began work.

(17)

Members of the Stealth Project, which later became known as the Green Project, divided the tasks amongst themselves. Mike Sheradin was to focus on business development, Patrick Naughton was to begin work on the graphics system, and James Gosling was to identify the proper programming language for the project. Gosling, who had joined Sun in 1984, had previously developed the commercially unsuccessful NEWS windowing system as well as GOSMACS - a C language implementation of GNU EMACS. He began with C++, but soon after was convinced that C++ was inadequate for this particular project. His extensions and modifications to C++ (also know as C++ ++ --), were the first steps towards the development of an independent language that would fit the project objectives. He named the language "Oak" while staring at an oak tree outside his office window! The name "Oak" was later dismissed due to a patent search which determined that the name was copyrighted and used for another programming language. According to Gosling, "the Java development team discovered that Oak was the name of a programming language that predated Sun's language, so another name had to be chosen."

"It's surprisingly difficult to find a good name for a programming language, as the team discovered after many hours of brainstorming. Finally, inspiration struck one day during a trip to the local coffee shop" Gosling recalls. Others have speculated that the name Java came from several individuals involved in the project: James gosling, Arthur Van hoff, Andy bechtolsheim.

There were several criteria that Oak had to meet in order to satisfy the project objective given the consumer electronics target market. Given the wide array of manufacturers in the market, Oak would have to be completely platform independent, and function seamlessly regardless of the type of CPU in the device. For this reason, Oak was designed to be an interpreted language, since it would be practically impossible for a complied version to run on all available platforms. To facilitate the job of the interpreter, Oak was to be converted to an intermediate "byte-code" format, which is then passed around across the network, and executed/interpreted dynamically.

Additionally, reliability was of great concern. A consumer electronics device that would have to be "rebooted" periodically was not acceptable. Another important design objective for Oak would then have to be high reliability by allowing the least amount of programmer-introduced errors. This was the motivation for several important modifications to C++. The concepts of multiple-inheritance and operator overloading were identified as sources of potential errors, and eliminated in Oak. Furthermore, in contrast to C++, Oak included implicit garbage collection thereby providing efficient memory utilization and higher reliability. Finally, Oak attempted to eliminate all unsafe constructs used in C and C++ by only providing data structures within objects.

Another essential design criterion was security. By design, Oak-based devices were to function in a network and often exchange code and information. Inherently, security is of great concern in a networked environment, especially in an environment as network dependent as the conceived Oak-based systems. For this reason, pointers were excluded in the design of Oak. This would theoretically eliminate the possibility of malicious programs accessing arbitrary addresses in memory.

2.5 Java Feature • Simple

• Secure

(18)

• Object Oriented

• Robust

• Multithreaded

• Interpreted

• Distributed

• Architecture Neutral and Portable

2.5.1 Simple

Java was designed to be easy for the professional programmer. It is easy to learn and can be used effectively. If you are an experienced C++ programmer, moving to Java will require very little effort.

Does not use pointers. Since Java does not have structures, and strings and arrays are objects, there's no need for pointers.

Does not use goto -- instead, provide labeled Break and Continue statements, and exception handling.

Unlike C++, Java has no operator overloading, no multiple inheritance. 2.5.2 Secure

There is a concept of applets in Java, which can be downloaded without fear or virus or malicious content, because the Java programs are confined to Java execution environment and are not allowed to access other parts of the CPU.

Java programs cannot forge pointers to memory, or overflow arrays, or read memory outside of the bounds of an array or string.

Byte-code verification process, performed by interpreter on any untrusted code that it loads -- checks for stack overflows and underflows, illegal byte-codes, etc.

2.5.3 Portable

The Java programs called Applets run in the JVM (Java virtual machine) environment that is in every browser therefore the programs can run anywhere.

2.5.4 Object Oriented

Class: collection of data and methods that operate on that data Java comes with an extensive set of classes, arranged in packages.

Most things in Java are objects. The only exceptions: the primitive number, character, and boolean types.

(19)

A class is the basic unit of compilation and of execution in Java; all Java programs are classes.

2.5.5 Interpreted

The Java compiler generates byte-codes for the Java Virtual Machine (JVM), rather than native machine code.

2.5.6 Robust

Garbage collection and Exception handling make Java a robust language. In garbage collection the user doesn’t have to bother about the memory allocation as, when the object is no longer in use it is automatically deleted to release memory space.

2.5.7 Multithreaded

A single threaded application has one thread of execution running at all times and such programs can do only one task at a time. A multi-threaded application can have several threads of execution running independently and simultaneously. These threads may communicate and cooperate and will appear to be a single program to the user.

2.5.8 Interpreted

The Java code is compiled into the byte code, which is the class file. The byte code is then interpreted to the machine language by the JVM environment.

2.5.9 Dynamic and Distributed

Any class can be loaded into a running Java interpreter at any time, then dynamically instantiated. Native code libraries can also be dynamically loaded.

Classes in Java are represented by the Class class. Information about a class is available dynamically at run-time. See Reflection....

"Distributed" means lots of high-level support for networking (e.g. URL class in java.net package).

Distributed nature of Java, combined with dynamic class loading capabilities, make it possible for a Java interpreter to download and run code across the Internet.

1.5.10 Architecture Neutral and Portable "Write once, run anywhere"

(20)

No implementation-dependent aspects -- e.g. all primitive data types are defined in Java, have same byte size on all platforms.

2.6 Differences between Java and C++

• Perhaps the single biggest difference between Java and C++ is that Java does not support pointers. After examining C++ in detail we know that the pointer is one of C++'s most powerful and important language features. It is also one of the most dangerous. Pointers don't exist in Java, as their existence would violate security aspects of the language. For example, using a pointer to gain access to memory addresses outside a program's code and data a malicious program could damage the system, perform unauthorized access etc.

• In Java all object variables, arguments and return types are references. There is no need for the reference operator, &, of C++.

• In Java, assigning one object to another does not invoke an assignment operator function. Instead, assigning one object to another has the effect of associating the variable with another location in memory, much like a pointer assignment.

• Java has a streamlined approach to memory allocation. Like C++, it supports the new keyword (which returns a reference). However it does not have a delete. Instead, when the last reference to an object is destroyed (goes out of scope), the object itself is destroyed the next time garbage collection occurs. The garbage collector runs as a background process freeing up unused memory.

• Java does not support operator overloading. This is not such a big restriction as we might think. After all, it is just as easy to say u = v.add (w) as u = v + w. This is precisely the notation used when we make the matrix class within Java.

• Java does not support complex numbers and since it does not support operator overloading we can't build complex numbers ourselves as is done in C++.

• Java does not include a preprocessor nor does it support preprocessor directives. The preprocessor plays a lesser role in C++ than in C and the designers of Java felt that it was time to eliminate it entirely.

• Java does not support automatic type conversions that result in a loss of precision. • All the code in a Java program is encapsulated within one or more classes. Therefore

Java does not have what you would normally think of as global variables or functions. • Java does not allow default arguments.

• Java does not support multiple inheritance. Java does support the interface, which is similar to abstract classes in C++, and does give a form of multiple inheritance.

• Java does not support templates. In Java all classes inherit from a single class called Object so that it is not difficult to write generalized classes building on the Object class as the base type.

(21)

2.7 The Java Virtual Machine

MACHINE LANGUAGE CONSISTS of very simple instructions that can be executed directly by the CPU of a computer. Almost all programs, though, are written in high-level programming languages such as Java, Pascal, or C++. A program written in a high-level language cannot be run directly on any computer. First, it has to be translated into machine language. This translation can be done by a program called a compiler. A compiler takes a high-level-language program and translates it into an executable machine-language program. Once the translation is done, the machine-language program can be run any number of times, but of course it can only be run on one type of computer (since each type of computer has its own individual machine language). If the program is to run on another type of computer it has to be re-translated, using a different compiler, into the appropriate machine language.

There is an alternative to compiling a high-level language program. Instead of using a compiler, which translates the program all at once, you can use an interpreter, which translates it instruction-by-instruction, as necessary. An interpreter is a program that acts much like a CPU, with a kind of fetch-and-execute cycle. In order to execute a program, the interpreter runs in a loop in which it repeatedly reads one instruction from the program, decides what is necessary to carry out that instruction, and then performs the appropriate machine-language commands to do so.

One use of interpreters is to execute high-level language programs. For example, the programming language Lisp is usually executed by an interpreter rather than a compiler. However, interpreters have another purpose: they can let you use a machine-language program meant for one type of computer on a completely different type of computer. For example, there is a program called "Virtual PC" that runs on Macintosh computers. Virtual PC is an interpreter that executes machine-language programs written for IBM-PC-clone computers. If you run Virtual PC on your Macintosh, you can run any PC program, including programs written for Windows. (Unfortunately, a PC program will run much more slowly than it would on an actual IBM clone. The problem is that Virtual PC executes several Macintosh machine-language instructions for each PC machine-language instruction in the program it is interpreting. Compiled programs are inherently faster than interpreted programs.)

The designers of Java chose to use a combination of compilation and interpretation. Programs written in Java are compiled into machine language, but it is a machine language for a computer that doesn't really exist. This so-called "virtual" computer is known as the Java virtual machine. The machine language for the Java virtual machine is called Java bytecode. There is no reason why Java bytecode could not be used as the machine language of a real computer, rather than a virtual computer. In fact, Sun Microsystems -- the originators of Java -- have developed CPU's that run Java bytecode as their machine language.

However, one of the main selling points of Java is that it can actually be used on any computer. All that the computer needs is an interpreter for Java bytecode. Such an interpreter simulates the Java virtual machine in the same way that Virtual PC simulates a PC computer.

Of course, a different Java bytecode interpreter is needed for each type of computer, but once a computer has a Java bytecode interpreter, it can run any Java bytecode program. And the same Java bytecode program can be run on any computer that has such an

(22)

interpreter. This is one of the essential features of Java: the same compiled program can be run on many different types of computers.

Why, you might wonder, use the intermediate Java bytecode at all? Why not just distribute the original Java program and let each person compile it into the machine language of whatever computer they want to run it on? There are many reasons. First of all, a compiler has to understand Java, a complex high-level language. The compiler is itself a complex program. A Java bytecode interpreter, on the other hand, is a fairly small, simple program. This makes it easy to write a bytecode interpreter for a new type of computer; once that is done, that computer can run any compiled Java program. It would be much harder to write a Java compiler for the same computer.

Furthermore, many Java programs are meant to be downloaded over a network. This leads to obvious security concerns: you don't want to download and run a program that will damage your computer or your files. The bytecode interpreter acts as a buffer between you and the program you download. You are really running the interpreter, which runs the downloaded program indirectly. The interpreter can protect you from potentially dangerous actions on the part of that program.

2.8 Java Program Structure public class ClassName {

(23)

class body

public static void main (String[] args) {

method body }

}

public class Hello {

public static void main(String[] args) {

System.out.println("Hello"); }

}

Save this program in the folder say C:\javaprogram. The name of the class is the same as the name of the file. When you’re creating a stand-alone program such as this one, one of the classes in the file must have the same name as the file. (The compiler complains if you don’t do this.) That class must contain a method called main () with the signature shown: public static void main(String[] args)

The public keyword means that the method is available to the outside world. The static keyword means that no need to create an object of this class to access the main function. The void means function is not returning anything. The main keyword is the name of the main function from where the execution will start and args are the command line arguments.

By default java import a package java.lang and in this package we have a System class, and System class has a static object out of PrintStream class. Since it’s static you don’t need to create anything. The out object is always there and provides a println( ) function, which is used to print the string on the console and end with a new line.” Thus, in any Java program you write you can say System.out.println("things") whenever you want to print something to the console.

Compiling and running

In order to compile the program open the command prompt and go to your directory and write this command.

C:\javaprogram>javac Hello.java

This command should produce no response. But it will create Hello.class file in your folder which is the bytecode of this program.

In order to run this program, write this command on the same command prompt. C:\javaprogram>java Hello

(24)

2.9 Java Token:

A java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are:

• Identifier • Keyword • Literal • Separator • Operator 2.9.1 Identifiers

The Java identifiers are the names given for classes, methods, variables, objects, labels, packages and interfaces in a program. Here are the rules for creating a properly formed identifier:

Java Identifiers

1. are names for classes, methods, or variables.

2. begin with a letter, underscore (_), or dollar sign ($). 3. are case sensitive.

4. have no maximum length. 5. must not begin with digit.

Identifiers must be meaningful, short enough to be quickly and easily typed and long enough to be descriptive and easily read.

2.9.2 Keywords

The following character sequences are reserved for use as keywords and cannot be used as identifiers

Keyword: one of

abstract default if private this boolean

do implements protected throw break double

import public throws byte else instanceof return transient case extends int short

try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized

The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.

(25)

Literal in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are:

Integer Literal Floating-Point Literal Boolean Literal Character Literal String Literal Null Literal 2.9.4 Operators

An operator is a symbol that takes one or more arguments and operates on them to produce a result. The following 37 tokens are the operators, formed from ASCII characters:

Operator: one of = > < ! ~ ? : == <= >= != && || ++ --+ - * / & | ^ % << >> >>> += -= *= /= &= |= ^= %= <<= >>= >>>= 2.9.5 Separators

Separators are symbols used to indicate where groups of code are divided and arranged. They basically define the shape and function of our code. The following ASCII characters are the separators (punctuators):

Separator: one of ( ) Parentheses { }Braces [ ] Brackets ; Semicolon , Comma . Period 2.10 Comments

There are two kinds of comments

/* text */ A traditional comment: all the text from the ASCII characters /* to the ASCII characters */ is ignored (as in C and C++).

// text A end-of-line comment: all the text from the ASCII characters // to the end of the line is ignored (as in C++).

2.11 White Space

White space is defined as the ASCII space, horizontal tab, and form feed characters, as well as line terminators

(26)

the ASCII SP character, also known as "space"

the ASCII HT character, also known as "horizontal tab" the ASCII FF character, also known as "form feed" LineTerminator

2.12 Constants

• A constant is an identifier that is similar to a variable except that it holds one value for its entire existence

• The compiler will issue an error if you try to change a constant

• In Java, we use the final modifier to declare a constant final int count = 100;

2.13 Backslash Character Constants

Constants Meanings • ‘\b’ back space • ‘\f’ form feed • ‘\n’ new line • ‘\r’ carriage return • ‘\t’ horizontal tab • ‘\’’ single quote • ‘\”’ double quote • ‘\\’ backslash

(27)

UNIT 3: VARIABLES AND OPERATORS

3.1Variables

3.2Data Types in java 3.3Scope of Variables 3.4Array 3.4.1 One-Dimensional Array 3.4.2 Two-Dimensional Array 3.5Strings 3.6Operators 3.6.1 Arithmetic Operators 3.6.2 Assignment Operators 3.6.3 Conditional Operators 3.6.4 Special Operators 3.6.5 Relational Operators 3.6.6 Boolean Logical Operators

3.6.7 Incrementing and Decrementing Operators 3.6.8 Bitwise Operators

3.6.9 Operator Precedence

3.1 Variables

A variable is an identifier that denotes a storage location used to store a data value. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Variable name may consist of alphabets, digits, the underscore ( _ ) and dollar character, subject to the following conditions:

1. They must not begin with a digit.

2. Uppercase and lowercase are distinct. This means that the variable Amount is not equal to amount or AMOUNT.

3. It should not be a keyword. 4. White space is not allowed.

(28)

Every variable must have a data type. A variable's data type determines the values that the variable can contain, size it takes in memory and the operations that can be performed on it.

2.2 Data type in Java

The Java programming language has two categories of data types: 1. Primitive

2. Reference

A variable of primitive type contains a single value of the appropriate size and format for its type: A Number, A Character, or A boolean value.

The following table lists, by keyword, all of the primitive data types supported by Java, their sizes and a brief description of each.

Primitive Data Types

Keyword Description Size

(integers)

Data Types

Character Boolean Floating-point Integer Non-numeric

Numeric classes Arrays

Non-primitive Interface Primitive double float long int short

(29)

Byte Byte-length integer One byte

Short Short integer Two bytes

Int Integer Four bytes

Long Long integer Eight bytes

(real numbers)

Float Single-precision floating point Four bytes Double Double-precision floating point Eight bytes (other types)

Char A single character Two bytes (Unicode character) Boolean A Boolean value (true or false) true or false

Purity Tip: In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-dependencies.

You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable you can write this:

int anInt = 4;

The digit 4 is a literal integer value. Here are some examples of literal values of various primitive types:

Examples of Literal Values and Their Data Types

Literal Data Type

178 Int 8864L Long 37.266 Double 37.266D Double 87.363F Float 26.77e3 Double ' c ' Char True Boolean False Boolean

Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred, as it cannot be confused with the digit '1'. A series of digits with a decimal point is of type double. You can specify a float by putting an 'f' or 'F' after the number. A literal character value is any single

(30)

Unicode character between single quote marks. The two boolean literals are simply true and false.

Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable.

A reference is called a pointer or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.

3.3 Scope of Variables

A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier.

The location of the variable declaration within your program establishes its scope and places it into one of these categories:

• Instance variables

• Class variables

• Local variable

Instance and class variables are declared inside a class. Instance variable are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object. On the other hand, class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable.

Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace { and a closing brace }.These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist. The are of the program where the variable is accessible (i.e. usable) is called its scope.

3.4 Array

An array is a group of contiguous or related data items that share a common name. Or we can say that an array stores multiple variables of

(31)

• a specific number of indices ("slots"). • you access an element by using its index.

3.4.1 One-Dimensional Arrays

A list of items can be given one variable name using only one subscript and such a variable is called a single-subscript variable or a one-dimensional array.

Declaration of Arrays:

type arrayname [] = new type[size];

For example we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number, then we may create the variable number as follows

int number[]=new int[5];

and computer reserves five storage locations as shown below

35 40 20 57 19

number[0] number[1] number[2] number[3] number[4]

Note that java creates arrays starting with a subscript of 0 and ends with a value one less than the size specified. Unlike C, Java protects arrays from overruns and underruns. Trying to access an array beyond its boundaries will generate an error message.

Initialization of Arrays: arrayname[subscript]=value;

we can also initialize array automatically in the same way as the ordinary variables when they are declared, as shown below.

type arrayname[ ] = {list of values}; Example :

int number [ ] = {35, 40, 20, 57, 19};

Array Length

Array Length

In java, all arrays store the allocated size in a variable named length. We can access the length of the array a using a.length. Example:

int aSize = a.length;

(32)

So far we have discussed the array variables that can store a list of values. There will be situations where a table of values will have to be stored. Consider the following data table, which shows the value of sales of three items by four salesgirls:

Item1 Item2 Item3

Salesgirl #1 310 275 365

Salesgirl #2 210 190 325

Salesgirl #3 405 235 240

Salesgirl #4 260 300 380

The table contains a total of 12 values, there in each line. We can think of this table as a matrix consisting of four rows and three columns. Each row represents the values of sales by a particular salesgirl and each column represents the values of sales of a particular item. For creating two-dimensional arrays, we must follow the same steps as that of simple arrays, we may create a two-dimensional array like this:

type arrayname[][]=new type[row][col]; int myarray = new int[3][4];

like the one-dimensional array, two-dimensional array may be initialized by following their declaration with a list of initial values enclosed in braces. For example,

int table[2][3] = {2, 2, 2, 4, 4, 4};

initialize the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as

int table[ ] [ ] = { {2, 2, 2}, {4, 4, 4}};

by surrounding the elements of each row by braces.

3.5 Strings

Internally, a String is an array of characters, an array of char. The Java API, however, considers a String to be an object. Therefore, you benefit from built-in methods and property to help you handle strings.

3.6 Operators

3.6.1 Arithmetic Operators

Operator Name Use Description

+ Addition Op1 + op2 Adds op1 and op2 - Subtraction Op1 - op2 Subtracts op2 from op1

(33)

* multiplication Op1 * op2 Multiplies op1 by op2 / Division Op1 / op2 Divides op1 by op2

% modulus (or mod) Op1 % op2 Computes the remainder of dividing op1 by op2

The arithmetic operators return a number.

numeric return value = <operand1> <operator> <operand2>; example: myLongString = myShortString + myOtherString;

• + addition

o adds two numbers

o concatenates two string objects

• - subtraction

o subtract one number from another • * multiplication

o multiply two numbers

• / division

o divide two numbers • % modulus

o the remainder of an integer division o 5 % 3 = 2 Because 5/3 = 1 and leaves 2.

o myRemainder = 5 % 3;

3.6.2 Assignment Operator

You use the assignment operator, =, to assign one value to another. Compound Assignment Operator

Operator Use Equivalent to

+= Op1 += op2 Op1 = op1 + op2

-= Op1 -= op2 Op1 = op1 - op2

*= Op1 *= op2 Op1 = op1 * op2

/= Op1 /= op2 Op1 = op1 / op2

(34)

&= Op1 &= op2 Op1 = op1 & op2

|= Op1 |= op2 Op1 = op1 | op2

^= Op1 ^= op2 Op1 = op1 ^ op2

<<= Op1 <<= op2 Op1 = op1 << op2 >>= Op1 >>= op2 Op1 = op1 >> op2 >>>= Op1 >>>= op2 Op1 = op1 >>> op2

3.6.3 Conditional Operator

Operator Use Description

?: Exp1 ? exp2 : exp3 If op1 is true, returns op2. Otherwise, returns op3. (This is the conditional operator.)

3.6.4

3.6.4 Special OperatorsSpecial Operators

[] Type [] Declares an array of unknown length, which contains type elements. [] Type[ op1 ] Creates and array with op1 elements. Must be used with the

new operator. [] op1[ op2 ]

Accesses the element at op2 index within the array op1. Indices begin at 0 and extend through the length of the array minus one.

. op1.op2 Is a reference to the op2 member of op1.

() op1(params)

Declares or calls the method named op1 with the specified parameters. The list of parameters can be an empty list. The list is comma-separated.

(type) (type) op1 Casts (converts) op1 to type. An exception will be thrown if the

type of op1 is incompatible with type.

new New op1 Creates a new object or array. op1 is either a call to a

constructor, or an array specification.

Instanceof op1 instanceof op2 Returns true if op1 is an instance of op2

3.6.5 Relational Operators

Logical operators test a condition by comparing values and return a boolean value (true or false).

• == equal (two adjacent equal signs) if (sum = = 100) { // do something ...

(35)

WARNING: Testing for identical values with = = is different from assigning a value with = • != not equal if (sum != 100) { // do something ... • > greater than if (sum > 100) { // do something ... • < less than if (sum < 100) { // do something ... • >= greater than or equal to

if (sum >= 100) { // do something ... • <= less than or equal to

if (sum <= 100) { // do something ... Here's two comparison operators in a sequence: isBigSum = sum > 100;

The variable isBigSum gets the value true only if the sum is greater than 100.

3.6.6 Boolean Logical Operators

• & - ampersand is the logical and operator

boolean isAllExpensive = (cost1 >= 100) & (cost2 >= 100);

Both cost1 and cost2 must be >= 100 to return true and both cost1 and cost2 are evaluated

• && - double ampersand is the logical and operator that can "shortcircuit" when appropriate

boolean isAllExpensive = (cost1 >= 100) && (cost2 >= 100);

// Both cost1 and cost2 must be >= 100 to return true and if cost1 fails the test, cost2 is NOT evaluated.

• | - the logical or operator is the "pipe" key

boolean hasExpensive = (cost1 >= 100) | (cost2 >= 100);

Either cost1 or cost2 must be >= 100 to return true and both cost1 and cost2 are evaluated

• || or - double "pipe" is the logical or operator that can "shortcircuit" when appropriate

boolean isAllExpensive = (cost1 >= 100) || (cost2 >= 100);

Either cost1 or cost2 must be >= 100 to return true and if cost1 passes the test, cost2 is NOT evaluated.

Note: Do not confuse the two forward slashes of comments (//) with the two "pipes" of one of the logical operators (||).

Truth table

(36)

True true True false true true

true false False true false true

False true False true false true

False false True false false false

3.6.7 Incrementing and Decrementing

These short cut unary operators increment or decrement a number by one. Operator Use Description

++ Op++ Increments op by 1; evaluates to the value of op before it was incremented

++ ++op Increments op by 1; evaluates to the value of op after it was incremented -- Op-- Decrements op by 1; evaluates to the value of op before it was decremented

-- --op Decrements op by 1; evaluates to the value of op after it was decremented Note the difference between prefix versus post-fix.

3.6.8 Bitwise Operators

Bitwise operators are used for testing the bits, or shifting them to right or left. Bitwise operators may not be applied to float or double.

Operator Meaning & bitwise AND ! bitwise OR

^ bitwise exclusive OR ~ one’s complement << shift left

>> shift right

>>> shift right with zero fill

3.7 Operator Precedence

Mnemonic Operator type Operators

Ulcer Unary + -

++--Addicts Arithmetic (and

shift) * / % + - << >> Really Relational > < >= <= == != Like Logical (and bitwise) && || & | ^ C Conditional (ternary) A > B ? X : Y

(37)

A Lot Assignment = (and compound assignment like *=)

(38)

UNIT 4: CONTROL STATEMENTS

4.1Selection Statements 4.1.1 If

4.1.2 If ..Else

4.1.3 If..Else if .. else 4.2The Switch Statement 4.3Iteration Statement

4.3.1 The while Statement 4.3.2 The do Statement 4.3.3 The for Statement 4.4The Comma Operator

4.5The break Statement 4.6The continue Statement 4.7Selection Statements

4.7.1 If 4.7.2 If ..Else

4.7.3 If..Else if .. else 4.8The Switch Statement 4.9Iteration Statement

4.9.1 The while Statement 4.9.2 The do Statement 4.9.3 The for Statement 4.10The Comma Operator 4.11The break Statement 4.12The continue Statement

4.1 Selection Statements

• A conditional statement lets us choose which statement will be executed next

• Therefore they are sometimes called selection statements

• Conditional statements give us the power to make basic decisions

• Java's conditional statements are the if statement, the if-else statement, and the switch statement

4.1.1 if

if( boolean expression ) { statement1;

...

statementn; }

(39)

Note: Curly braces only required if there is more than one execution statement. 4.1.2 If..else if(x==y){ // do this } else { // do this }

Note: The "else" is for the last statement.

4.1.3 If..else if .. else if( x == y ) {

// do this

} else if( x > y ) { // nested 'if' // do this

// Note: any number of "else if" clauses after "if" and before "else" } else {

// do this }

Note: The "else" is for the last statement.

The output is: x not > or = to y

4.2 The switch Statement

• The switch statement provides another means to decide which statement to execute next

• The switch statement evaluates an expression, then attempts to match the result to one of several possible cases

(40)

• The flow of control transfers to statement list associated with the first value that matches

The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1; break; case value2 : statement-list2; break; case value3 : statement-list3; break; default : statement-list4; break; }

• Often a break statement is used as the last statement in each case's statement list

• A break statement causes control to transfer to the end of the switch statement

• If a break statement is not used, the flow of control will continue into the next case

• A switch statement can have an optional default case

• If the default case is present, control will transfer to it if no other case value matches

• The test variable or expression to be tested can be of the primitive types byte, char, short, or int

Example :

For example, the program: class Toomany {

static void howMany(int k) { switch (k) { case 1: System.out.print("one "); case 2: System.out.print("too "); case 3: System.out.println("many"); } }

public static void main(String[] args) { howMany(3);

howMany(2); howMany(1); }

}

contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:

many too many

(41)

one too many

If code is not to fall through case to case in this manner, then break statements should be

used, as in this example: class Twomany {

static void howMany(int k) { switch (k) {

case 1: System.out.println("one"); break; // exit the switch case 2: System.out.println("two");

break; // exit the switch case 3: System.out.println("many");

break; // not needed, but good style }

}

public static void main(String[] args) { howMany(1);

howMany(2); howMany(3); }

}

This program prints: one

two many

4.3 Iteration Statements

Java has three kinds of repetition statements: the while loop, the do loop, and the for loop

4.3.1 The while Statement

The while statement executes an Expression and a Statement repeatedly until the value of the Expression is false.

While Statement:

while (Expression) Statement

The Expression must have type boolean, or a compile-time error occurs. The while is an

entry-controlled loop statement. Therefore, the body of a while loop will execute zero or more times

public class WhileTest {

public static void main(String[] args) { int r = 0; while(r < 3) { System.out.println(r); } } }

(42)

The output will be 0

1 2

4.3.2 The do Statement

The do statement executes a Statement and an Expression repeatedly until the value of the Expression is false. do { statement; } while ( condition )

The statement is executed once initially, and then the condition is evaluated The statement is repetitively executed until the condition becomes false

• A do loop is similar to a while loop, except that the condition is evaluated after the body of the loop is executed

• Therefore the body of a do loop will execute at least one time

• The do while is an exit control loop statement.

4.3.3 The for Statement

The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false. for ( initialization ; condition ; increment )

statement;

The increment portion is executed at the end of each iteration

Example:

Example:

public class ListCharacters {

public static void main(String[] args) { for( char c = 0; c < 128; c++)

if (c != 26 ) // ANSI Clear screen

System.out.println("value: " + (int)c + " character: " + c); }

(43)

4.4 The comma operator

Comma operator is used to separate definitions and function arguments public class CommaOperator {

public static void main(String[] args) { for(int i = 1, j = i + 10; i < 5;i++, j = i * 2) { System.out.println("i= " + i + " j= " + j); }}}

4.5 The break Statement

The Java break statement causes the Java interpreter to transfer the flow of execution to the end of an enclosing statement. In other words, it is used to break out of a do, for, switch, or while statement.

The syntax of the Java break statement is: break;

Example:

for (int i=0; i < myArray.length; i++) {

if (myArray[i] == null; {

break; // break out of for loop }

} // execution resumes at following statement on break

4.6 The continue statement

A Java continue statement is used to terminate the current iteration of a loop and continue with the next iteration. A continue statement can only be used within a do, for, or while loop.

The syntax of the Java continue statement is: continue;

Example:

for (int i=0; i < myArray.length; i++) {

if (myArray[i] == null; {

continue; // skips remainder of loop and begins next iteration }

myMethod (myArray[i]); // do something with a non-null myArray[i] }

(44)

The different types of looping statements vary in how the continue statement begins a new iteration.

• do loop: On encountering a continue statement, the Java interpreter jumps to the bottom of the do loop. Then, it evaluates the test condition to determine whether to begin a new iteration.

• for loop: On encountering a continue statement, the Java interpreter begins at the top of the loop in the for statement. First, it evaluates the update expression, e.g. i++. Then, it evaluates the test expression, e.g. i < myArray.length. The important thing is that the update expression is evaluated.

• while loop: On encountering a continue statement, the Java interpreter begins at the top of the loop in the while statement. Then, it evaluates the test condition to determine whether to begin a new iteration.

References

Related documents

• The very short summer during the transition year – we all must be aware 

The diuretic activity of Argemone mexicana leaves extract evaluated using the standard methods, measuring urinary output, pH, and conductivity..

I am confident that by understanding curricular and instructional practices of exemplary, globally-competent schools, as well as the behavior and characteristics of globally

To evaluate the relationship between teams’ co-location and project performance, this paper uses a parallel between project performance parameters proposed by Clark

The ordinal regression method was used to evaluate the relationship between ICT performance of the overall production procedures in Greek SMEs (enhancement of

Since di ff erences in the crystalline phases in Mixtures 1, 2, and 3 exist, and the types associated with diopside in Mixtures 2 and 3 and anorthite in Mixture 1, the di ff erence

When using cable restraint systems, the secondary vertical force component generated by the horizontal load is always directed upward, loading the support hanger rod in

When using the adaptive time-slot monitoring mechanism, upon the detection of bursty traffic, the duration of time slots was set to the default value for the following target