sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object...

82
Java & Internet Programming Lecture Notes Unit I Unit Structure 1.1 Introduction to Object Oriented Programming 1.2 Java on the Internet 1.3 Multithreading and Persistence 1.4 Java Keywords and Flow Control 1.5 Garbage Collection 1.6 Packages 1.7 Final Declaration 1.8 Interfaces 1.9 Inner Classes 1.10 Java I/O Classes 1.11 Run time Type Identification. 1.1Introduction to Object Oriented Programming Object oriented programming is the new concept of programming introduced in late 80's. OOP is a design philosophy. O bject- O riented P rogramming ( OOP ) uses a different set of programming languages than old procedural programming languages ( C, Pascal , etc.). Everything in OOP is grouped as self sustainable " objects ". A type of programming in which programmers define not only the data type of a data structure , but also the types of operations ( functions ) that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions. OOPs reduce the code of the program because of the extensive feature of Polymorphism. OOPs have many properties such as Data Hiding, Inheritance, Data Abstraction, Data Encapsulation and many more. Department of Information Technology 1.1

Transcript of sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object...

Page 1: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Unit I

Unit Structure

1.1 Introduction to Object Oriented Programming1.2 Java on the Internet1.3 Multithreading and Persistence1.4 Java Keywords and Flow Control1.5 Garbage Collection 1.6 Packages1.7 Final Declaration 1.8 Interfaces 1.9 Inner Classes 1.10 Java I/O Classes 1.11 Run time Type Identification.

1.1Introduction to Object Oriented Programming

Object oriented programming is the new concept of programming introduced in late 80's. OOP is a design philosophy. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects".

A type of programming in which programmers define not only thedata type of a data structure, but also the types of operations (functions) that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions.

OOPs reduce the code of the program because of the extensive feature of Polymorphism. OOPs have many properties such as Data Hiding, Inheritance, Data Abstraction, Data Encapsulation and many more.

1.2Introduction

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called "Oak" but was renamed "Java" in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype.

JAVA IS IMPORTANT TO THE INTERNETJava expands the universe of objects that can move about freely in cyberspace. In a

network, two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you Department of Information Technology 1.1

Page 2: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

read your e-mail, you are viewing passive data. Even when you download a program, the program's code is still only passive data until you execute it.

Java Applets and Applications-Java can be used to create two types of programs: applications and applets. An

application is a program that runs on your computer, under the operating system of that computer.

-An applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser.

-The important difference is that an applet is an intelligent program, not just an animation or media file. In other words, an applet is a program that can react to user input and dynamically change - not just run the same animation or sound over and over.

Security

Every time that you download a "normal" program, you are risking a viral infection. Prior to Java, most users did not download executable programs frequently, and those who did scan them for viruses prior to execution. Even so, most users still worried about the possibility of infecting their systems with a virus. In addition to viruses, another type of malicious program exists that must be guarded against. This type of program can gather private information, such as credit card numbers, bank account balances, and passwords, by searching the contents of your computer's local file system. Java answers both of these concerns by providing a "firewall" between a networked application and your computer.

Portability

Many types of computers and operating systems are in use throughout the world- and many are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. As you will soon see, the same mechanism that helps ensure security also helps create portability. Indeed, Java's solution to these two problems is both elegant and efficient.The progress of abstraction

All programming languages provide abstractions. It can be argued that the complexity of the problems you’re able to solve is directly related to the kind and quality of abstraction. By “kind” I mean, “What is it that you are abstracting?” Assembly language is a small abstraction of theunderlying machine. Many so-called “imperative” languages that followed (such as Fortran, BASIC, and C) were abstractions of assembly language.

These languages are big improvements over assembly language, but their primary abstraction still requires you to think in terms of the structure of the computer rather than the structure of the problem you are trying to solve. The programmer must establish the association between the machine model (in the “solution space,” which is the place where you’re modeling that problem, such as a computer) and the model of the problem that is actually being solved (in

Department of Information Technology 1.2

Page 3: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

the “problem space,” which is the place where the problem exists). The effort required to perform this mapping, and the fact that it is extrinsic to the programming language, produces programs that are difficult to write and expensive to maintain, and as a side effect created the entire “programming methods” industry.

1. Everything is an object. Think of an object as a fancy variable; it stores data, but you can “make requests” to that object, asking it to perform operations on itself. In theory, you can takeany conceptual component in the problem you’re trying to solve (dogs, buildings, services, etc.) and represent it as an object in your program.

2. A program is a bunch of objects telling each other what to do by sending messages. To make a request of an object, you “send a message” to that object. More concretely, you can think of a message as a request to call a function that belongs to a particular object.

3. Each object has its own memory made up of otherObjects. Another way to create a new kind of object by making a package containing existing objects. Thus, you can build complexity in a program while hiding it behind the simplicity of objects.

4. Every object has a type. Using the parlance, each object is an instance of a class, in which “class” is synonymous with “type.” The most important distinguishing characteristic of a class is “What messages can you send to it?”

5. All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see later. Because an object of type “circle” is also an object of type “shape,” a circle is guaranteed to accept shape messages. This means you can write code that talks to shapes and automatically handle anything that fits the description of a shape. This substitutability is one of the most powerful concepts in OOP.

Garbage collectors vs. efficiency and flexibility

Creating objects on the heap can be much more expensive. Always inheriting from a base class and making all function calls polymorphic also exacts a small toll. But the garbage collector is a particular problem because you never quite know when it’s going to start up or how long it will take. This means that there’s an inconsistency in the rate of execution of a Java program, so you can’t use it in certain situations, such as when the rate of execution of a program is uniformly critical. (These are generally called real time programs, although not all real time programming problems are this stringent.)

Exception handlingJava’s exception handling stands out among programming languages, because in Java, exception handling was wired in from the beginning and you’re forced to use it. If you don’t write your code to properly handle exceptions, you’ll get a compile-time error message. This guaranteedConsistency makes error handling much easier.

Department of Information Technology 1.3

Page 4: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

1.2 JAVA AND THE INTERNETAlthough Java is very useful for solving traditional standalone programming problems, it is also important because it will solve programming problems on the World Wide Web.

Client/Server computingThe primary idea of a client/server system is that you have a central repository of information some kind of data, often in a database that you want to distribute on demand to some set of people or machines. A key to the client/server concept is that the repository of information is centrally located so that it can be changed and so that those changes will propagate out to the information consumers.

Client-side programmingThe server produced static pages for the client browser, which would simply interpret and display them. Basic HTML contains simple mechanisms for data gathering: text-entry boxes, check boxes, radio boxes, lists and drop-down lists, as well as a button that can only be programmed to reset the data on the form or “submit” the data on the form back to the server. This submission passes through the Common Gateway Interface (CGI) provided on all Web servers.

Scripting languagesPlug-ins resulted in an explosion of scripting languages. With a scripting language you embed the source code for your client-side program directly into the HTML page, and the plug-in that interprets that language is automatically activated while the HTML page is being displayed.

ActiveXTo some degree, the competitor to Java is Microsoft’s ActiveX, although it takes a completely different approach. ActiveX was originally a Windows only solution, although it is now being developed via an independent consortium to become cross-platform. Effectively, ActiveX says “if your program connects to its environment just so, it can be dropped into a Web page and run under a browser that supports ActiveX.” (IE directly supports ActiveX and Netscape does so using a plug-in.)

Server-side programming

A common scenario involves a request for a complex database search, which the server then formats into an HTML page and sends to you as the result. (Of course, if the client has more intelligence via Java or a scripting language, the raw data can be sent and formatted at the client end, which will be faster and less load on the server.) Or you might want to register your name in a database when you join a group or place an order, which will involve changes to that database. These database requests must be processed via some code on the server side, which is generally referred to as server-side programming.

1.3 MULTITHREADING AND PERSISTENCEA fundamental concept in computer programming is the idea of handling more than one task at a time. Many programming problems require that the program be able to stop what its doing, deal with some other problem, and then return to the main process.

Department of Information Technology 1.4

Page 5: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Sometimes interrupts are necessary for handling time-critical tasks, but there’s a large class of problems in which you’re simply trying to partition the problem into separately running pieces so that the whole program can be more responsive. Within a program, these separately running pieces are called threads, and the general concept is called multithreading. A common example of multithreading is the user interface.

By using threads, a user can press a button and get a quick response rather than being forced to wait until the program finishes its current task.Java’s threading is built into the language, which makes a complicated subject much simpler. The threading is supported on an object level, so one thread of execution is represented by one object. Java also provides limited resource locking. It can lock the memory of any object (which is, after all, one kind of shared resource) so that only one thread can use it at a time. This is accomplished with the synchronized keyword. Other types of resources must be locked explicitly by the programmer, typically by creating an object to represent the lock that all threads must check before accessing that resource.

PersistenceWhen you create an object, it exists for as long as you need it, but under no circumstances does it exist when the program terminates. While this makes sense at first, there are situations in which it would be incredibly useful if an object could exist and hold its information even while the program wasn’t running.

Then the next time you started the program, the object would be there and it would have the same information it had the previous time the program was running. Of course, you can get a similar effect by writing the information to a file or to a database, but in the spirit of making everything an object it would be quite convenient to be able to declare an object persistent and have all the details taken care of for you.

Java provides support for “lightweight persistence,” which means that you can easily store objects on disk and later retrieve them. The reason it’s “lightweight” is that you’re still forced to make explicit calls to do the storage and retrieval. In addition, JavaSpaces provide for a kind of persistent storage of objects. In some future release

A First Simple ProgramNow that the basic object-oriented underpinning of Java has been discussed, let's look at some actual Java programs. Let's start by compiling and running the short sample program shown here. As you will see, this involves a little more work than you might imagine.

/*This is a simple Java program.Call this file "Example.java".*/class Example {// Your program begins with a call to main().public static void main(String args[]) {

Department of Information Technology 1.5

Page 6: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

System.out.println("This is a simple Java program.");}}

Note : The descriptions that follow use the standard JDK (Java Developer's Kit), which is available from Sun Microsystems. If you are using a different Java development environment, then you may need to follow a different procedure for compiling and executing Java programs. In this case, consult your compiler's user manuals for details.

Compiling the Program

To compile the Example program, execute the compiler, javac, specifying the name of the source file on the command line, as shown here:C:\\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the Java bytecode is the intermediate representation of your program that contains instructions the Java interpreter will execute. Thus, the output of javac is not code that can be directly executed.

To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Example as a command-line argument, as shown here:C:\\>java Example

MULTITHREADING:

Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel.

Those who are familiar with the modern operating system such as windows XP may recognize that they can execute several programs simultaneously. This ability is known as multitasking. In system’s terminology it is called multithreading.

A unique property of Java is its support for multithreading. That is, Java enables us to use multiple flows of control in developing programs.

Each flow of control may be thought of as a separate tiny program known as a thread that runs in parallel.

A program that contains multiple flows of control is known as multithreading program.

DIFFERENCE BETWEEN MULTITHREADING AND MULTITASKING:

Department of Information Technology 1.6

Page 7: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

MULTITHREADING MULTITASKING

The processor has to switch between different parts or threads of a program.

The processor has to switch between different programs to processes.

It is highly efficient. It is a less efficient in comparison to multithreading.

A thread is the smallest unit in multithreading.

.A program or process is the smallest unit in a multitasking environment

It helps in developing efficient programs. It helps in developing efficient operating system.

It is cost effective in case of context switching.

.It is expensive in case of context switching.

TYPES OF MULTITHREADING:

There are two ways of multithreading. They are:

Creating a thread Extending a thread

CREATING A THREAD

Creating thread in a Java is simple. Threads are implemented in the form of objects that contains a method called run ().It is an only method in which that threads behaviour can be implemented. The run () method should be invoked by an object of the concerned thread. It would appear as follows:

public void run()

{

………………..…………………………}

Creating a thread is by two steps. They are:

Creating a new class thread: Define a class that extend thread class and override its run () method with the code required by the thread.

Department of Information Technology 1.7

Page 8: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Converting a class into thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run (), that is to be defined in the method with the code to be executed by the thread.

EXTENDING A THREAD:

We can make a class Runnable as thread by extending the class java.lang.thread.

Extending a thread is of four following steps. They are:

Declare a thread: Declare the class as extending the thread class.The thread class can be extended as follows:

Class MyThread extends thread

{

……………. …………….. ………….. }

Implementing a thread: Implement the run() method that is responsible for executing the sequence of codes that the thread will execute. The run () method has been inherited by the class MyThread. We have to override this method in order to implement the code to be executed by our thread. The basic implementation of run() will look like this:public void run()

{

………..

……….. // Thread code here

………..

}

Start a thread: Create a thread object and call the start() method to initiate the thread execution. To actually create and run an instance of our thread class, we must write the following:MyThread aThread=new MyThread();

aThread.start (); // invokes run() method

The first line instantiates a new object of class MyThread. The second line calls the start () method causing the thread to move into the Runnable state.

Department of Information Technology 1.8

Page 9: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Stopping a thread: Whenever we need to stop a thread from running further, we may to do so by calling its stop() method like,aThread.stop();

This statement causes a thread to move to the dead state. A stop() method may be used when the premature death of a thread is desired.

Blocking a thread: A thread can also be temporarily suspended or blocked from entering into the Runnable and subsequently running state by using either of the following thread methods,

sleep () // blocked for a specified time

suspend () // blocked until further orders

wait () // blocked until certain condition occurs

These methods cause the thread to go into the blocked state. The thread will return to the Runnable state when the specified time is elapsed in case of sleep (), the resume () method is invoked in case of suspend (), the notify () method is called in case of wait ().

MULTITHREADING LIFE CYCLE OF A THREAD:

New Thread

Running Runnable Dead

Blocked

Start

stop()

stop()

stop()

Supend

Sleep

Wait

Resume

notify

yield

yield

During the life time of a thread, there are many states it can enter. They include:

1. New born stateDepartment of Information Technology 1.9

Page 10: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

2. Runnable state3. Running state4. Blocked state5. Dead state

A thread is always in one of these states. It can move from one state to other.

NEW BORN STATE:

When we create a thread object, the thread is born and is said to be in new born state. It is not yet scheduled for running. In this state,

Schedule it for running using start () method. Kill it using stop () method.

RUNNABLE STATE:

The Runnable state means the thread is ready for execution and it is waiting for availability of the processor. The queues of thread are waiting for execution. If all the threads have equal priority then they give time slots for execution. This process of assigning time to threads is known as time slicing.

RUNNING STATE:

Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. A running thread may have:

1. It has been suspended using suspend () method. A suspended thread can be revived by using the resume () method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it.

Department of Information Technology 1.10

Page 11: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

2. It has been made to sleep. We can put a thread to sleep for a specified time using the method sleep (). The thread re-enters the Runnable state as soon as this time period is elapsed.

3.It has been told to wait until some event occurs. This is done using wait () method. The thread can be scheduled to run again using the notify () method.

BLOCKED STATE:

A thread is said to be blocked when it is prevented from entering into the Runnable state and subsequently the running state. This happens when thread is suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run again.

DEAD STATE:

Every thread has a life cycle. A running thread ends its life when it has completed executing its run () method. We can kill it by sending a stop message to it at any state thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running or even when it is in “not Runnable state” condition.

Example Program:

Class A extends Thread

{

public void run()

{Department of Information Technology 1.11

Page 12: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

for(int i=1;i<=5;i++)

{

System.out.println (“\t Thread A:i=”+i);

}

System.out.println (“Exit from A”);

}

}

Class B extends Thread

{

public void run()

{

for ( int j=1;j<=5;j++)

{

System.out.println (“\t Thread B:j=”+j);

}

System.out.println (“Exit from B”);

}

}

Class C extends Thread

{

public void run ()

{

For (int k=1;k<=5;k++)

{

System.out.println (“\t Thread C:k=”+k);

Department of Information Technology 1.12

Page 13: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

}

System.out.println (“Exit from C”);

}

}

Class Thread Test

{

public static void main (string arg[])

{

New A ().start ();

New B ().start ();

New C ().start ();

}

}

THREAD PRIORITY:

In Java, each thread is assigned to a priority which affects a order in which it is scheduled for running. The threads we discuss before is of same priority.

Java permits as to set the priority of thread using the setPriority () method as follows:

ThreadName.setPriority(intNumber);

The intNumber is an integer value to which the thread’s priority is set. The Thread class defines several priority constants:

MIN_PRIORITY=1

NORM_ PRIORITY=5

MAX_PRIORITY=10

For a thread of priority to gain control, one of the following should happen:

1.It stops running at the end of run().

2.It is made to sleep using sleep().Department of Information Technology 1.13

Page 14: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

3.It is told to wait using wait().

Example program:

Class A extends Thread

{

Public void run()

{

System.out.println(“threadA started”);

For(int i=1; I<=4; i++)

{

System. Out. Println(“\tFrom Thread A : i=” +i);

}

System. Out. Println(“Exit from A”);

}

}

Class B extends Thread

{

Public void run()

{

System.out,println(“threadB started”);

For(int j=1; j<=4; j++)

{

System. Out. Println(“\tFrom Thread B : j =” + j);

}

System. Out. Println(“Exit from B”);

}

Department of Information Technology 1.14

Page 15: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

}

Class C extends Thread

{

Public void run()

{

System.out.println(“threadC started”);

For(int k=1; k<=4; k++)

{

System. Out. Println(“\tFrom Thread C : k=”+k);

}

System.out.println(“Exit from C”);

}

}

Class ThreadPriority

{

Public static void main(String args[])

{

A threadA = new A();

B threadB = new B();

V threadC = new C();

threadC,setPriority( Thread.MAX_PRORITY);

threadB.setPriority(threadA.getPririty()+1);

threadA.setPririty(Thread.MIN_PRIORITY);

system.out.println(“Start thread A”);

threadA.start();

Department of Information Technology 1.15

Page 16: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

system.out.println(“Start thread B”);

threadB.start();

system.out.println(“Start thread C”);

threadC.start();

system.out.println(“End of main thread”);

}

}

CONSTANTS

Constants are fixed values that do not change during the execution of a program. Java supports several types of constants as follows,

Integer constants Real constants Single character constants String constants Backslash character constants

INTEGER CONSTANTS

An integer constant refers to a sequence of digits. There are three types of integers namely decimal integers, octal integers and hexadecimal integers.

Decimal integers consist of a set of digits from 0 through 9, preceded by an optimal minus sign. Here embedded spaces, commas and non digit characters are not permitted in between digits.

An octal integer constant consists of any combination of digits from the set 0 through, with a leading zero.

Eg: 037, 0551

REAL CONSTANTS

As integers are inadequate to represent quantities that vary continuously such as distances, heights, temperature ,prices and so on quantities are represented by numbers containing fractional parts , such numbers are called as real constants or floating point constants.Department of Information Technology 1.16

Page 17: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Eg: 0.0083, -0.75

Therefore a floating point constant may comprise of four parts,

A whole number A decimal point A fractional part An exponent

SINGLE CHARACTER CONSTANTS

A single character constant contains a single character enclosed within a pair of single quote marks.

Eg: ‘r’ , ‘;’ , ‘ x’

STRING CONSTANTS

A string constant is a sequence of characters enclosed within double quotes. The characters may be alphabets, digits, special characters and blank spaces.

Eg: “Hello” , “1997”

BACKSLASH CHARACTER CONSTANTS

Java supports some special backslash character constants that are used in output methods. Here each of them represents only one character though there are two characters present. These character combinations are referred to as escape sequences. Some examples are

\n - new line

\b - back space

\f - form feed

\r - carriage return

\t - horizontal tab

VARIABLES

A variable is an identifier that denotes a storage location used to store a data value. Unlike constants a variable may take different values at different times during the execution of the program. A variable name may consists of alphabets, digits ,underscore and dollar characters, subject to the following conditions,

They must not begin with a digit

Department of Information Technology 1.17

Page 18: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

It should not be a keyword Uppercase and lower cases are distinct White space is not allowed Variable names can be of any length

DATA TYPES

Every variable in java has a data type. Data types specify the size and type of values that can be stored. Data types in java are categorized mainly into two types namely

Primitive or intrinsic data types Non primitive or derived data types

PRIMITIVE DATA TYPES

Primitive data types mainly comprise of,

Integer types Floating point types Character types Boolean types

INTEGER TYPES

Integer data types hold whole numbers. Java supports four types of integers namely byte, short, int and long. Java does not support the concept of unsigned types. The memory size and the range of all the four integer data types is given as follows

TYPE SIZE MINIMUM VALUE MAXIMUM VALUE

Byte One byte -128 127

Short Two bytes -32, 768 32, 767

Int Four bytes -2,147,483,648 2, 147, 483, 647

Long Eight bytes -9 ,223 ,372 ,036 ,854 ,775 , 808

9, 223, 372, 036, 854, 775, 807

Here wider data types require more time for manipulation ana therefore it is advisable to use smaller data types.

Department of Information Technology 1.18

Page 19: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

FLOATING DATA TYPES

Integer types can hold only whole numbers and therefore to use fractional numbers we go for floating data types. Float type values are single precession numbers while the double type represents double precession numbers. The size and range of these two data types are,

TYPE SIZE MINIMUM VALUE MAXIMUM VALUE

Float 4 bytes 3.4e-038 1.7e-0.38

double 8 bytes 3.4e-038 1.7e-308

Floating point data types support a special value known as not-a-number. NaN is used to represent the result of operations such as divide zero by zero where an actual number is not produced.

CHARACTER TYPES

Char data type is used for storing character constants in memory. It assumes a size of 2 bytes but basically it can hold only a single character.

BOOLEAN TYPES

It is used when we want to test a particular condition during the execution of a program. There are only two values that a Boolean type can take true or false. It is denoted by the keyword Boolean. The words true or false cannot be used as identifiers. Boolean values are often used in selection and iteration statements.

DECLARATION OF VARIABLES

In java variables are the names of storage locations. After designing suitable variable names we must declare to them to the compiler. Declaration does the following three things,

It tells the compiler what the variable name is It specifies what type of data the variable will hold The place of declaration decides the scope of the variable

A variable must be declared before it is used in the program. The general form of declaration of a variable is,

Type variable1

Variables are separated by commas. A declaration statement must end with a semicolon.

Department of Information Technology 1.19

Page 20: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

GIVING VALUES TO VARIABLES

A variable must be given a value after it has been declared. This is achieved in two ways,

Using an assignment statement Using a read statement

ASSIGNMENT STATEMENT

A value can be assigned to a variable through assignment statement as follows

Variable name=value

READ STATEMENT

Values can also be given to variables interactively through the keyboard using readLine() method . This method reads the input from the keyboard as a string which is then converted to the corresponding data type using the data type wrapper class.

SCOPE OF VARIABLES

Java variables are classified into three kinds

Instance variables Class variables Local variables

Instance and class variables are declared inside a class. Instance variables are created when the objects are instantiated and therefore are

associated with the objects. Whereas class variables are global to the class and belong to the entire set of objects.

Variables declared and used inside methods are called local variables.

DEFINING A CLASS

A class is a user defined data type. Once a class has been defined we can create variables of that type using declarations similar to basic class declarations. The basic form of a class declaration is,

Class classname

{Department of Information Technology 1.20

Page 21: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

[ fields declaration];

[ methods declaration];

}

It is to noted that there is no semicolon after closing brace.

FIELD DECLARATION

Data is encapsulated in a class by placing data fields inside the body of the class definition. These are called as instance variables as they are created whenever an object of the class is instantiated.

Example:

Class rectangle

{

Int length;

Int width;

}

Instance variables are also known as member variables.

METHOD DECLARATION

A class with only data fields has no life. We must therefore create methods that are necessary for manipulating the data contained in the class. They are declared inside the body of the class but immediately after the declaration of instance variables.

Type methodname (parameter-list)

{

Method-body;

}

Method declaration has the following four basic parts,

The name of the method The type of the value the method returns A list of parameters The body of the method

Department of Information Technology 1.21

Page 22: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Eg:

Class rectangle

{

Int length;

Int width;

Void getdata (int x, int y)

{

Length=x;

Width=y;

}

Creating objects

An object in java is a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object. In java objects are created using the new operator.

Example:

Rectangle rect1;

Rect1= new rectangle();

ACCESSING CLASS MEMBERS

To access the various instance variables and methods in the class directly we use the concerned object and dot operator.

Objectname . variablename= value;

Objectname . methodname(parameter list);

Here object name is the name of the object ,and variable name and method names are the names of the instance methods and variables.

STATIC MEMBERS

Department of Information Technology 1.22

Page 23: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

The members that are declared static are called as static members. Static members are often referred to as class variables and methods. Static are generally used when we want to have a variable common to all instances of a class.

o Static int count;

o Static int max(int x, int y);

Static methods have several restrictions as follows namely,

They can call only static methods They can access only static data They cannot refer to this or super keywords in any way

SUPER KEYWORD

Super keyword is used by the subclass constructor to invoke the constructor method of the superclass. The keyword super is used subject to the following conditions,

It may be used only within a subclass constructor method The call to super class constructor must appear as the first statement within the

subclass constructor. The parameters in the super call must match the order and type of the instance

variable declared in the superclass.

FINAL VARIABLES AND METHODS

The overriding of variables and methods can be prevented by using the keyword final as a modifier. Declaring a variable to final ensures that the values assigned to the variable can never be changed. Similarly declaring a final method ensures that method will never be altered in any way.

Final int size =100;

Final void show status()

FINAL CLASSES

A class that cannot be sub classed is called a final class. This is achieved using the keyword final. Declaring a class final prevents any unwanted extensions to the class.

Final class class(…)

CONSTRUCTORS

Department of Information Technology 1.23

Page 24: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Java supports a special type of method called constructor that enables an object to initialize itself when it is created. Constructors have the same name as class itself and secondly they do not specify a return value, not even void because they return the instance of the class itself. Eg:

Class Rectangle

{

Int length;

Int width;

Rectangle(int x,int y) //constructor method

{

Length=x;

Width=y;

}

Int rectArea()

{

Return(length*width);

}

}

INHERITANCE

The mechanism of deriving a new class from an old class is called as inheritance. The old class is known as the base class or super class or parent class and the new class is called the subclass or derived class or child class. Inheritance may take different subforms as follows,

Single inheritance Multiple inheritances Hierarchical inheritance Multilevel inheritance

MULTIPLE INHERITANCES

Department of Information Technology 1.24

Page 25: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Java does not supports the concept of multiple inheritance however this concept is implemented using a secondary interface path in the form of interfaces. A interface in a class is defined using implements.

MULTILEVEL INHERITANCE

For this the common requirement is the use of the derived class as a super class . Here the class A serves as a base class for the derived class B which in turn serves as the base class for the derived class C. the chain ABC is known as inheritance path.

Class A

{

}

Class B extends A

{

}

Class C extends B

{

}

HIERARCHIAL INHERITANCE

Using hierarchical inheritance many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below the level. This inheritance is used as a support to the hierarchical design of a program.

Eg: hierarchical classification of accounts in a commercial bank

Example :[single inheritance]

Class Room

{

Int length;

Int breadth;

Room(int x, int y)

Department of Information Technology 1.25

Page 26: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

{

Length=x;

Breadth=y;

}

Int area()

{

Return (length*breadth);

}

}

Class BedRoom extends Room

{

Int height;

BedRoom(int x, int y, intz)

{

Super(x,y)

Height=z;

}

Int volume()

{return(length*breadth*height);

}

}

Class InherTest

{

Public static void main(String args[])

Department of Information Technology 1.26

Page 27: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

{

BedRoom room1=new BedRoom(14,12,10);

Int area1=room1.area();

Int volume1=room1.volume();

System.out.println(“area1=” +area);

System.out.println(“volume=” +volume);

}

}

Output:

Area1= 168

Volume1= 1680

OPERATORS:

Java operators can be classified into number of operators as balow:

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators

ARITHMETIC OPERATORS:Arithmetic operators are used to construct mathematical expressions.java provides all the

basic operators they are given by +,-,*, /. We cannot use these operators on boolean typeArithmetic operators are used as shown below:

a-b a/ba+b a%ba*b

here a and b may be variables or constants and are known as operands.

INTEGER ARITHMETIC:

Department of Information Technology 1.27

Page 28: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

When both the operands in a single arithmetic expression such as a+b are integers, the expression is called as integer expression, and the operation is called as Integer arithmetic. Integer arithmetic always yields an integer value.

In the above examples, if a and b are integers then a=14 and b=4 we have the following results:

a+b=18a-b=10a*b=56a/b=3(decimal part truncated)a%b=2(remainder of integer division)

For modulo division,the sign of the result is always the sign of the first operand. For eg:-14%3=-2-14%-3=214%-3=2

REAL ARITHMETIC:

An arithmetic operation involving only real operands is called real arithmetic. A real operand may assume values either in decimal or exponential notation. Since floating point values are rounded to the number of significant digits permissible, the final value is an approximation of the correct result.

Unlike C and C++, modulus operator % can be applied to the floating point data as well. The floating point modulus operator returns the floating point equivalent of an integer division. What this means is that the division is carried out with both floating point operands, but the result is given as the integer as the integer.

Eg:

class FloatingPoint

{

public static void main(String arg[])

{

float a=20.5F,

float b=6.4F;

System.out. println(“a=”,+a);

System.out. println(“b=”,+b);

Department of Information Technology 1.28

Page 29: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

System.out. println(“a+b=”,+(a+b));

System.out. println(“a-b=”,+(a-b));

System.out. println(“a*b=”,+(a*b));

System.out. println(“a/b=”,+(a/b));

System.out. println(“a%b=”,+(a%b));

}

}

RELATIONAL OPERATORS:

We often compare two quantities, and depending on their relation, take certain decisions. For eg we may compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the help of relational operators. Java supports six relational operators. The operators along with the meaning is given below:

Operators Meaning

< is less than

> is greater than

>= is greater than or equal

<= is less then or equal

= = is equal to

!= is not equal

class RelationalOperators

{

public static void main(String args[])

{

float a=15.0F;

float b=20.75F;

float c =15.0F;Department of Information Technology 1.29

Page 30: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

System.out.pintln(“a=”+a);

System.out.pintln(“b=”+b);

System.out.pintln(“c=”+c);

System.out.pintln(“a<b is “+(a<b));

System.out.pintln(“a>b is” +(a>b));

System.out.pintln(“a==c is” +( a==c));

System.out.pintln(“a<=c”+(a<=c));

}

}

LOGICAL OPERATORS:

In addition to the relational operators, Java has three logical operators, which are given by:

Operators Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Eg:

a>b && x==10

An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression. Like the simple relational expressions, a logical expression also yields a value of true or false.

ASSIGNMENT OPERATORS:

Assignment operators are used to assign the value of an expression to the variable. We have seen the usual assignment operators, “=”. In addition, Java has a set of ‘shorthand’ assignment operators which are used in the form;

v op=exp;

Here v is a variable, exp is an expression and op is a Java binary operator. The operator op= is known as the shorthand assignment operator.Department of Information Technology 1.30

Page 31: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

The assignment statement,

v op = exp;

is equivalent to

v=v op(exp);

with v accessed only once. Consider an eg:

x+=(y+1);

This is the same as the statement

x=x+(y+1);

The use of shorthand operators has three advantages:

What appears on the left hand side may not be repeated and therefore it becomes easier to write.

The statement is more concise and easies to read. Use of shorthand operator results in a more efficient code.

INCREMENT AND DECREMENT OPERATORS:Java has two very useful operators not generally found in many other languages. These are

the increment and decrement perators:

++ and --

The operator ++ adds 1 to the operand while -- subtracts 1. Both are unary operators and are used in the following form:

They can be given as:

Increment operators:

Pre-increment(++m) Post increment(m++)

Decrement operators:

Pre-decrement(--m) Post-decrement(m--)

++m is equivalent to m=m+1 or m+=1--m is equivalent to m=m-1 or m-=1

Department of Information Technology 1.31

Page 32: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Consider the value of

m=5;y=++m;

Here the value of both y and m will be as 6.

CONDITIONAL OPERATORS:The character pair ? : is a ternary operator available in Java. This is used to condition

expression of the form:

exp ? exp2 : exp3

where exp1,exp2,exp3 are the expressions.

The conditional operator works in the follows: exp1 is evaluated first. If it is non zero(true), then the exp2 is evaluated and becomes the value of the conditional expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the condition expression. Note that only one expression can be evaluated(either exp2 or exp3).

BITWISE OPERATORS: Java has a distinction of supporting special operators known as the bitwise operators

for the manipulation of the data at values of the bit level. These operators are used for the testing of the bits, or shifting them to the right or left. Bitwise operators may not be applied to float or double.

Operator Meaning

& Bitwise AND

! Bitwise OR

^ Bitwise Exclusion

~ One’s complement

<< Shift left

>> Shift right

>>> Shift right with zero fill

Department of Information Technology 1.32

Page 33: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

SPECIAL OPERATORS:Java supports some special operators of interest such as instanceof and member

selection operator(.).

Instanceof operator:The instanceof is a reference operator and returns true if the object on the left on

side is an instance of the class given on the right hand side. This operator allows us to determine whether the object belongs to the particular class or not

Eg:

person instanceof student

the above example is true if the object person belongs to the class student, otherwise it is false.

Dot operator:The dot operator (.) is usedto access instance variable and methods of class

objects.

Eg:person.age();person.salary();

It is used to access classes and sub-packages from a package

CONTROL STATEMENTS:

Java language possess such decision making capabilities and supports the following statements known as control or decision statements.

1. If statement2. Switch statement3. Conditional operator statement

In this chapter, we shall discuss the features, capabilities and applications of these statements which are classified as selection statement.

DECISION MAKING STATEMENTS:

Department of Information Technology 1.33

Page 34: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

IF STATEMENT:

The “if” is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used with the conjunction with an expression. It takes the following form:

if(test expression)

Some of the decision making, using if statement are:

1. Simple if statement2. if….else statement3. Nested if….else4. else…if ladder

SIMPLE IF STATEMENT:

The general form of a simple if statement is:

The statement block may be a single statement or a group of statements. If the test expression is true the statement block will be executed, otherwise the statement block will be skipped and the execution will jump to the statement-X.

THE IF-ELSE STATEMENT:

The if-else statement is the extension of the simple if statement. The general form is,

if(test expression){ True statement;}else

Department of Information Technology 1.34

if(test expression) { Statement block; } Statement-X

Page 35: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

{ False statement}statement X;

If the ‘test expression’ is true, then the true statement is executed, otherwise the false statement is executed, not both are executed. In both the cases, the control is transferred subsequently to the statement X.

Example:class IfElseTest{ public static void main(String arg[]){ int number[]={50,65,70.56.81} int even=0,odd=0; for(int i=0; i<number.length;i++){ if((number[i]%2)= =0){ even+=1;} else{ odd+=1;}}System.out.println(“Even Numbers: ”+even + “Odd numbers :”+odd);}

OUTPUT: Even Numbers:3 Odd Numbers:2 NESTING OF IF…ELSE STATEMENTS:

When a series of decisions are involved, we may have to use more than one if…else statement in nested as follows:

Department of Information Technology 1.35

Page 36: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

if(test condition1) { if( test condition2) {

Statement 1; } else {

Statement 2; }

} else {

Statement 3; }

Statement X;

Here the if along with the “test condition1” is associated along with the last else, then the if along with “test condition2” is associated with the second else statement.

Example: class IfElseNesting{ public static void main(String arg[]){ int a=325; int b=712; int c=478;System.out.println)”Largest Value is:”);

if(a>b){

if(a>c) { System.out.println(a); }else {System.out.println(c); }}else{

if(c<b){System.out.println(c);

Department of Information Technology 1.36

Page 37: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

} else{ System.out.println(b);} } }

} }

Output:

Largest value is: 712

THE ELSE IF LADDER: There is a another way of putting is together when multipath decisions are

involved. A multipath decision is a chain of its in which the statement associated with each else is an if. It takes the following general form:

if(condition 1)

statement 1;

else if(condition 2)

statement 2;

else if(condition 3)

statement3;

………………………………….

else if(condition n)

statement n;

else

default- statement; statement-X

Example:class ElseIfLadder{ public static void main(String arg[]) { int rollNumber[]={111,222,333,444};

Department of Information Technology 1.37

Page 38: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

int marks[]={81,75,43,58}; for(int i=0;i<rollNumber.length:i++) { if (marks[i] > 79) System.out.println(rollNumber[i] + “Honours”);elseif (marks[i] > 59)

System.out.println(rollNumber[i] + “ 1st division”):elseif (marks[i] > 49)

System.out.println(rollNumber[i] + “2nd division”);else

System.out.println(rollNumber[i] + “FAIL”); } } }

THE SWITCH STATEMENT: We have seen that one of the many alternatives is to be selected, we can

design a program using if statements to control the selection. Java has a built-in multiway decision statement known as switch

switch(expression) { case 1: block-1 break; case 2: block-2; break; . . . . . . . . . . default: default-block; } Statement-X;

The expression is an integer expression or characters. Value-1,value-….are constant or constant expressions and they are known as case variables. Each of these values should be unique within a switch statement, block-1,block-2… are the statement lists and may contains zero or more statements. There is no need to put braces around these block but it is important to note that the case labels end with a colon(:).

Department of Information Technology 1.38

Page 39: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

The break statement is given at end of each case. The default is an optional case. When present it will be executed if the value of an expression does not match with any of the case values. If not present, no action takes place if all the matches get fail and control goes to the statement x.

LOOPING STATEMENTS: A program loop consists of two segments, one known as the body of the loop

and the other known as the control statements. The control statements tests certain condition and then directs the repeated execution of the statements contained in the body of the loop

Depending upon the position of the control statement in the loop, a control structure can be classified as the entry controlled loop and the exit controlled loop.

A looping process, in general would include the following four steps:1. Setting and initialization of a counter.2. Execution of the statements in the loop3. Test for a specified condition for execution of the loop.4. Incrementing the counter.

The java language provides for three constructs for performing loop operations. They are:

While construct. Do-while construct. For construct.

THE WHILE STATEMANT: The simplest of all the looping structures in Java is the while statement. The basic format of the while statement is:

Initializationwhile( test condition){ Body of the loop;}

The ‘while’ is a entry controlled loop statement. The test condition is evaluated first, if it is true then the body of the loop is executed. The process takes place repeatedly until the condition fails. Once the condition fails the control is transferred out of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements.

Example: class WhileTest

Department of Information Technology 1.39

Page 40: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

{

public static void main(String arg[])

{

int sum=0;

int n=1;

while(n < = 10)

{

sum = sum + n * n;

n = n + 1;

}

System.out.println(“ Sum=” + sum);

}

The body of the loop is executed for 10 times for n=1,2,3….10 times. Each time it adds the square of the values of n, which is incremented inside the loop. The condition may also be given as n < 11, the output might have been the same.

THE DO-WHILE STATEMENT:The while loop construct that we have already discussed in the previous

section makes a test condition before the loop is executed. Therefore, the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. The syntax may be given as:

Syntax:Initializationdo{ Body of the loop}while( test condition);On reaching the do statement, the program proceeds to evaluate the body of the loop

first. At the end of the loop the test condition in the while statement is evaluated.If the condition is true, then the program continues to execute once again.

WHILE DO WHILE

It is a loop that will execute only if the It is a loop that execute atleast once even if the

Department of Information Technology 1.40

Page 41: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

condition is true condition is false

It is an entry controlled loop It is an exit controlled loop

It is generally used for implementing common looping situations

It is typically used for implementing menu based programs where the menu is required to be printed atleast once

THE FOR STATEMENT:

The for loop is another entry controlled loop that provides more conscise loop control structure. The general form is:

for( initialization ; test condition ; increment/decrement){

Body of the loop}

Example: class Fortest{ public static void main(String arg[]) {

long p; int n; double q; System.out.println(“ 2 to power-n n 2 to power n”); p=1; for( n=0; n < 10;n++) { if(n = = 0) p = 1;else p = p * 2;q=1.0/ (double) p;System.out.println(“ ” + q + “ ” +n + “ ” +p)}}}

Department of Information Technology 1.41

Page 42: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

OUTPUT:

2 to power-n n 2 to power n1 0 10.5 1 20.25 2 40.125 3 80.0625 4 16

ARRAYS:

An array is a group of contiguous or related data items that share a common name. The ability to use a single name to represent a collection of items.

Syntax:

Array arrayname[ index ];

Example:

Salary[10];

ONE DIMENSIONAL ARRAY:

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

Example:

Number[10];

CREATING AN ARRAY:

Arrays must be declared and created in the computer memory before they are used. Creation of an array involves three steps:

1. Declaring the array2. Creating memory locations3. Putting values into the memory locations.

DECALARATION OF ARRAYS

Arrays in java may be declared in two forms:

Form1 : type arrayname[];

Department of Information Technology 1.42

Page 43: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Form2 : type []arrayname;

Examples:

Int number[];

Float average[];

CREATION OF ARRAYS:

After declaring an array, we need to create it in the memory. Java allows us to create arrays using new operator only.

Arrayname = new type[size];

Examples:

Number = new int[5];

Average = new float[10];

These lines create necessary memory locations for the arrays number and average and designate them as int and float respectively.

INTIALIZATION OF ARRAYS:

The final step is to put into the array created. This process is known as initialization. This is done using the array subscripts as shown below.

Arrayname[subscript] = value;

Example:

Number[0]=35;

Number[1]=40;

We can also initialize arrays automatically in the same way as the ordinary variables when they are declared, as shown below:

Type arrayname[]={ list of values};

ARRAY LENGTH:

All arrays store the allocated size in a variable named length. We can obtain the length of the array a using a.length.

Example:

Department of Information Technology 1.43

Page 44: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Int aSize = a.length;

TWO DIMENSIONAL ARRAYS:

There will be situation where a table of values will have to be stored. Java allows us to define such tables of items by using two dimensional arrays.

Example:

V[4][3];

The first index selects the row and the second index selects the column within that row.

VARIABLE SIZE ARRAYS:

Java treats multidimensional array as “arrays of arrays”. It is possible to declare a two dimensional array as follows:

Int x[][]= newint[3][];

X[0]=new int[2];

X[1]=new int[4];

X[2]=new int[3];

STRINGS:

String manipulation is the most common part of many java programs. Strings represent a sequence of characters. The easiest way to represent a sequence of characters in java is by using a character array.

Example:

Char charArray[]=new char[4];

CharArray[0]= ‘j’;

charArray[1]=’a’;

charArray[2]=’v’;

charArray[3]=’a’;

strings may be declared and created as follows:

String StringName;

Department of Information Technology 1.44

Page 45: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

StringName = new String(“string”);

Example:

String firstName;

firstName=new String(“Anil”);

String Arrays:

We can also create and use arrays that contain strings. The statement will create an itemArray of size 3 to hold three string constants. We can assign the strings to the itemArray element using three different statements or more efficiently using a for loop.

String itemArray[]=new String[3];

STRING METHODS:

The strings class defines a number of methods that allow us to accomplish a variety of string manipulation tasks.

Example:

compareTo() to sort an array of strings.

STRINGBUFFER CLASS:

String Buffer is a peer class of String. While String creates strings of fixed_length, StringBuffer creates strings of flexible length that can be modified in terms of both length and content. We can insert characters and substrings in the middle of a string, or append another string to the end.

S1.setChartAtn,’x’

S1.append(s2)

S1.insert(n, s2)

S1.setlength(n)

VECTORS:

This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. The objects do not have to be homogeneous. Arrays can be easily implemented as vectors. Vectors are created like arrays as follows:

Vector intVect = new Vector ();

Department of Information Technology 1.45

Page 46: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Vector list = new Vector (3);

Vectors posses a number of advantages over arrays.

1. It is convenient to use vectors to store objects.2. A vector can be used to store a list of objects that may vary in size.3. We can add and delete objects from the list as and when required.

WRAPPER CLASSES:

Vectors cannot handle primitive data types like int, float, long, char and double. Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang.package.

Simple type wrapper class

Boolean BooleanChar characterDouble doubleFloat floatInt integerLong longPACKAGES:

Packages are Java’s way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. In fact, packages act as “containers” for classes.

We have repeatedly stated that one of the main features of OOP is its ability to reuse the code already created.

One way of achieving this is by extending the classes and implementing the interfaces.

Another way of achieving the reusability in Java, therefore is to use packages.

By organizing our classes into packages we achieve the following benefits:

1. The classes contained in the packages of other programs can be easily reused.2. In packages, classes can be unique compared with classes in other packages. That is, two

classes in two different packages can have same name. They may be refer by their fully qualified name, comprising the package name and the class name.

3. Packages provide a way to hide classes thus preventing other programs or packages from accessing classes that are meant for internal use only.

4. Packages also provide a way for separating “design” from “coding”.First,we can design classes and decide their relationships and then we can implement the Java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of design.

Department of Information Technology 1.46

Page 47: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

TYPES OF PACKAGES:

Packages is of two types. They are:

Java API Packages User Defined Package

JAVA API PACKAGE:

Java API provides a large number of classes grouped into different packages according to functionality. Most of the time we use the packages with the JavaAPI. It shows the functional breakdown of packafes that are frequently used in the programs.

Java.langLanguage support classes. These are classes that Java compiler itself uses and therefore itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions.

Java.utilLanguage utility classes such as vectors,hash tables,random numbers,date etc.. Java.ioInput/Output support classes. They provide facilities for the input and output of

data. Java.awtSet of packages for implementing graphical user interface. They include

classes for windows,buttons,lists,menus and so on. Java.netClasses for networking. They include classes for communicating with local

computers as well as with internet servers. Java.appletClasses for creating and implementing applets.

USER DEFINED PACKAGE:

Department of Information Technology 1.47

lang

Java API

util io awt net applet

Page 48: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

User defined package is created by user. The user defined package is of two types. They are:

Creating a package Accessing a package

CREATING A PACKAGE:

Java system packages are organized and used. creating our own packages is by:

We must first declare the name of the packages using the package keyword followed by a package name. This must be the first statement in a Java source file. Then we define a class, just as we normally define a class. Here is an example:

Package first Package; // package declarationPublic class First-Class // class definition{……………….……………….………………}

We want to use a class in a member of places in the program or we may like to use many of the classes contained in a package. We may achieve this easily as follows:

import packagename.classname;

Or

o import package name.*

These are known as import statement and must appear at the top of the file, before any class declarations, import is a keyword.

Creating our own package involves the following steps:

1 Declare the packages at the beginning of a file using the form

Packages packages name:

2. Define the class that is to be put in the package and declare it public.

3. Create a subdirectory under the directory where the main source files are stored.

4. Store the listing as the classname.java file in the subdirectory created.

5. Compile the file. This creates .class file in the subdirectory.

Department of Information Technology 1.48

Page 49: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

ACCESSING A PACKAGE:

A Java system package can be accessed either using a fully quantifies class name or using a shortcut approach through the import statement. We can use the import statement when there are many references to a particular package name are too long and unwidely.

The general form of import statement for searching a class is as follows:

Import package1 [.package2] [.package3].classname;

We can access a package by,

import package name. class name;

We can also use another approach as follows:

import packagename.*;

Example Program of a Package:

Package addsubpublic class addition{public class add(int a,int b){int c=a+b;System.out.println(c);}}public class subtraction{public void sub(int a,int b){int c=a-b;System.out.println(c);}}

Package muldivpublic class multiplication{public void mul(int a,int b){int c=a*b;Department of Information Technology 1.49

Page 50: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

System.out.println( c );}}public class division{public void div(int a,int b){int c=a/b;System.out.println( c );}}

import addsub.*;import muldiv.*;class TestPackage{public static void main(String arg[]){addition a=new addition;a.add(10,20);subtraction s=new subtraction;s.sub(20,45);multiplication m=new multiplication;m.mul(5,6);division d=new division;d.div(2,5);}}GARBAGE COLLECTION :

Java handles deallocation automatically. The technique that accomplishes this is called garbage collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need to destroy objects as in C++. It will not occur simply because one or more objects exist that are no longer used.

The finalize( ) Method

To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class.

Department of Information Technology 1.50

Page 51: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Inside the finalize( ) method you will specify those actions that must be performed before an object is destroyed.

The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects.

The finalize( ) method has this general form:

protected void finalize( ) { // finalization code here }

INTERFACES:

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways:

An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface

matching the name of the file.

The bytecode of an interface appears in a .class file.

Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

You cannot instantiate an interface. An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

Department of Information Technology 1.51

Page 52: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:

Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */import java.lang.*;//Any number of import statements

public interface NameOfInterface{ //Any number of final, static fields //Any number of abstract method declarations\}

Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.

Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

Methods in an interface are implicitly public.

Example:

/* File name : Animal.java */interface Animal {

public void eat();public void travel();

}

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

Aclass uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Department of Information Technology 1.52

Page 53: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

/* File name : MammalInt.java */public class MammalInt implements Animal{

public void eat(){ System.out.println("Mammal eats"); }

public void travel(){ System.out.println("Mammal travels"); }

public int noOfLegs(){ return 0; }

public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); }}

This would produce following result:

Mammal eatsMammal travels

Extending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

//Filename: Sports.javapublic interface Sports{ public void setHomeTeam(String name); public void setVisitingTeam(String name);}

//Filename: Football.javapublic interface Football extends Sports{

Department of Information Technology 1.53

Page 54: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter);}

//Filename: Hockey.javapublic interface Hockey extends Sports{ public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot);}

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

public interface Hockey extends Sports, Event

Inheritance Among Interfaces

●Interfaces are not part of the class hierarchy

● However, interfaces can have inheritance relationship among themselves.

Eg:

public interface PersonInterface

{void doSomething();

}

public interface StudentInterface extends PersonInterface {Department of Information Technology 1.54

Page 55: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

void doExtraSomething();

}

INNER CLASSES:

Inner classes, also called Nested Classes, are nothing but classes that are defined within other classes. The nesting is a relationship between classes, not objects.

Java inner classes have feature that makes them richer and more useful. An object of an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of the outer object. Only static inner classes don’t have this pointer. It is actually invisible when we write the code, but compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM.

Inner classes may be defined with following access modifiers : public, protected, private, or with default package access.

The syntax for inner class is as follows:

RUN-TIME TYPE IDENTIFICATION

This takes two forms: “traditional” RTTI, which assumes that you have all the types available at compile-time and run-time, and the “reflection” mechanism, which allows you to discover class information solely at run-time. The “traditional” RTTI will be covered first, followed by a discussion of reflection.

The need for RTTIConsider the now familiar example of a class hierarchy that uses polymorphism. The generic type is the base class Shape, and the specific derived types are Circle, Square, and Triangle:

Thus, you generally create a specific object (Circle, Square, or Triangle), upcast it to a Shape (forgetting the specific type of the object), and use that anonymous Shape reference in the rest of the program.

As a brief review of polymorphism and up casting, you might code the above example as follows:Shapes.javaimport java.util.*;class Shape {

Department of Information Technology 1.55

Page 56: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

void draw() {System.out.println(this + ".draw()");}}class Circle extends Shape {public String toString() { return "Circle"; }}class Square extends Shape {public String toString() { return "Square"; }}class Triangle extends Shape {public String toString() { return "Triangle"; }}public class Shapes {public static void main(String[] args) {ArrayList s = new ArrayList();s.add(new Circle());s.add(new Square());s.add(new Triangle());Iterator e = s.iterator();while(e.hasNext())((Shape)e.next()).draw();} }

Once the Class object for that type is in memory, it is used to create all objects of that type. If this seems shadowy or if you don’t really believe it, here’s a demonstration program to prove it:SweetShop.javaExamination of the way the class loader works.class Candy {static {System.out.println("Loading Candy");}}class Gum {static {System.out.println("Loading Gum");} }class Cookie {static {System.out.println("Loading Cookie");} }public class SweetShop {public static void main(String[] args) {System.out.println("inside main");new Candy();System.out.println("After creating Candy");

Department of Information Technology 1.56

Page 57: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

try {Class.forName("Gum");} catch(ClassNotFoundException e) {e.printStackTrace(System.err);}System.out.println("After Class.forName(\"Gum\")");new Cookie();System.out.println("After creating Cookie");} }

JAVA I/O CLASSES:Introduction

This section introduces the basic organization of the java.io classes, consisting of:* Input and output streams* Readers and writers* Data and object I/O streams

Input stream classesIn the InputStream class, bytes can be read from three different sources:

* An array of bytes* A file* A pipe

Sources, such as ByteArrayInputStream and FilterInputStream, subclass the InputStream class. The subclasses under InflatorInputStream andFilterInputStream are listed in the figure below.

Department of Information Technology 1.57

Page 58: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

InputStream methods

Various methods are included in the InputStream class.

* abstract int read() reads a single byte, an array, or a subarray of bytes. It returnsthe bytes read, the number of bytes read, or -1 if end-of-file has been reached.

* read(), which takes the byte array, reads an array or a subarray of bytes and returns a-1 if the end-of-file has been reached.

* skip(), which takes long, skips a specified number of bytes of input and returns thenumber of bytes actually skipped.

* available() returns the number of bytes that can be read without blocking. Both theinput and output can block threads until the byte is read or written.

* close() closes the input stream to free up system resources. OutputStream classes

Bytes can be written to three different types of sinks:* An array of bytes* A file* A pipeThe following figure shows OutputStream classes.

Department of Information Technology 1.58

Page 59: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

CheckedOutputStream and DigestOutputStream are part of the FilterOutputStream class. They calculate checksums or message digests on the output.

DeflatorOutputStream writes to an OutputStream and creates a zip file. This class does compression on the fly.

The PrintStream class is also a subclass of FilterOutputStream, which implements a number of methods for displaying textual representation of Java primitive types.

For example:

* println(long)* println(int)* println(float)* println(char)

DataOutputStream implements the DataOutput interface. DataOutput defines the methods required for streams that can write Java primitive data types in a machine-independent binary format.

OutputStream methods

The OutputStream class provides several methods:

* The abstract void write() method takes an integer byte and writes a single byte.* The void write() method takes a byte array and writes an array or subarray of bytes.* The void flush() method forces any buffered output to be written.* The void close() method closes the stream and frees up system resources.It is important to close your output files because sometimes the buffers do not get completelyflushed and, as a consequence, are not complete.

Department of Information Technology 1.59

Page 60: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

DataInput and DataOutput

The DataInput and DataOutput classes define the methods required for streams that can read Java primitive data types in a machine-independent binary format.

They are implemented by RandomAccessFile. The ObjectInput interface extends the DataInput interface and adds methods for deserializing objects and reading bytes and arrays of bytes. You can learn more about serialization in Object serialization.

The ObjectOutputStream class creates a stream of objects that can be deserialized by the ObjectInputStream class.

The ObjectOutput interface extends the DataOutput interface and adds methods for serializing objects and writing bytes and arrays of bytes.

ObjectOutputStream is used to serialize objects, arrays, and other values to a stream.

Character input streams

Let's take a look at the different character input streams in the java.io package.* Strings* Character arrays* Pipes

InputStreamReader is a character input stream that uses a byte input stream as its data source and converts it into Unicode characters.

LineNumberReader, a subclass of BufferedReader, is a character input stream that keeps track of the number of lines of text that have been read from it.

PushbackReader, a subclass of FilterReader, is a character input stream that uses another input stream as its input source and adds the ability to push characters back onto the stream.

Character output streams

Let's take a look at the different character output streams in the java.io package. There are several branches of this inheritance tree you can explore. Like Readers, any of the branches are available. Sinks for Writer output can be:* Strings* CharArray* Pipes

-OutputStreamWriter uses a byte output stream as the destination for its data.

Department of Information Technology 1.60

Page 61: sureshsmvec.files.wordpress.com€¦  · Web viewUnit I. Unit Structure. Introduction to Object Oriented Programming. Java on the Internet. Multithreading and Persistence. Java Keywords

Java & Internet Programming Lecture Notes

-BufferedWriter applies buffering to a character output stream, thus improving output efficiency by combining many small write requests into a single large request.

-FilterWriter is an abstract class that acts as a superclass for character output streams.The streams filter the data written to them before writing it to some other character outputstream.

-PrintWriter is a character output stream that implements print() and println()methods that output textual representations of primitive values and objects.

Department of Information Technology 1.61