SlideShare a Scribd company logo
1 of 24
Download to read offline
UNIT-III INPUT AND OUTPUT STREAMS
1. Code a Graphics method in java to draw String “Hello World” from coordinates(100,200)
import java.applet.*;
import java.awt.*;
/*
<applet code = "Demo.class", height=200 width=200>
</applet>
*/
public class Demo extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World",100,200);
}
2. }
2. What is an applet?
Applets are the java program that can be run on a java enabled web browser. An applet is typically
embedded inside a web page and runs in the context of a browser. The Applet class provides the
standard interface between the applet and the browser environment.
3. What is the difference between applications and applets?
Applet Application
1. Applet do not use main method for initiating
the execution of the program
Applet use main method for initiating the
execution of the program
2 They cannot run independently. They can run
inside a web page using HTML Tag
They can run independently
3 It cannot read and write files in the computer It can read and write files in the computer
4 It cannot communicate with other servers on
the network
It can communicate with other servers on
the network
5 It is restricted to use libraries from other
language c,c++
It is use libraries from other language
c,c++
6 In applet,AWT methods drawstring() which
outputs a string to a specified X,Y location.
Output is performed by
System.out.println();
4. What is a steam and which class allows your to read objects directly from stream?
A stream can be defined as a sequence of data. The InputStream is used to read data from a source
and the OutputStream is used for writing data to a destination. The ObjectInputStream class
supports the reading of objects from input streams.
5. Difference between init() and start() methods.
Init() method is called when the applet is loaded by the Browser for execution.The
Programmer can initialize variables, create objects, load imags etc. This method is called only once
in the life cycle.
The start() method is called by init() method ,when applet is brought back from minimize (seen
in status bar) position. In minimize position, applet looses focus of the viewer. When the applet
get focus, Browser calls first start() and then paint(). This method is called and executed multiple
times whenever the applet gains focus
6. How to set foreground and background color of the applet?
import java.applet.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
/*
<applet code = "Demo.class", height=200 width=200>
</applet>
*/
public class Demo extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.YELLOW);
setForeground(Color.RED);
g.drawString("hello java",100,100);
}
}
7. What are the methods that control an applet’s on-screen appearance
- The paint() method is called in situations the applet window being overwritten by another
window or uncovered or the applet window being resized.
- The update() is called when a portion of its window be redrawn. It is defined by the AWT.
8. Explain how to read information from the applet parameters.
9. What are the ways in which we can pass the parameter to an applet?
We can supply parameter to an applet using <PARAM> tag. Each <PARAM> tag has a
name attribute and value attribute.
<applet>
<param name=”color” value=”text”>
</applet>
The getParameter() method of the Applet class can be used to retrieve the
parameters passed from the HTML pag
Example1:
import java.applet.*;
import java.awt.*;
/*<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="hai"> </applet>
*/
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
10. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. Whenever the applet needs to
update the information displayed in it window ,it calls repaint();
11. Present the structure of Applet.
init() method - Can be called when an applet is first loaded start() method
paint() method - Can be called when the applet is minimized or maximized.
stop() method - Can be used when the browser moves off the applet’s page
destroy() method - Can be called when the browser is finished with the applet.
import java.awt.*;
import java.applet.*;
/*
<applet code="DemoApplet" width=400 height=200>
</applet>
*/
public class DemoApplet extends Applet
{
public void init()
{
//initialization
}
public void start()
{
//start or resume
}
public void stop()
{
//suspends execution
}
public void destroy()
{
//perform shut down activites
}
public void paint(Graphics g)
{
//display the content of window
}
}
12. What is a stream? Draw the hierarchy of stream class.
A stream is continuous group of data or a channel through which data flows from one point to
another point. Java implements streams within class hierarchies defined in the java.io package.
13. Distinguish between Input stream and reader classes & Output stream and writer
classes.
An Streams work at the byte level, they can read (InputStream) and write (OutputStream)
bytes or list of bytes to a stream.
Reader/Writers add the concept of character on top of a stream. Since a character can only
be translated to bytes by using an Encoding, readers and writers have an encoding component (that
may be set automatically since Java has a default encoding property). The characters read (Reader)
or written (Writer) are automatically converted to bytes by the encoding and sent to the stream.
14. Explain how to implement an applet into a web page using applet tag
To view an applet in the browser, following steps need to be followed: Compile the applet
you have written … the .java file so as to get the .class file. Then, include the following code in
your .html file:
<APPLET CODE="XZY.class" WIDTH=100 HEIGHT=100>
</APPLET>
And then open the file using a java enabled browser.
Simple example of Applet by html file
import java.applet.Applet;
import java.awt.Graphics;
public class Demo1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
15. What are the attributes of APPLET tag?
- height : Defines height of applet
- width: Defines width of applet
- align: Defines the text alignment around the applet
- alt: An alternate text to be displayed if the browser support applets but cannot run this applet
- archive: A URL to the applet when it is stored in a Java Archive or ZIP file
- code: A URL that points to the class of the applet
- codebase: Indicates the base URL of the applet if the code attribute is relative
- hspace: Defines the horizontal spacing around the applet
- vspace: Defines the vertical spacing around the applet
- name: Defines a name for an applet
- object: Defines the resource name that contains a serialized representation of the applet
- title: Display information in tool tip
16. How can we determine the height and width of the applet?
When applet is running inside a web browser the size of an applet is set by the height and width
attributes and cannot be changed by the applet. The 'getSize()' method is retrieved the size of an
applet.
17. What is meant by getCodeBase and getDocumentBase method?
In Applet, The getCodebase() method is also commonly used to establish a path to other files or
folders that are in the same location as the class being run. The getDocumentBase() method is used
to return the URL of the directory in which the document is resides.
18. What are the different ways of running an applet?
There are two standard ways in which you can run an applet :
1. Executing the applet within a Java-compatible web browser.
<applet code="HelloWorld" width=200 height=60>
</applet>
2. Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes
your applet in a window. This is generally the fastest and easiest way to test your applet.
appletviewer RunHelloWorld.html
19. Why the applet classes are declared as public?
A java applet is a small program that can be placed within a web page, like a small game or a
calculator.
-> When ever we declare the class as public, it means it is possible to access this class inside the
same package and outside of the current package.
-> The server needs to access some of the applet's attributes, so it is declared as public. If the applet
was private, nobody would be able to access it.
-> Also because classes from other packages such as sun.applet.AppletPanel cannot access it.
20. State the usage of System.console.println().
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords. If you read password using Console class, it will not be displayed to the user.
. System.console() provides methods for reading password without echoing characters
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
D:ann-runit3>java ReadStringTest
Enter your name:
Raj
Welcome Raj
21. How will you pass parameters to applet
Parameter in Applet
We can supply parameter to an applet using <PARAM> tag.Each <PARAM> tag has a name
attribute and value attribute.
<applet>
<param name=”color” value=”text”>
</applet>
Parameters are passed on an applet when it is loaded.
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:
Example1:
import java.applet.*;
import java.awt.*;
/*<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="hai"> </applet>
*/
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
22. What is Byte stream in Java?
Byte streams process data byte by byte (8 bits). Programs use byte streams to perform
input and output of 8-bit bytes. All byte stream classes are descended from InputStream and
OutputStream. For example FileInputStream is used to read from source and
FileOutputStream to write to the destination. Byte oriented reads byte by byte. A byte stream
is suitable for processing raw data like binary files.
23. What is Character stream in java?
In Java, characters are stored using Unicode conventions. Character stream is useful when
we want to process text files. These text files can be processed character by character. A character
size is typically 16 bits. Reader is used to read from source and Writer to write to the
destination.
24. What is the use of native methods in Applets?
Native methods and native libraries are bits of platform-specific executable code (written
in languages such as C or C++) contained in libraries or DLLs. Applet cannot access the native
methods
PART-B:
1. Explain I/O streams with suitable examples
Stream
Java programs perform input/output through streams. A stream is an abstraction that either produces or
consumes information as shown in Figure 3.1. A stream is linked to a physical device by the Java I/O
system. All streams behave in the same manner, even if the actual physical devices to which they are
linked differ. Thus, the same I/O classes and methods can be applied to any type of device. This means
that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network
socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Streams
are a clean way to deal with input/output without having every part of code understands the difference
between a keyboard and a network. Java implements streams within class hierarchies defined in the java.io
package.
Figure 3.1 Streams usage
Java 2 defines two types of streams based on data pass through streams: byte and character.Byte streams
provide a convenient means for handling input and output of bytes. Byte streams are used, for example,
when reading or writing binary data. Character streams provide a convenient means for handling input
and output of characters. They use Unicode and, therefore, can be internationalized. Also, in some cases,
character streams are more efficient than byte streams.
3.2.1 The Byte Stream Classes
• Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream.
• To use the stream classes, we must import java.io.
• The abstract classes InputStream and OutputStream define several key methods that the other
stream classes implement.
• Two of the most important are read ( ) and write ( ), which, respectively, read and write bytes of
data. Both methods are declared as abstract inside InputStream and OutputStream. They are
overridden by derived stream classes.
Byte Stream Classes
Stream Class Meaning
BufferedInputStream Buffered input stream
BufferedOutputStream Buffered output stream
ByteArrayInputStream Input stream that reads from a byte array
ByteArrayOutputStream Output stream that writes to a byte array
DataInputStream An input stream that contains methods for reading the Java
standard
data types
DataOutputStream An output stream that contains methods for writing the Java
standard
data types
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that writes to a file
FilterInputStream Implements InputStream
FilterOutputStream Implements OutputStream
InputStream Abstract class that describes stream input
OutputStream Abstract class that describes stream output
PipedInputStream Input pipe
PipedOutputStream Output pipe
PrintStream Output stream that contains print( ) and println( )
PushbackInputStream Input stream that supports one-byte “unget,” which returns a
byte to
the input stream
RandomAccessFile Supports random access file I/O
Example:
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available(); //returns available bytes count
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A
The Character Stream Classes
• Character streams are defined by using two class hierarchies. At the top are two abstract classes,
Reader and Writer. These abstract classes handle Unicode character streams. Java has several
concrete subclasses of each of these.
• The abstract classes Reader and Writer define several key methods that the other stream classes
implement. Two of the most important methods are read ( ) and write ( ), which read and write
characters of data, respectively. These methods are overridden by derived stream classes.
Character Stream Class
Stream Class Meaning
BufferedReader Buffered input character stream
BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Output stream that writes to a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
FilterReader Filtered reader
FilterWriter Filtered writer
InputStreamReader Input stream that translates bytes to characters
LineNumberReader Input stream that counts lines
OutputStreamWriter Output stream that translates characters to bytes
PipedReader Input pipe
PipedWriter Output pipe
PrintWriter Output stream that contains print( ) and println( )
PushbackReader Input stream that allows characters to be returned to the input stream
Reader Abstract class that describes character stream input
StringReader Input stream that reads from a string
StringWriter Output stream that writes to a string
Writer Abstract class that describes character stream output
Example:
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to java
Output:
Welcome to java
2. Explain the Reader Stream class hierarchy with an example program.
3. Explain the Writer Stream class hierarchy with an example program.
The Character Stream Classes
• Character streams are defined by using two class hierarchies. At the top are two abstract classes,
Reader and Writer. These abstract classes handle Unicode character streams. Java has several
concrete subclasses of each of these.
• The abstract classes Reader and Writer define several key methods that the other stream classes
implement. Two of the most important methods are read ( ) and write ( ), which read and write
characters of data, respectively. These methods are overridden by derived stream classes.
Character Stream Class
Stream Class Meaning
BufferedReader Buffered input character stream
BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Output stream that writes to a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
FilterReader Filtered reader
FilterWriter Filtered writer
InputStreamReader Input stream that translates bytes to characters
LineNumberReader Input stream that counts lines
OutputStreamWriter Output stream that translates characters to bytes
PipedReader Input pipe
PipedWriter Output pipe
PrintWriter Output stream that contains print( ) and println( )
PushbackReader Input stream that allows characters to be returned to the input
stream
Reader Abstract class that describes character stream input
StringReader Input stream that reads from a string
StringWriter Output stream that writes to a string
Writer Abstract class that describes character stream output
Example:
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to java
Output:
Welcome to java
JAVA SYSTEM CLASS
• All Java programs automatically import the java.lang package.
• This package defines a class called System, which encapsulates several aspects of the run-time
environment.
• System contains three predefined stream variables, in, out, and errs. These fields are declared as
public and static within System. This means that they can be used by any other part of your
program and without reference to a specific System object.
• System.out refers to the standard output stream. By default, this is the console.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which also is the console by default.
• System.in is an object of type InputStream; System.out and System.err are objects of type
PrintStream. These are byte streams, even though they typically are used to read and write
characters from and to the console.
•
READING CONSOLE INPUT
In Java, console input is accomplished by reading from System.in. To obtain a character-based stream
that is attached to the console, you wrap System.in in a BufferedReader object, to create a character
stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is
shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created.
Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes
to characters. To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all
together, the following line of code creates a BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console through
System.in.
3.4.1 Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value.
It returns –1 when the end of the stream is encountered.
import java.io.*;
class BRRead {
public static void main(String args[])throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader
class. Its general form is shown here:
String readLine( ) throws IOException
Example:
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
4. Explain about reading and writing file in java.
FileInputStream and FileOutputStream
Reading a content from a file
import java.io.*;
class FDemoo
{
public static void main(String args[]) throws Exception
{
FileInputStream fr=new FileInputStream("4.txt");
int ch;
while((ch=fr.read())!=-1)
{
System.out.print((char)ch);
}
}
}
Writing a content to a file
import java.io.*;
class FWDemoo
{
public static void main(String args[]) throws Exception
{
FileOutputStream fo=new FileOutputStream("5.txt");
String name="java programming";
byte[] b=name.getBytes();
fo.write(b);
fo.close();
}
}
5. Explain applet lifecycle? How applet are prepared and executed.
Applets are the java program that can be run on a java enabled web browser. An applet is typically
embedded inside a web page and runs in the context of a browser. The Applet class provides the standard
interface between the applet and the browser environment.
All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also
import java.awt. Execution of an applet does not begin at main( ). Actually, few applets even have main(
) methods. Instead, execution of an applet is started and controlled with an entirely different mechanism.
Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The
applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the
HTML file.
To view and test an applet more conveniently, simply include a comment at the head of your Java
source code file that contains the APPLET tag. This way, your code is documented with the necessary
HTML statements needed by your applet, and you can test the compiled applet by starting the applet
viewer with your Java source code file specified as the target. Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200
pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier,
all of the applets shown in this notes will contain the appropriate APPLET tag embedded in a comment.
Applets override a set of methods that provides the basic mechanism by which the browser or
applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ),
stop( ), and destroy( ), apply to all applets and are defined by Applet. Default implementations for all of
these methods are provided. Applets do not need to override those methods they do not use.
AWT-based applets will also override the paint( ) method, which is defined by the AWT
Component class. This method is called when the applet’s output must be redisplayed.
import java.awt.*;
import java.applet.*;
/* <applet code="AppletSkel" width=300 height=100></applet> */
public class AppletSkel extends Applet
{
public void init()
{
// initialization
}
public void start()
{
// start or resume execution
}
public void stop()
{
// suspends execution
}
public void destroy()
{
// perform shutdown activities
}
public void paint(Graphics g)
{
// redisplay contents of window
}
}
It is important to understand the order in which the various methods shown in the skeleton are called.When
an applet begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
Let’s look more closely at these methods.
1. init(): This method is intended for whatever initialization is needed for an applet.
2. start(): This method is automatically called after init method. It is also called whenever user returns
to the page containing the applet after visiting other pages.
3. stop(): This method is automatically called whenever the user moves away from the page
containing applets. This method can be used to stop an animation.
4. destroy(): This method is only called when the browser shuts down normally.
5. paint():The paint( ) method is called each time applet’s output must be redrawn. This situation
can occur for several reasons. For example, the window in which the applet is running may be
overwritten by another window and then uncovered. Or the applet window may be minimized and
then restored. paint( ) is also called when the applet begins execution. The paint( ) method has
one parameter of type Graphics. This parameter will contain the graphics context, which describes
the graphics environment in which the applet is running. This context is used whenever output to
the applet is required.
PART C
1. Write an applet program that sets the foreground and back ground colours and outputs
a string.
Setting background and foreground color
import java.applet.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
/*
<applet code = "BackgroundColorApplet.class", height=200 width=200>
</applet>
*/
public class BackgroundColorApplet extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.YELLOW);
setForeground(Color.RED);
g.drawString("hello java",100,100);
}
}
2. Write an example program that demonstrate passing parameters to Applets
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
3. Write an java program to demonstrate applet skeleton
APPLET SKELETON
Most applets override these four methods. These four methods forms Applet lifecycle.
• init() : init() is the first method to be called. This is where variable are initialized. This method is
called only once during the runtime of applet.
• start() : start() method is called after init(). This method is called to restart an applet after it has
been stopped.
• stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
• destroy() : destroy() method is called when your applet needs to be removed completely from
memory.
import java.awt.*;
import java.applet.*;
/* <applet code="AppletSkel" width=300 height=100></applet> */
public class AppletSkel extends Applet
{
public void init()
{
// initialization
}
public void start()
{
// start or resume execution
}
public void stop()
{
// suspends execution
}
public void destroy()
{
// perform shutdown activities
}
public void paint(Graphics g)
{
// redisplay contents of window
}
}
Example of an applet
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
4. Write an applet program to fill colours in Shapes.
import java.awt.*;
import java.applet.*;
public class GDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawRect(20,20,45,78);
g.fillRect(100,20,45,78);
g.drawOval(20,100,45,78);
g.fillOval(100,100,45,78);
g.drawLine(200,50,10,10);
}
}
/*<applet code="GDemo.class" width=700 height=400>
</applet>
*/
5. Write a program to display image using applets.
import java.awt.*;
import java.applet.*;
public class DisImg extends Applet
{
Image pic;
public void init()
{
pic=getImage(getDocumentBase(),"Penguins.jpg");
}
public void paint(Graphics g)
{
g.drawImage(pic,30,30,this);
}
}
/*<applet code="DisImg.class" height=300 width=700>
</applet>*/
Smart material - Unit 3 (1).pdf

More Related Content

Similar to Smart material - Unit 3 (1).pdf

Similar to Smart material - Unit 3 (1).pdf (20)

Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 
Java applet
Java appletJava applet
Java applet
 
Appletjava
AppletjavaAppletjava
Appletjava
 
Applet
AppletApplet
Applet
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
Class notes(week 10) on applet programming
Class notes(week 10) on applet programmingClass notes(week 10) on applet programming
Class notes(week 10) on applet programming
 
Class notes(week 10) on applet programming
Class notes(week 10) on applet programmingClass notes(week 10) on applet programming
Class notes(week 10) on applet programming
 
applet.pptx
applet.pptxapplet.pptx
applet.pptx
 
3. applets
3. applets3. applets
3. applets
 
Java
JavaJava
Java
 
java programming - applets
java programming - appletsjava programming - applets
java programming - applets
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Applet
AppletApplet
Applet
 
Applet1 (1).pptx
Applet1 (1).pptxApplet1 (1).pptx
Applet1 (1).pptx
 
Java applet
Java appletJava applet
Java applet
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
Applets
AppletsApplets
Applets
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 

More from GayathriRHICETCSESTA (20)

nncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdfnncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdf
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
CS8601-IQ.pdf
CS8601-IQ.pdfCS8601-IQ.pdf
CS8601-IQ.pdf
 
CS8601-QB.pdf
CS8601-QB.pdfCS8601-QB.pdf
CS8601-QB.pdf
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
 
Annexure 2 .pdf
Annexure 2  .pdfAnnexure 2  .pdf
Annexure 2 .pdf
 
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.pptcs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
 
ann-ics320Part4.ppt
ann-ics320Part4.pptann-ics320Part4.ppt
ann-ics320Part4.ppt
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
 
nncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdfnncollovcapaldo2013-131220052427-phpapp01.pdf
nncollovcapaldo2013-131220052427-phpapp01.pdf
 
alumni form.pdf
alumni form.pdfalumni form.pdf
alumni form.pdf
 
Semester VI.pdf
Semester VI.pdfSemester VI.pdf
Semester VI.pdf
 
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.pptcs621-lect18-feedforward-network-contd-2009-9-24.ppt
cs621-lect18-feedforward-network-contd-2009-9-24.ppt
 
ann-ics320Part4.ppt
ann-ics320Part4.pptann-ics320Part4.ppt
ann-ics320Part4.ppt
 
Semester V-converted.pdf
Semester V-converted.pdfSemester V-converted.pdf
Semester V-converted.pdf
 
Elective II.pdf
Elective II.pdfElective II.pdf
Elective II.pdf
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
unit 1 and 2 qb.docx
unit 1 and 2 qb.docxunit 1 and 2 qb.docx
unit 1 and 2 qb.docx
 
CS8601-IQ.pdf
CS8601-IQ.pdfCS8601-IQ.pdf
CS8601-IQ.pdf
 

Recently uploaded

MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 

Recently uploaded (20)

MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 

Smart material - Unit 3 (1).pdf

  • 1. UNIT-III INPUT AND OUTPUT STREAMS 1. Code a Graphics method in java to draw String “Hello World” from coordinates(100,200) import java.applet.*; import java.awt.*; /* <applet code = "Demo.class", height=200 width=200> </applet> */ public class Demo extends Applet { public void paint(Graphics g) { g.drawString("Hello World",100,200); } 2. } 2. What is an applet? Applets are the java program that can be run on a java enabled web browser. An applet is typically embedded inside a web page and runs in the context of a browser. The Applet class provides the standard interface between the applet and the browser environment. 3. What is the difference between applications and applets? Applet Application 1. Applet do not use main method for initiating the execution of the program Applet use main method for initiating the execution of the program 2 They cannot run independently. They can run inside a web page using HTML Tag They can run independently 3 It cannot read and write files in the computer It can read and write files in the computer
  • 2. 4 It cannot communicate with other servers on the network It can communicate with other servers on the network 5 It is restricted to use libraries from other language c,c++ It is use libraries from other language c,c++ 6 In applet,AWT methods drawstring() which outputs a string to a specified X,Y location. Output is performed by System.out.println(); 4. What is a steam and which class allows your to read objects directly from stream? A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. The ObjectInputStream class supports the reading of objects from input streams. 5. Difference between init() and start() methods. Init() method is called when the applet is loaded by the Browser for execution.The Programmer can initialize variables, create objects, load imags etc. This method is called only once in the life cycle. The start() method is called by init() method ,when applet is brought back from minimize (seen in status bar) position. In minimize position, applet looses focus of the viewer. When the applet get focus, Browser calls first start() and then paint(). This method is called and executed multiple times whenever the applet gains focus 6. How to set foreground and background color of the applet? import java.applet.*; import java.awt.Color; import java.awt.Graphics; import java.awt.event.*; /* <applet code = "Demo.class", height=200 width=200> </applet> */ public class Demo extends Applet { public void paint(Graphics g) { setBackground(Color.YELLOW); setForeground(Color.RED); g.drawString("hello java",100,100); } }
  • 3. 7. What are the methods that control an applet’s on-screen appearance - The paint() method is called in situations the applet window being overwritten by another window or uncovered or the applet window being resized. - The update() is called when a portion of its window be redrawn. It is defined by the AWT. 8. Explain how to read information from the applet parameters. 9. What are the ways in which we can pass the parameter to an applet? We can supply parameter to an applet using <PARAM> tag. Each <PARAM> tag has a name attribute and value attribute. <applet> <param name=”color” value=”text”> </applet> The getParameter() method of the Applet class can be used to retrieve the parameters passed from the HTML pag Example1: import java.applet.*; import java.awt.*; /*<applet code="UseParam.class" width="300" height="300"> <param name="msg" value="hai"> </applet> */ public class UseParam extends Applet { public void paint(Graphics g) { String str=getParameter("msg"); g.drawString(str,50, 50); } }
  • 4. 10. What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. Whenever the applet needs to update the information displayed in it window ,it calls repaint(); 11. Present the structure of Applet. init() method - Can be called when an applet is first loaded start() method paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet’s page destroy() method - Can be called when the browser is finished with the applet. import java.awt.*; import java.applet.*; /* <applet code="DemoApplet" width=400 height=200> </applet> */ public class DemoApplet extends Applet { public void init() { //initialization } public void start() { //start or resume } public void stop() { //suspends execution } public void destroy() { //perform shut down activites } public void paint(Graphics g) { //display the content of window } }
  • 5. 12. What is a stream? Draw the hierarchy of stream class. A stream is continuous group of data or a channel through which data flows from one point to another point. Java implements streams within class hierarchies defined in the java.io package. 13. Distinguish between Input stream and reader classes & Output stream and writer classes. An Streams work at the byte level, they can read (InputStream) and write (OutputStream) bytes or list of bytes to a stream. Reader/Writers add the concept of character on top of a stream. Since a character can only be translated to bytes by using an Encoding, readers and writers have an encoding component (that may be set automatically since Java has a default encoding property). The characters read (Reader) or written (Writer) are automatically converted to bytes by the encoding and sent to the stream. 14. Explain how to implement an applet into a web page using applet tag To view an applet in the browser, following steps need to be followed: Compile the applet you have written … the .java file so as to get the .class file. Then, include the following code in your .html file: <APPLET CODE="XZY.class" WIDTH=100 HEIGHT=100> </APPLET> And then open the file using a java enabled browser. Simple example of Applet by html file import java.applet.Applet; import java.awt.Graphics; public class Demo1 extends Applet { public void paint(Graphics g) { g.drawString("welcome",150,150); } } myapplet.html <html> <body>
  • 6. <applet code="First.class" width="300" height="300"> </applet> </body> </html> 15. What are the attributes of APPLET tag? - height : Defines height of applet - width: Defines width of applet - align: Defines the text alignment around the applet - alt: An alternate text to be displayed if the browser support applets but cannot run this applet - archive: A URL to the applet when it is stored in a Java Archive or ZIP file - code: A URL that points to the class of the applet - codebase: Indicates the base URL of the applet if the code attribute is relative - hspace: Defines the horizontal spacing around the applet - vspace: Defines the vertical spacing around the applet - name: Defines a name for an applet - object: Defines the resource name that contains a serialized representation of the applet - title: Display information in tool tip 16. How can we determine the height and width of the applet? When applet is running inside a web browser the size of an applet is set by the height and width attributes and cannot be changed by the applet. The 'getSize()' method is retrieved the size of an applet. 17. What is meant by getCodeBase and getDocumentBase method? In Applet, The getCodebase() method is also commonly used to establish a path to other files or folders that are in the same location as the class being run. The getDocumentBase() method is used to return the URL of the directory in which the document is resides. 18. What are the different ways of running an applet? There are two standard ways in which you can run an applet : 1. Executing the applet within a Java-compatible web browser. <applet code="HelloWorld" width=200 height=60> </applet> 2. Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet. appletviewer RunHelloWorld.html 19. Why the applet classes are declared as public?
  • 7. A java applet is a small program that can be placed within a web page, like a small game or a calculator. -> When ever we declare the class as public, it means it is possible to access this class inside the same package and outside of the current package. -> The server needs to access some of the applet's attributes, so it is declared as public. If the applet was private, nobody would be able to access it. -> Also because classes from other packages such as sun.applet.AppletPanel cannot access it. 20. State the usage of System.console.println(). The Java Console class is be used to get input from console. It provides methods to read texts and passwords. If you read password using Console class, it will not be displayed to the user. . System.console() provides methods for reading password without echoing characters import java.io.Console; class ReadStringTest{ public static void main(String args[]){ Console c=System.console(); System.out.println("Enter your name: "); String n=c.readLine(); System.out.println("Welcome "+n); } } D:ann-runit3>java ReadStringTest Enter your name: Raj Welcome Raj 21. How will you pass parameters to applet Parameter in Applet We can supply parameter to an applet using <PARAM> tag.Each <PARAM> tag has a name attribute and value attribute. <applet> <param name=”color” value=”text”> </applet> Parameters are passed on an applet when it is loaded. We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a method named getParameter(). Syntax: Example1: import java.applet.*; import java.awt.*; /*<applet code="UseParam.class" width="300" height="300"> <param name="msg" value="hai"> </applet>
  • 8. */ public class UseParam extends Applet { public void paint(Graphics g) { String str=getParameter("msg"); g.drawString(str,50, 50); } } 22. What is Byte stream in Java? Byte streams process data byte by byte (8 bits). Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream. For example FileInputStream is used to read from source and FileOutputStream to write to the destination. Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files. 23. What is Character stream in java? In Java, characters are stored using Unicode conventions. Character stream is useful when we want to process text files. These text files can be processed character by character. A character size is typically 16 bits. Reader is used to read from source and Writer to write to the destination. 24. What is the use of native methods in Applets? Native methods and native libraries are bits of platform-specific executable code (written in languages such as C or C++) contained in libraries or DLLs. Applet cannot access the native methods
  • 9. PART-B: 1. Explain I/O streams with suitable examples Stream Java programs perform input/output through streams. A stream is an abstraction that either produces or consumes information as shown in Figure 3.1. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Streams are a clean way to deal with input/output without having every part of code understands the difference between a keyboard and a network. Java implements streams within class hierarchies defined in the java.io package. Figure 3.1 Streams usage Java 2 defines two types of streams based on data pass through streams: byte and character.Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. They use Unicode and, therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte streams. 3.2.1 The Byte Stream Classes • Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. • To use the stream classes, we must import java.io. • The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. • Two of the most important are read ( ) and write ( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes. Byte Stream Classes
  • 10. Stream Class Meaning BufferedInputStream Buffered input stream BufferedOutputStream Buffered output stream ByteArrayInputStream Input stream that reads from a byte array ByteArrayOutputStream Output stream that writes to a byte array DataInputStream An input stream that contains methods for reading the Java standard data types DataOutputStream An output stream that contains methods for writing the Java standard data types FileInputStream Input stream that reads from a file FileOutputStream Output stream that writes to a file FilterInputStream Implements InputStream FilterOutputStream Implements OutputStream InputStream Abstract class that describes stream input OutputStream Abstract class that describes stream output PipedInputStream Input pipe PipedOutputStream Output pipe PrintStream Output stream that contains print( ) and println( ) PushbackInputStream Input stream that supports one-byte “unget,” which returns a byte to the input stream RandomAccessFile Supports random access file I/O Example:
  • 11. import java.io.*; public class DataStreamExample { public static void main(String[] args) throws IOException { InputStream input = new FileInputStream("D:testout.txt"); DataInputStream inst = new DataInputStream(input); int count = input.available(); //returns available bytes count byte[] ary = new byte[count]; inst.read(ary); for (byte bt : ary) { char k = (char) bt; System.out.print(k+"-"); } } } Here, we are assuming that you have following data in "testout.txt" file: JAVA Output: J-A-V-A The Character Stream Classes • Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. • The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read ( ) and write ( ), which read and write characters of data, respectively. These methods are overridden by derived stream classes. Character Stream Class Stream Class Meaning BufferedReader Buffered input character stream BufferedWriter Buffered output character stream CharArrayReader Input stream that reads from a character array CharArrayWriter Output stream that writes to a character array FileReader Input stream that reads from a file FileWriter Output stream that writes to a file FilterReader Filtered reader FilterWriter Filtered writer
  • 12. InputStreamReader Input stream that translates bytes to characters LineNumberReader Input stream that counts lines OutputStreamWriter Output stream that translates characters to bytes PipedReader Input pipe PipedWriter Output pipe PrintWriter Output stream that contains print( ) and println( ) PushbackReader Input stream that allows characters to be returned to the input stream Reader Abstract class that describes character stream input StringReader Input stream that reads from a string StringWriter Output stream that writes to a string Writer Abstract class that describes character stream output Example: import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:testout.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } } Here, we are assuming that you have following data in "testout.txt" file: Welcome to java Output: Welcome to java 2. Explain the Reader Stream class hierarchy with an example program. 3. Explain the Writer Stream class hierarchy with an example program. The Character Stream Classes • Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. • The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read ( ) and write ( ), which read and write characters of data, respectively. These methods are overridden by derived stream classes.
  • 13. Character Stream Class Stream Class Meaning BufferedReader Buffered input character stream BufferedWriter Buffered output character stream CharArrayReader Input stream that reads from a character array CharArrayWriter Output stream that writes to a character array FileReader Input stream that reads from a file FileWriter Output stream that writes to a file FilterReader Filtered reader FilterWriter Filtered writer InputStreamReader Input stream that translates bytes to characters LineNumberReader Input stream that counts lines OutputStreamWriter Output stream that translates characters to bytes PipedReader Input pipe PipedWriter Output pipe PrintWriter Output stream that contains print( ) and println( ) PushbackReader Input stream that allows characters to be returned to the input stream Reader Abstract class that describes character stream input StringReader Input stream that reads from a string StringWriter Output stream that writes to a string Writer Abstract class that describes character stream output Example: import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exception{ FileReader fr=new FileReader("D:testout.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i);
  • 14. fr.close(); } } Here, we are assuming that you have following data in "testout.txt" file: Welcome to java Output: Welcome to java JAVA SYSTEM CLASS • All Java programs automatically import the java.lang package. • This package defines a class called System, which encapsulates several aspects of the run-time environment. • System contains three predefined stream variables, in, out, and errs. These fields are declared as public and static within System. This means that they can be used by any other part of your program and without reference to a specific System object. • System.out refers to the standard output stream. By default, this is the console. • System.in refers to standard input, which is the keyboard by default. • System.err refers to the standard error stream, which also is the console by default. • System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream. These are byte streams, even though they typically are used to read and write characters from and to the console. • READING CONSOLE INPUT In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Its most commonly used constructor is shown here: BufferedReader(Reader inputReader) Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); After this statement executes, br is a character-based stream that is linked to the console through System.in. 3.4.1 Reading Characters To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. import java.io.*; class BRRead { public static void main(String args[])throws IOException
  • 15. { char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } } Here is a sample run: Enter characters, 'q' to quit. 123abcq 1 2 3 a b c q Reading Strings To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here: String readLine( ) throws IOException Example: import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } } 4. Explain about reading and writing file in java.
  • 16. FileInputStream and FileOutputStream Reading a content from a file import java.io.*; class FDemoo { public static void main(String args[]) throws Exception { FileInputStream fr=new FileInputStream("4.txt"); int ch; while((ch=fr.read())!=-1) { System.out.print((char)ch); } } } Writing a content to a file import java.io.*; class FWDemoo { public static void main(String args[]) throws Exception { FileOutputStream fo=new FileOutputStream("5.txt"); String name="java programming"; byte[] b=name.getBytes(); fo.write(b); fo.close(); } }
  • 17. 5. Explain applet lifecycle? How applet are prepared and executed. Applets are the java program that can be run on a java enabled web browser. An applet is typically embedded inside a web page and runs in the context of a browser. The Applet class provides the standard interface between the applet and the browser environment. All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also import java.awt. Execution of an applet does not begin at main( ). Actually, few applets even have main( ) methods. Instead, execution of an applet is started and controlled with an entirely different mechanism. Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that contains the APPLET tag. This way, your code is documented with the necessary HTML statements needed by your applet, and you can test the compiled applet by starting the applet viewer with your Java source code file specified as the target. Here is an example of such a comment: /* <applet code="MyApplet" width=200 height=60> </applet> */ This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier, all of the applets shown in this notes will contain the appropriate APPLET tag embedded in a comment. Applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. AWT-based applets will also override the paint( ) method, which is defined by the AWT Component class. This method is called when the applet’s output must be redisplayed. import java.awt.*; import java.applet.*; /* <applet code="AppletSkel" width=300 height=100></applet> */ public class AppletSkel extends Applet { public void init() { // initialization } public void start() { // start or resume execution } public void stop() { // suspends execution } public void destroy() {
  • 18. // perform shutdown activities } public void paint(Graphics g) { // redisplay contents of window } } It is important to understand the order in which the various methods shown in the skeleton are called.When an applet begins, the AWT calls the following methods, in this sequence: 1. init( ) 2. start( ) 3. paint( ) When an applet is terminated, the following sequence of method calls takes place: 1. stop( ) 2. destroy( ) Let’s look more closely at these methods. 1. init(): This method is intended for whatever initialization is needed for an applet. 2. start(): This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages. 3. stop(): This method is automatically called whenever the user moves away from the page containing applets. This method can be used to stop an animation. 4. destroy(): This method is only called when the browser shuts down normally. 5. paint():The paint( ) method is called each time applet’s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. PART C
  • 19. 1. Write an applet program that sets the foreground and back ground colours and outputs a string. Setting background and foreground color import java.applet.*; import java.awt.Color; import java.awt.Graphics; import java.awt.event.*; /* <applet code = "BackgroundColorApplet.class", height=200 width=200> </applet> */ public class BackgroundColorApplet extends Applet { public void paint(Graphics g) { setBackground(Color.YELLOW); setForeground(Color.RED); g.drawString("hello java",100,100); } } 2. Write an example program that demonstrate passing parameters to Applets import java.awt.*;
  • 20. import java.applet.*; public class MyApplet extends Applet { String n; String a; public void init() { n = getParameter("name"); a = getParameter("age"); } public void paint(Graphics g) { g.drawString("Name is: " + n, 20, 20); g.drawString("Age is: " + a, 20, 40); } } /* <applet code="MyApplet" height="300" width="500"> <param name="name" value="Ramesh" /> <param name="age" value="25" /> </applet> */ 3. Write an java program to demonstrate applet skeleton APPLET SKELETON Most applets override these four methods. These four methods forms Applet lifecycle.
  • 21. • init() : init() is the first method to be called. This is where variable are initialized. This method is called only once during the runtime of applet. • start() : start() method is called after init(). This method is called to restart an applet after it has been stopped. • stop() : stop() method is called to suspend thread that does not need to run when applet is not visible. • destroy() : destroy() method is called when your applet needs to be removed completely from memory. import java.awt.*; import java.applet.*; /* <applet code="AppletSkel" width=300 height=100></applet> */ public class AppletSkel extends Applet { public void init() { // initialization } public void start() { // start or resume execution } public void stop() { // suspends execution } public void destroy() { // perform shutdown activities } public void paint(Graphics g) { // redisplay contents of window } } Example of an applet import java.awt.*; import java.applet.*; public class MyApplet extends Applet { String n; String a; public void init() { n = getParameter("name"); a = getParameter("age"); }
  • 22. public void paint(Graphics g) { g.drawString("Name is: " + n, 20, 20); g.drawString("Age is: " + a, 20, 40); } } /* <applet code="MyApplet" height="300" width="500"> <param name="name" value="Ramesh" /> <param name="age" value="25" /> </applet> */ 4. Write an applet program to fill colours in Shapes. import java.awt.*; import java.applet.*; public class GDemo extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.drawRect(20,20,45,78); g.fillRect(100,20,45,78); g.drawOval(20,100,45,78); g.fillOval(100,100,45,78); g.drawLine(200,50,10,10); } } /*<applet code="GDemo.class" width=700 height=400>
  • 23. </applet> */ 5. Write a program to display image using applets. import java.awt.*; import java.applet.*; public class DisImg extends Applet { Image pic; public void init() { pic=getImage(getDocumentBase(),"Penguins.jpg"); } public void paint(Graphics g) { g.drawImage(pic,30,30,this); } } /*<applet code="DisImg.class" height=300 width=700> </applet>*/