Java - Applets Interview questions

Applets

Q: What are restrictions for an applet? What are applets prevented from doing?
Answer: In general, applets loaded over the net are prevented from reading and
writing files on the client file system, and from making network connections
except to the originating host.
In addition, applets loaded over the net are prevented from starting other
programs on the client. Applets loaded over the net are also not allowed to
load libraries, or to define native method calls. If an applet could define
native method calls, that would give the applet direct access to the
underlying computer.
Q: Do I need special server software to use applets?
Answer: No. Java applets may be served by any HTTP server. On the server side they are
handled the same as any other file, such as a text, image, or sound file. All the special action
happens when the applet class files are interpreted on the client side by a Java technologyenabled
browser, such as HotJava browser or 1.x or Netscape 3.x/4.x.
source: http://java.sun.com/products/jdk/faq.html#A8
Q: I know that applets have limited possibility to do many things. It is about network
connections, file reading/writhing and more.
Can applet read all system properties and if not how many of them are restricted?
Answer: Applets can read quite many of system properties by using:
file:///C|/330_new/330_new/applets.htm (1 of 13) [2003-07-22 22:07:47]
Applets
String ss = System.getProperty(String key):
java.version
java.vendor
java.vendor.url
java.class.version
os.name
os.arch
os.version
file.separator
path.separator
line.separator
Applets are prevented from reading these system properties:
java.home
java.class.path
user.name
user.home
user.dir
source: http://java.sun.com/sfaq/
--
AP. (J.A.)
Q: I write my first applet and it become very huge! It is an applet but looks like huge Java
Application.
Could you point me what is most is important for having a small applet?
Answer:
1. Use compiler optimization: javac -O But check it the size anyway. Sometime it makes the
code bigger..
2. Use jar files instead of class files
3. Try to use inheritance as much as possible: than more code you can reuse than less new
lines you have to add.
4. Try to use standard APIs. Often they are better optimized in size than some private exotic
packages. Of course often they have better methods and so on but try to use efficiently what
we have already!
5. Use short names.
6. Do not initialize big arrays because. They will be initialized and put directly into bytecode.
You can do it later on the fly
Please if you know more methods to make an applet smaller mail us and we will add your
comments here!
--
AP. (J.A.)
file:///C|/330_new/330_new/applets.htm (2 of 13) [2003-07-22 22:07:47]
Applets
Q: Why do I get message like “wrong magic number” when I am trying to run applet? What
is a magic number?
Answer: The first thing a JVM does when it loads a class is check that the first four bytes are (in
hex) CA FE BA BE. This is the "magic number" and thats why you are getting that error, you
are trying to load a file that isnt a class and so the class loader in the JVM is throwing out that
exception.
Make sure you transfer the class files to site in binary mode, rather than text or ASCII mode.
An error from the browser saying "cannot start applet ... bad magic number" usually means that
one of the class files on the server is corrupted. '
Replace your class binary files on the web server; clean up the cache of your browser, and
reload your applet.
Q: I've got problems with the Socket class (network)
I've got problems with the Socket class. I use it inside an applet (I've
written a small chatbox). I have code like this:
Socket s = new Socket("192.168.0.4", 13780);
When the server I'm connecting to is on the same machine as the client, it works.
When the server is an other machine, both NS and IE give an error message like:
Security:Can't connect to 192.168.0.4 with origin ''
Does anyone know how I can fix this??
Answer: The standard security concept for an applet is the 'sandbox'. An applet can't talk
outside it's memory space, can't talk to any files at all, and cannot talk to
anything on the internet except the same machine that it's 'parent'
HTML page originated from. So your applet can never talk to 192.168.0.4
unless the HTML came from 192.168.0.4
Q: How do I view the error output from my Java applets in IE?
Answer: The file windows\Java\Javalog.txt contains info about the last Applet loaded in IE.
All the System.out messages and exception information is stored here when Java Logging
is enabled in IE. To enable Java Logging start IE and select View/Options/Advanced.
Select "Enable Java Logging" check box click OK. Restart IE.
In NT4 the file in C:\WINNT\Java
Q: Is there a way to reduce the amount of time that it takes to download an applet?
Answer: There is a way to reduce the amount of time an applet takes to download. What ever
classes the Java applet is refering, you cluster them in a JAR file with the help of JAR utility
that comes with the JDK version. Check out the help for the options of that utility and make a
file:///C|/330_new/330_new/applets.htm (3 of 13) [2003-07-22 22:07:47]
Applets
".jar" file out of the applets refered classes and images and other relevent data which you want
to load.
Use the archive option of the applet tag and assign the .jar file:


Q: I want to be able to print debugging text messages during the whole applet's lifetime. Is
there an easy way to do that???
I'm a beginner in java. Right now i am doing an applet and i want to
write messages to the browser window for debugging purposes i.e. to
follow how the applet executes. Like when i'm developing an C++
application i usually use lots of "couts" to check values and the
programs behavior. Is there an easy way to do things like that when
making a Java applet? For me it seems like everything happens in a
function called "paint(graphics g)" and that function is only called at
the beginning of the applet start. I want to be able to print text
messages during the whole applet's lifetime. Is there an easy way to do
that???
Answer: you'd be better off doing a
System.out.println("the value is " + whateverValue);
This will show up in the java console. to see it in ie5, do View->Java Console, and in
netscape4.7, do Communicator->Tools->Java Console and it will pop up the java console
window.
If you are doing it in appletviewer from dos, it will show up in the dos window you used to call
appletviewer.
Q: I am writing an applet that will use images. I would like to ship out the images using a jar
file that contains all the images that the applet is going to use. I have seen a piece of code that
does that in the past, but I don't remember where.
Answer: by David Risner The following is from:
http://developer.netscape.com/docs/technote/java/getresource/getresource.html
import java.applet.*;
import java.awt.*;
import java.io.*;
public class ResourceDemoApplet extends Applet {
Image m_image;
public void init() {
try {
file:///C|/330_new/330_new/applets.htm (4 of 13) [2003-07-22 22:07:47]
Applets
InputStream in = getClass().getResourceAsStream("my.gif");
if (in == null) {
System.err.println("Image not found.");
return;
}
byte[] buffer = new byte[in.available()];
in.read(buffer);
m_image = Toolkit.getDefaultToolkit().createImage(buffer);
} catch (java.io.IOException e) {
System.err.println("Unable to read image.");
e.printStackTrace();
}
}
public void paint(Graphics g) {
if (m_image == null)
return;
Dimension d = getSize();
g.drawImage(m_image, 0, 0, d.width, d.height, Color.white, this);
}
}
Q: I want to use more fonts in my applet... say for example Arial... which is not avilable in
the present jdk package...
How can i deal with it?
Answer: import java.awt.Toolkit;
....
Toolkit tools = new Toolkit();
String[] fontList = tools.getFontList();
Q: How can I slow down my applet?
I have a game applet that is running too fast on newer systems that have high-end video cards.
Its easy enough to slow down the game by having it sleep between thread cycles, but I need to
be able to
determine how fast a users machine is before I determine how long to sleep for.
I have been muddling through the documentation but cannot find any calls that will tell my
applet what the users configuration is as regards to CPU speed and other components they
may have on their system.
Answer: Simple create a new Date (), then perform a standard lengthy operation on the order
of something that takes about one second on your machine, like a long loop, then create
another new Date() and compare it to the first. If it takes 1/2 of the time compared to your
file:///C|/330_new/330_new/applets.htm (5 of 13) [2003-07-22 22:07:47]
Applets
machine, then the CPU is probably about 2 times faster. if it takes 3 times the duration
compared to your machine, the CPU is probably 1/3 as fast as yours.
Do this dynamically, and it might help with speed changes when there's lots of action
happening as well - unless this issue is already being dealt with using threads, that is.
--
by Max Polk

Q: In my applet I have a bunch of gif's in my JAR file. When I try to access a gif using:
Image img = getImage(getCodeBase(), "image.gif");
everything works fine under Microsoft Internet Explorer but it does not under Netscape and
appletviewer. Of course I do not have any gifs in my CodeBase directory on server.
Any idea why?????
Answer: Because this is not how you access resources in a Jar file. You need to use
getResourceAsStream if you want to access GIFs from Netscape. Look at:
http://developer.iplanet.com/docs/technote/java/getresource/getresource.html
for example code. This same code will work in Sun's Appletviewer.
--
David Risner
http://david.risner.org/
Q: How do I get JVM version in Internet Explorer?
When you open the Java Console through internet explorer, it prints the following useful line at
the top:
Microsoft (R) VM for Java, 5.0 Release 5.0.0.3318
file:///C|/330_new/330_new/applets.htm (6 of 13) [2003-07-22 22:07:47]
Applets
We would like to be able to obtain the above String (or atleast the 5.0.0.3318 part of it) through
a Java Applet / Javascript at runtime.
Does anyone know of any handy methods that allow access to this String ? I've looked in all the
System.properties, but it wasn't there. Is it stored in the user's registry anywhere ?
Answer: just for Microsoft't VM!
try :
class test{
public static void main(String[] args){
String build;
build=com.ms.util.SystemVersionManager.getVMVersion().getProperty ("BuildIncrement");
System.out.println("Using build "+build);
}
}
Real Gagnon from Quebec, Canada
* Looking for code code snippets ? Visit Real's How-to
* http://www.rgagnon.com/howto.html
Q: I wonder if there is a way to find out if a button in an applet has been clicked, no matter
which of the buttons in an applet it might be.
Of course I can write, with a particular button (if event.target==button1) but maybe there is a
syntax that looks more or less like this (it is an imaginary code just to show what I would like to
do)
(if.event.target.ComponentType==Button) etc.
I tried a lot of things with getClass but none of them worked
Answer: Have your applet implement the ActionListener interface, and have every button that's
instantiated add the applet as an ActionListener. Then, inside of your applet, have the following
method:
public void actionPerformed(ActionEvent event) {


// check to see if the source of the event was a button
if(event.getSource() instanceof Button) {
// do whatever it is you want to do with buttons...
}
}
Darryl L. Pierce Visit
file:///C|/330_new/330_new/applets.htm (7 of 13) [2003-07-22 22:07:47]
Applets
Q: Could you suggest how to draw one centimeter grid in applet, please? One cm on the
screen must be equal to real cm.
Answer: If you're not all that picky about it, you can always use java.awt.Toolkit's
getScreenResolution() to see how far between the lines should be in the grid....that's assuming
the applet security allows it.
But have it _exactly_ one cm, you can't do, since the user can always adjust the display with
the monitor controls (making the picture wider/taller/whatever), and no computer that I know of
can know those settings.
--
Fredrik Lännergren
Not only that, the OS (and thus Java) does not know if I am using a 21" or a 14" monitor and
thus can't know the actual physical size of a given number of pixels. By convention, on
Windows monitors are assumed to be either 96dpi or 120dpi (depending on the selection of
large or small fonts). Java usually assumes 72dpi. None of these values is likely to be
accurate.
--
Mark Thornton
Q: Does anyone know how to or where I can find information about determining if cookies
are disabled on a client browser making a request to a servlet or JSP (or any server side
request handler, for that matter)? Also, is there a way to determine whether or not a client's
browser has style sheets enabled?
Answer: To test if the client has cookies enabled, create a cookie, send it, and read it back. If
you can't read it back, then the client does not accept them. It's not a clean way of doing it, but
it's the only way (that I know if).
As for CSS, there is no way to know if they allow CSS. Different versions of the browsers
support varying levels of CSS. You can get the browser type from the request object and then
make decisions based on that.
Q: How can two applets communicate with each other? Have you some examples?
Answer: You will occasionally need to allow two or more applets on a Web page to
communicate with each other. Because the applets all run within the same Java context-that is,
they are all in the same virtual machine together-applets can invoke each other's methods. The
AppletContext class has methods for locating another applet by name, or retrieving all the
applets in the current runtime environment
-----------------------------------------------------------------
import java.applet.*;
import java.awt.*;
import java.util.*;
file:///C|/330_new/330_new/applets.htm (8 of 13) [2003-07-22 22:07:47]
Applets
// This applet demonstrates the use of the getApplets method to
// get an enumeration of the current applets.
public class ListApplets extends Applet {
public void init() {
// Get an enumeration all the applets in the runtime environment
Enumeration e = getAppletContext().getApplets();
// Create a scrolling list for the applet names
List appList = new List();
while (e.hasMoreElements()) {
// Get the next applet
Applet app = (Applet) e.nextElement();
// Store the name of the applet's class in the scrolling list
appList.addItem(app.getClass().getName());
}
add(appList);
}
}
I hope that did it!
by 11037803
Here are some useful links on applet to applet communication. I don't know if they will solve
your problem but these are a variety of good approaches for this type of issue.
http://www.javaworld.com/javaworld/javatips/jw-javatip101.html
http://www.twf.ro/calculatoare/TricksJavaProgramGurus/ch1.htm
http://www.galasoft-lb.ch/myjava/CommTest/backup00/
http://www.rgagnon.com/javadetails/java-0181.html
http://www.2nu.com/Doug/FAQs/InterframeIAC.html
by Mickey Segal
Q: I would like to ask if there 's anyway that I can use the same program run as an applet or
application?
Answer: You would have to provide at least a main() for the application part, and init(), start(),
stop(), destroy() for the applet part of your program. Your class could simply display the applet
within a Frame.
Example:
class Foo extends Frame {
public Foo(String title){
//...
Foo applet = new Foo();
applet.start();
add(applet, "Center");
//...
}
file:///C|/330_new/330_new/applets.htm (9 of 13) [2003-07-22 22:07:47]
Applets
main()is function of course, not constructor
--
Alex
Q: Is it possible to run a java applet in a dos window (win98 se)?
Answer: No. A dos window is a character device. You can use the applet viewer program that
comes with the JDK though.
--
Mike
Q: Is there a simple way to tell if a PC online or not from within an applet?
Answer: Not without either server-side support or signing the applet, since applets are not
allowed to connect to other hosts than the one they are downloaded from. Best approach, I
suppose, would be to ping the target from the server.
However, this is not quite full proof because of firewalling: my pc, for example, will not answer
to pings.
--
Michiel
Q: Is it possible to close browser from applet?
Answer: Yes, use this (tested):
//////////////////////////////////////////////////////
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import netscape.javascript.JSObject;
class CloseApplet extends Applet
implements ActionListener{
protected Button closeButton = null;
protected JSObject win = null;
public void init(){
this.win = JSObject.getWindow(this);
this.closeButton = new Button("Close Browser Window");
this.add(this.closeButton);
this.closeButton.addActionListener(this);
} // ends init(void)
public void actionPerformed(ActionEvent ae){
this.win.eval("self.close();");
}
file:///C|/330_new/330_new/applets.htm (10 of 13) [2003-07-22 22:07:47]
Applets
} // ends class CloseApplet
//////////////////////////////////////////////////////
and the HTML needs to have MAYSCRIPT enabled.
//////////////////////////////////////////////////////


Integre Technical Publishing



CODEBASE="java/" MAYSCRIPT>




//////////////////////////////////////////////////////
Here's the API:
javascript.html>
It's small enough that you could include it in your JAR if you'd like. But most users will even
have it on their systems.
It says "Netscape," but I know that IE understands it fine.
--
Greg Faron
Integre Technical Publishing
Q: Is it possible to run an Applet inside a JAVA application?
Answer: An applet is just another class that can be instantiated:
Applet myApplet = new MyApplet();
where MyApplet is the name of the applet class that you have written and then added to a
container of some kind
myFrame.add(myApplet);
..but you need explicitly call the init() method that a browser would normally call "behind the
scenes":
myApplet.init();
file:///C|/330_new/330_new/applets.htm (11 of 13) [2003-07-22 22:07:47]
Applets
--
artntek
Q: I want to bypass the security sandbox so that my Applet loaded from IE can read and
write files on the client side:
(1)configure the server as trust side, (2)install my own security manager to override those
checks.
Will that work? Do I still need to have my Applet signed?
Answer: AFAIK this will not work. "Core Java II" says on page 716:
Once the program installs a security manager, any attempt to install a second security manager
only succeeds if the first security manager agrees to be replaced. This is clearly essential;
otherwise, a bad applet could install its own security manager.
Sign the applet and make the Security calls that request the access you need. If the user
consents, your code will be allowed. If they don't, it'll fail.
Be aware that the Netscape security model is not that of the Java specification, and if you want
to run there, too, you'll have to find a way of dealing with the discrepancy. Netscape's
developer Web site includes the documentation for their model, as well as stub libraries you
can compile against.
For information on the Java security model (Sun sanctioned version), check out these Web
pages (chosen from the results of the Google search "Java Security Model"):
http://java.sun.com/security/
http://java.sun.com/security/SRM.html
http://www.sans.org/infosecFAQ/code/java_sec.htm
--
Randall Schulz, Michael Pellaton
Q: I just started to do Java programming. How can I bring the system standard output (what
you see on your telnet window) to display in an applet?
I want to do:
system(myprogram);
then I want the screen output to be in my applet.
Answer: There is no system() method in the standard API. This functionality in Java is provided
by the java.lang.Runtime class. Runtime allows you to capture standard output from an
external process you started.
file:///C|/330_new/330_new/applets.htm (12 of 13) [2003-07-22 22:07:47]
Applets
Q: How does one remove or replace the message "Java Applet Window" at the bottom of a
frame?
Do not confuse this with the status message at bottom of a browser.
Answer: This can be done.
Use the .java.policy file in the user|home directory with following contents:
grant {
permission java.awt.AWTPermission "showWindowWithoutWarningBanner";
};
--


No comments: