INNER CLASSES
1.
What is inner class and when we should go for inner classes?
Some times we can declare
a class inside another class such type of classes are called inner classes
Example
Class Car{
//more
code here
Class
Engine{
//more
code here
}
}
Without existing Car
object there is no chance of existing Engine object, hence Engine class has
declared inside Car class.
2.How
many types of inner classes are present?
There are four types of
inner classes are present
- Normal or regular inner class
- Method local inner class
- Anonymous inner class
- Static nested class
3.What is method local inner class?
- Sometimes we can declare a
class inside a method such type of classes are called method
local
inner classes
- The main purpose of method
local inner classes is to define method specific functionality
The
scope of method local inner classes is the scope of the method where it is
declared.
- This is the mostly rarely used
type of inner classes.
Example
class Test{
public
void m1(){
class Inner {
public void sum(int I,int j){
System.out.println(i+J);
}//sum
}//inner
Inner i=new Inner();
i.sum(10,20);
//more code here
I.sum(100,303);
//more code here
i.sum(102,84);
}//m1()
Public
static void main(){
New
Test().m1();
}
}
4.What
is anonymous inner class?
- Some times we can declare a
inner class without name such type of inner classes are
called
anonymous
inner classes
- Anonymous inner classes can be
divided into 3 categories
- Anonymous inner class that
extends a class
- Anonymous inner class that
implements an interface
- Anonymous inner class that
defines inside a method argument
ANONYMOUS
INNER CLASS THAT EXTENDS A CLASS
Example
Class
popcorn{
Public
void taste(){
System.out.println(“it
is salty”);
}
//more
code here
}
Class
Test{
Public
static void main(String[] args)
{
Popcorn
p=new Popcorn()
{
// here we are creating child class for popcorn
Public
void taste(){
System.out.println(“it
is sweet”);
}
};//here
semicolon indicates we r creating child class object with
parent
//
class reference here child class dosent contain name
p.taste()//
it is sweet
Popcorn
p=new Popcorn();
p1.taste()
//it is salty
}
}
ANONYMOUS
INNER CLASS THAT IMPLEMENTS AN INTERFACE
example
class
Test{
Public static void main(String[] args){
Runnable
r=new Runnable(){
Public
void run(){
for(int i=0;i<10;i++){
System.out.printin(“child
thread”);
}
}
};
Thread
t=new Thread(r);
t.start();
for(int
i=0;i<10;i++){
System.out.printin(“main
thread”);
}
}
}
Don’t
become fool that here we are creating object of interface Runnable.Here we are
actually
creating an object of class that is implemented Runnable interface.
ANONYMOUS
INNER CLASS THAT DEFINES INSIDE A METHOD ARGUMENT
Example
Class
Test{
Public static void main(String[] args){
New
Thread(new Runnable()
{
Public void run(){
for(int
i=0;i<10;i++){
System.out.printin(“child
thread”);
}
}
}).start();
for(int i=0;i<10;i++){
System.out.printin(“main
thread”);
}
}//main
}//Test
5.
With out having name of class how we can create an object and utilize the
functionality of Anonymous
inner class?
By using parent
class names
6.
What is difference between anonymous inner class and general class?
- A general class can extend only
one class at a time of course inner class can extend only one class at
a Time.
- A general class can implement
any no of interfaces at a time but a anonymous inner class can
- implement only one interface at
a time
- A general class can extend a
class and can implement an interface simultaneously but an
anonymous
inner class can extend a class or can implement an interface one at a time but
not
both
simualtaneously
7.
What is difference between normal inner class and static nested class?
Normal
Inner Class
|
Static
Nested Class
|
|
outer
class object , ie without existing outer class object inner class
object can exist
|
|
declare
static members
|
|
|
|
|
8.What is static nested calss?why the term nested instead of inner in static nested class?
Some times we can declare inner class with static modifier such type of
inner class are called static
nested classes.the term nested instead of static because without existing outer
class object inner
class object can exist.
Example
Class outer{
Static
class Nested{
Public
static void main(String[] args){
System.out.println(“nested
class main()”);
}
}
Public
static void main(String[] args){
System.out.println(“outer
class main()”);
}
}
- Java Outer
O/P
Outer
class main()
- Java Outer$Nested
O/P
Nested
class main()
9.
Inside inner class is it possible to declare main()?
No
it is not possible to declare main () inside inner class but in static nested
class it is possible for
Example refer above code
JAVA FAQ’s FROM JAVAFAQ SITE
Q:
ServerSocket or DatagramSocket? What is better to use in my applications?
Answer:
Both of them are good. It depends on task you do. DatagramSocket is designed for UDP and
ServerSocket for TCP. TCP is more
reliable in terms that it ensures delivery, UDP not.
But UDP packets are much smaller and
have no such big headers like TCP packets have.
If it is smaller then there is more
probability that it arrives faster. UDP used mostly in areas where you do no
mind about retransmission. You just do not need this, because information
become obsolete. Sound, for example. It is better to make small pause or repeat
last packet than to
play some piece that was send first but
received second. It is up to you to take
decision. If you do not mind that can lose small piece of data - use UDP.
Otherwise use TCP.
Q:
I read this statement: "The main thread must be the last thread to finish
execution. When the main thread stops, the program terminates." Is it
true?
Answer:
Absolutely wrong! The correct one: When
you start a program, JVM creates one thread to run your program. The JVM
creates one user thread for running a program.
This thread is called main thread.
The main method of the class is called from the main thread. If program
spawns new threads from the main thread it does stop until last thread id
died. Even if the main thread dies
program keep running.
Q:
What is asynchronous architecture?
Answer:
In asynchronous architecture a program does not wait for return immediately.
The program continues to do another staff and does not care when it will
happen. Simple example: modeless dialog.
You can do something else and return later to that dialog, change something and
press "Apply" button.
Synchronous example: modal dialog call, the procedure call it will
not continue until the model dialog
returns. For example, when you try to
delete files you will be asked: "Are you sure that you want to delete
file(s)?" You can not continue until you press
"Yes", "No" or
"Cancel".
Q:
Why C++ is not platform independent?
Answer:
C++ compiles to binary code (.obj, .exe, .dll, a.out etc.). Binary code
(Machine code, 0's and 1's) are machine dependent. Java compiles to byte code which is
independent of any machine. It need to
be interpreted to binary code by JVM, and executed by the machine.
Q:
I have heard that String concatenation operator "+" affects
performance of program if it used much. Is it true?
Answer:
Yes, it affects your program performance if you do a lot of "+"
operations with strings:
A new StringBuffer must be created,
then two arguments are added to it with append(), and the final result must be
converted back with a toString(). Your
time and space is wasted...
In case if you are appending more than
one String, try to use a StringBuffer directly.
Code
example: I want to show you one funny thing!
The code is shown below is simplest that you can imagine and does very unusual
thing!
It is slightly bigger than "Hello
World!" program but does much more. It lists all files in the current
directory if you run it like this:
java test * (of course after compilation) in
DOS/CMD prompt on Windows or in any shell in UNIX.
The program shows all files both in
Unix and Windows. If you do: java test. * On UNIX it also shows all hidden
files.
class
test{
public
static void main(String args[]){
for (int i = 0;i < args.length; i++) {
System.out.println("File " + i +
":" + args[i]);
}
if (args.length<=0) {
System.out.println("No files!");
}
}
}
You
can ask how can we get this list without any file handling functionality in the
code? Indeed looks mysterious...
But in reality everything is very simple.
When you type "*" (wildcard) OS (DOS, Windows, UNIX), not Java (!!!)
sends the list of files in the current directory to your program as a list of
parameters. And you see this list...
Q:
When can I use System.exit() in servlets?
Answer:
Never! Depends on server you run on...
Security exceptions on good server or
full shut down for simpler one
Q:
I was writing and testing some servlet program. Now I decided to remove it from
our web server. But it is still there causing confusion to another developers I
am working with. How can I unload my servlet explicitly?
Answer:
It depends on server you use. Often you can unregister your servlet somehow.
Easier way to make your servlet empty (remove all code), compile it and copy
class file to server. Many servers reload automatically a new class if they see
it was changed. You will still have your servlet on the server but it will do
nothing and nobody will complain...
Q:
By default an application has no security manager and Java runtime environment
does not create automatically a security manager for my program. How then
applet where I am not creating any security manager already prevented from many
operations?
Answer:
It is true - Java by default let you do whatever you want and then it is your
responsibility to restrict something. In case with applets a little bit
different story - applet viewers and browser have THEIR OWN security manager,
not from JRE. That's why even if you did not define any security manager in the
code of your applet, during the start up time browser/viewers will use their
own security manager. This manager is built in into their application (browser,
viewer), not your Java applet.
Q:
I the see method getClass() in java.lang.Object. Do we need it? I know all my
classes.
Answer:
Exactly. If you know - you do not need it. But if you do not know then it helps
you. For example if you get some object and would like to instantiate it:
Object createNewInstOf(Object obj) { return obj.getClass().newInstance(); }
Q:
I know that Java file should have the same name as public class in the
file.. But what are rules for files
that have no public classes?
Answer:
No rules are defined for such case! It is up to you how to
name it. Please check my example:
// ****** ABCDEFG.java file
*******************
class G {
public static void main(String[]
args) {
System.out.println("This
is class G!");
}
}
class Z {
public static void main(String[]
args) {
System.out.println("This
is another class Z!");
}
}
class AB {}
class CD {}
class EF {}
After compilation you will get AB, CD,
EF, G and Z classes. You can run G and Z
(they have main method), but not AB, CD, EF.
Try it: java G or
java Z
Q:
I am currently working on a program for generating a landscape from a
bitmap. I use lots of 4-Point-QuadArrays
next to each other and set the vertexes z-positions according to values from a
grayscale bitmap. It looks pretty OK but
is very memory intensive (at 150X150 QuadQrrays i get a memory exc.).
Answer:
You might want to try the utilities that I've written and are part of the
j3d.org code repository. Instead of a
QuadArray per pixel, I just generate one large array for the entire image.
You control the size of the quads by
the size of the image :)
It also sounds like you are doing some
automatic terrain generation, so you might want to have a look at the fractal
terrain generator that is also part of the package. Here's the pages:
and Javadoc
Q:
I am planning on making a MRU(Most Recently Used) list and allowing the user to
configure some primitive directory settings, like where to look for images,
other data, etc. I have a class fairly
well worked out in my brain to accomplish these goals. It's not rocket science. It does, however require that a file be
written to store the information, and the application needs to be able to
discern from whence the information should be read when started. In C++, I have stripped the directory from
which the application was run (from argv[0]) and saved my
"ApplicationSettings.cfg" file in that directory.
Any thoughts as to how to accomplish this?
Answer:
Check the API documentation for JDK1.4 beta:
===========================
public abstract class Preferences
extends Object
A node in a hierarchical collection of
preference data. This class allows applications to store and retrieve user and
system preference and configuration data. This data is stored persistently in
an implementation-dependent backing store.
Typical implementations include flat files, OS-specific
registries, directory servers and SQL
databases. The user of this class
needn't be concerned with details of the backing store.
============================
Note the bit about 'needn't be
concerned with details'. The ugly
problem of where to put such preference data has been abstracted away from the
developer, which makes life much easier.
The Preferences API is part of JDK 1.4, which is available in beta form
now, with a production release in the near future.
Q:
I am writing a Java Applet program which pop up a Window, However, there is a
Warning:Java Applet..." message appears at the bottom of the windows. Do you know how can I remove this, or Can I
rewrite the wording, for example, write company info instead of the
"Waring:Java Applet ....."?
Answer:
The rule for writing secure application is to use encapsulation. Always make variables PRIVATE. One of Sun's programmers, whose name I do not
mention here, did not follow that
idea.
He wrote the class Window like this:
public class Window extends Container{
String warningString;
......
private FocusManager focusMgr;
private static int nameCounter = 0;
.....
}
What you do is like this:
Write:
package java.awt;
public class SetWarning {
public static void setWarning(Window w){
w.warningString = "";
/*disable warning string*/
}
}
Compile this file and then put the
class SetWarning.class inside the subdirectory java\awt somewhere onto the
classpath, and you suddenly have gain access to the internal of the java.awt
package. Include whatever need be in
your final product.
Q:
Can I access a private variable of one Object from another Object?
Answer:
Yes, if this object of the same class. You can access private field from static
method of the class through an instance of the same class.
Check one example below:
public class Example {
private int privateVar;
Example(int a) {
privateVar = a;
System.out.println("private
privateVar = " + privateVar);
}
public static void main(String[] args) {
Example ex = new Example(5);
System.out.println(ex.privateVar);
}
}
Q:
I understand multi-threading as "parallel instances of execution" and
I have a query in this regard. The following is a code and its output. I would
like to how will you describe "what exactly is the join() method
doing?".
Answer: join() is a left over from UNIX days of doing
process synchronization (via the infamous fork/spawn mechanism). join() makes
the current thread (the one where you call T.join()) wait
until the thread that it is called on
(namely T) dies (or is interrupted).
This is useful in the case where, for example, your main thread had to
do additional work AFTER the other threads were finished doing theirs. join
guarantees that the only way that the call to join will return is if the target
thread is dead.
There's a good book on java
multithreading that you might want to read "Java Threads" by Scott
Oaks & Henry Wong.
Q:
I run some code in my program like this:
Runtime rt = Runtime.getRuntime();
rt.exec("C:/StartMyApp.bat");
I get very strange behavior: sometime
it starts from first time, sometime I need to call it a few times and
often it does not start at all after I
run it once..
Answer:
You need to modify your code since you execute your bat file in the MSDOS shell
(Win95/98) or command line shell"cmd.exe" (NT). You should use exec(String[] cmdarray) not
exec(String cmd) method...
Q:
I have a question between C and Java Language. In C, I want to call a Java
Library, as Java calls C library in Java.
In Java, I can call a C function and execute an application program by
using JNI Mechanism. But can I call a library
of Java Class in C ?
Answer:
Not easily. But you can execute a Java program from C. If you really need to call Java from C, write
a Java program that does what you want and "call" it.
Q:
Why Servlets are better than CGI scripts?
Answer: Generally, every new client's request
to CGI script starting a new process. With servlet web server starts just a new
thread that is much cheaper in terms of time for starting up, memory and CPU
consumption. JVM uses just one
process. This answer is right for "standard"
CGI. Now appear new modules for Perl that uses the same approach as servlet
does. Anyway, writing large programs on Java is much easier than on Perl,
atleast for me. Java has also very rich
API.
Q:
I can't find the API documentation on any classes in the sun.* packages. Where
is it?
Answer: The short answer is that SUN provides
documentation only for the public classes in java.*. SUN does not provide
documentation for sun.* because those are the Sun-specific
implementation,
and specifically not part of the Java technology API standard, and are
therefore subject to change without notice.
In
general, SUN doesn't provide javadoc documentation for sun.* classes in order
to discourage developers from writing programs that use them. For further
explanation, see the next question.
However, if you must have it, the documentation for sun.* is available
separately, here: http://java.sun.com/communitysource/index.html For example,
the doc comments for sun.net are in the source files located at: /src/share/sun/sun/net/*.java This source code release does not include
javadoc-generated documentation. You would have to generate those docs yourself
Q:
My friend claim that garbage collectors do not collect int value since they are
not created with new() method.. Is he
right?
Answer: Programmers know about the importance
of initialization, but often forget the importance of cleanup. After all, who
needs to clean up an int? But with libraries, simply "letting go" of
an object once you're done with it is not always safe. Of course, Java has the
garbage collector to reclaim the memory of objects that are no longer used. Now
consider a very unusual case. Suppose your
object allocates "special" memory without using new. The garbage collector knows only how to
release memory allocated with new, so it won't know how to release the bject's
"special" memory. To handle this case, Java provides a method called
finalize( ) that you can define for your class. Here's how it's supposed to
work. When the garbage collector is ready to release the storage used for your
object, it will first call finalize( ), and only on the next garbage-collection
pass will it reclaim the object's memory. So if you choose to use finalize( ),
it gives
you
the ability to perform some important cleanup at the time of garbage
collection.
Q: In my program where I use finalizers
to help GC to free the memory faster... But it seems that it is difficult to
know when it happens. I tried to find it and see that even on the same machine
my program runs differently...
Answer: You are right! Garbage collection
happens differently each time because it based not on definite schedule but
quite complicate alghorithms that take into consideration many factors
such
as CPU load, number of variables, memory size and so on. Even developers of JVMs just guess when some
process can start but not exactly. Since we have many JVMs, Java programmers,
therefore, should avoid writing code for which program correctness depends upon
the timely finalization of objects. For example, if a finalizer of an
unreferenced object releases a resource that is needed again later by the
program, the resource will not be made available until after the garbage
collector has run the object finalizer. If the program needs the resource
before the garbage collector has gotten around to finalizing the unreferenced
object, the program is out of luck.
Q: I do not understand the difference
between clone() and new(). Why shouldn't
I just call new()?
Can
apply new() to cloned object?
Answer: The difference is that clone() creates
the object that possibly has changed fields (after start up) and this object is
willing to be cloned by implementation Cloneable interface. New() method can be applied without objects "permission" and create a
new instance with fields just initialized and not changed. They will be changed later during runtime.
Clone() "mirroring" this modified object. That's why you NEVER should call new() on
cloned object. You can destroy the clone...
Q: We need to authenticate a user on the
local Linux system before he/she/it can log on to the application and begin
taking over the world. Since the Linux system uses shadow passwords, we must
have a method to retrieve the password and authenticate the user in the user
shadow database. Once authenticated, this user can work with the
application. How it can be done in Java?
Answer: It can be done, it is already
done! Here if you are interested in
interfacing C with Java in Linux (the JNI Solution): http://cscene.org/CS4/CS4-04.html
Advice: If you are C/C++ programmer be careful
with shortcut assignment operator "+=" in Java when you work with
Strings!
Why: The shortcut assignment operator +=
when used with Strings may confuse C and C++ programmers at first. Recall that
a += b is equivalent to a = a + b. Let's look at two code samples written in
C++ and the Java programming language:
//C++
code
string* s1 = new string("hello");
string* s2 = s1;
(*s1)
+= " world";
cout<<*s1<<endl<<*s2<<endl;
return 0;
//s1
= s2 = "hello world"
//Java programming language code
String
s1 = "hello";
String
s2 = s1;
s1
+= " world";
System.out.println(s1
+ "\n" + s2);
//s1
= "hello world" and s2 =
"hello"
In
the C++ example, the strings s1 and s2 print the same result because they both
point to the same address. In the Java programming language, Strings can't be
modified, so the + operator
must
create a new String when "world" is appended to s1.
Q: What is difference between:
String My = "Test";
and
String My = new String ("My"); ?
Answer: Because the compiler automatically
creates a new String object for every literal string it encounters, you can use
a literal string to initialize a String.
String
s = "Test";
The
above construct is equivalent to, but more efficient than, this one, which ends
up creating two Strings instead of one:
String
s = new String("Test");
The
compiler creates the first string when it encounters the literal string
"Test", and the second one when it encounters new String.
Q: Why the String does not have a
capacity method?
Answer:
The String class doesn't have a capacity method, because a string cannot
be changed.
Q: Why can not I compile this simple
example?
public
class Test{
int a;
final static int fin;
final int finint;
}
Answer: You can not compile it because you
have to initialize final variables. It must be done explicitly.
Q: Can someone point me to some resources
that explain how JSP and Servlets work together?
I
am trying to develop a small project (to learn JSP and Servlets) that is
similar to a banking transaction where I want to use JSP and Servlets.
I
would ideally like to do something like this.
1.
Get some input from the user in a HTML form.
2.
Send this data to the database.
3.
Get the reply from the database for user queries.
4.
Print the results to the user.
It
was suggested that I use JSP to display data and Servlets to interact with the
browser. But I was not able to find a concrete example. Any help regarding this
would be greatly appreciated.
Answer: Here is how this stuff works,
generally:
1)
The form (regular html) sends the request to a servlet that does all of the
processing and stores the results in standard javabeans (not ejb) in the
context that you want (either request
context
or session context).
The
things that the JSP is going to use need to be properties of the javabeans that
are accessible with the normal getters and setters (i.e. street needs to be
accessible by getStreet method
and
city needs to be accessible with getCity method). You can create as many of
these beans as you need to accomplish your purpose and store them in the
context that makes sense for your
app.
2) Get a request dispatcher from the
ServletRequest using getRequestDispatcher("/") and call its forward
method to transfer control to a JSP. If
you have been diligent in designing the beans, you will not need any java code
inside the JSP to write your page back to the browser. If the JSP has form stuff in it, you can send
that form data off to another servlet and start the cycle over again.
This
whole scheme has been enhanced for internationalization and other stuff with
the Struts framework (http://jakarta.apache.com). You will
be able to accomplish your modest
goals with the information above.
Q: Do I need to call Garbage Collector
gc() explicitly? If not why then does exist this method?
Answer: Do not afraid, if you do not call gc()
it will run anyway! You can be sure that GC-ing happens anyway... Why does SUN
provide us such method? I see two reasons at least for having it:
1.
Time critical applications. If you know that in some moment it is safe to run
GC call it. Probably it will run immediately. Not always. Anyway it can provide better distribution of
GC-ing in time increasing GC activity in "safe" time
2.
Test applications. It can help you to be sure that your objects will be
collected faster than usually.
Q: Does Garbage Collection hang my
program for a while?
Answer: Well, of course it somehow
"hungs" if you run your program on one CPU. Not in terms that it
hungs until some GC-ing is over. Usually
well written GC runs in own thread, alongside to your Java program and not more
time than any other thread. Your program
will not wait until some point is reached in GC but rather wait some amount of
time which the GC-ing thread allowed to take.
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 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.
Q: Main disadvantage of Java GUI is that
it is often slow. But I have seen also very fast working GUIs. Unfortunately
the code is hidden and I do not know the technique for writing of fast Java
GUIs.
Answer: I can describe one of main technique
you can use. It does not give you full solution, but will certainly speed up
your GUI. The main idea is to use
"lazy" initialization. Instead of creating and initializing of all
GUI components in constructors during start up time postpone it to later time
until you really need. Let say, you have a lot of tab panels with many elements
on each tab panel. Your constructors
should be "quite" empty and do not create and initialize those small
elements until your tab panel is chosen.
You should have very small constructor for tab panel itself and
additional lazy constructor for the rest. It should be called when user clicks
on that particular tab. This does not
decrease the full time of initialization, but spreads it up. The user will not
feel big delays during start up of your application. You should use these lazy
constructors just before you are going to call any paint method.
Q: Could you give me simplest example how
to do print in Java? I will work out it
myself :-)
Answer: Please compile and run it! It will
draw empty rectangle (you see I save your inks!)
import
java.awt.*;
public
class print {
public static void main(String args[])
{
Frame frm = new
Frame("JavaFAQ_test");
frm.pack();
PrintJob printJob =
frm.getToolkit().getPrintJob(frm,
"print", null);
if (printJob != null) {
Graphics grphcs =
printJob.getGraphics();
grphcs.drawRect(50, 50, 150, 100);
grphcs.dispose();
printJob.end();
}
System.exit(0);
}
}
Question: Please describe
shortly J2ME and what is different comparing to J2SE and J2EE?
Answer: It will not be shortly :-) ...
J2ME
is SUN's Java version for machines with limited amount of memory (RAM 128
KB)and low performance (comparing to
desktop versions such as PIII) processors.
The main difference from J2EE and J2SE is that it has a set of different
profiles.
J2ME
consist of three parts:
1. Java virtual machines* that fit inside
the range of consumer devices.
2. APIs that are specialized for each type
of device.
3. A profile, that is, a specification of
the minimum set of APIs useful for a particular kind of
consumer device (set-top, screenphone,
wireless, car, and digital assistant) and a
specification of the Java virtual
machine functions required to support those APIs. Each
profile is designed for specific
hardware type - mobile phone, PDA, microwave oven and so
on. Profile contains minimum libraries
that are enough to support the particular device. The
program is designed with profile for
mobile phone does not contain many classes that must
be used by oven oven, for example. Each
profile uses JVM that uses some subset of JVM
from J2SE and J2EE. Usually the program
that you write for J2SE or J2EE will not run on
J2ME JVM.
SUN
already released two profiles:
1.
The Foundation Profile is a set of Java
APIs which, together with the Connected Device
Configuration
(CDC), provides a J2ME application runtime environment targeted at
next-generation, consumer electronic and embedded devices.
2.
The Mobile Information Device Profile
(MIDP) is a set of Java[tm] APIs which, together with the Connected, Limited
Device Configuration (CLDC), provides a complete J2ME application runtime
environment targeted at mobile information devices, such as cellular phones and
two-way pagers.
To
be able to write a program with J2ME you must use profile's implementaion -
configuration. Profiles define only specification.
SUN
has two profiles now:
1.
Connected Device Configuration (CDC)
and C virtual machine CDC is a Java Community
Process effort that has standardized a portable,
full-featured Java[tm] 2 virtual machine
building block for
next-generation, consumer electronic and embedded devices. CDC runs on top of
the C Virtual Machine (CVM) that is provided as part of this release.
2.
Connected Limited Device Configuration
(CLDC) and K virtual machine. CLDC Java
Community
Process effort that has standardized a portable, minimum-footprint Java
building block for small,
resource-constrained devices. CLDC runs on top of Sun's K Virtual Machine (KVM)
that is provided as part of this
release.
Also
SUN provides developers with J2ME Wireless Toolkit The J2ME Wireless Toolkit is
a set of tools that provides developers with the emulation environment,
documentation and examples needed to develop CLDC/MIDP compliant applications.
Question: Can anybody tell
me what an API is...
Answer: It stands for "Application
Programming Interface" and is used to mean the collection of packages,
classes, and methods that expose a proprietary implementation to an external
user.
That's
a pretty good definition, but I would qualify it a little bit.
"Proprietary"
usually, in the vernacular, means "tied to a particular vendor's
tools".
A
lot of APIs are not tied to any particular vendor. One example is the C
standard library. In that library, there is a common definition and syntax for
a function to print to a file:
int
printf(const char *format, ...);
and
that function is considered to be part of the standard C API
and
not tied to anything proprietary.
As
well, any vendor can write a library and sell it, and it'll have its API, and
that will be considered "proprietary."
An
API can be either proprietary or non-proprietary.
Now,
this is a Java group, and the standard Java API could be considered to be a
proprietary Sun library. I'm aware that Sun considered and rejected the idea of
giving ownership to all things
Java
to the international standards committees.
But
for our intents and purposes, we can call the standard Java library
"non-proprietary", if only by virtue of the fact that we can get
implementations of it from IBM and other sources.
Some
might disagree with this, but that's okay, I don't feel strongly about it, and
I'm not a software contract lawyer, thank goodness.
Question: I am quite new to
JavaBeans and having some difficulty with making threads work with it. I wrote a thread class and I want to use it
in a visual builder (specifically VisualAge). I want to drop the class as a
bean on the composition screen and then connect its output to other beans
and
so on. Only problem is I don't know how
to start this thread
Answer: One way would be subclass the bean
into a runnable subclass that also inherits from Runnable, like so:
MyBean
<--extends-- RunnableMyBean ---implements--> Runnable
You
could then call the run() method in the RunnableMyBean class by invoking
RunnableMyBean.start().
Question: What are Thread
Groups useful for? I do not see big reason to have them in Java API...
Answer: From the beginning Thread Groups were
added for security reasons. Assumed, that not trusted code from third parties
will run in dedicated Thread Group. Of course it can not affect the
rest
of program. Those threads from external companies were not allowed to start,
stop and suspend your threads. Then this model is changed and we have no such
protection now. Now the Thread Groups
will let you a little bit easier manage your threads. You can manage many
threads simultaneously rather than each separately. For example you can set
maximum priority level, call suspend(), interrupt() on all threads in your
group. Also giving good names will help you to easily track and debug your
program.
Question: Could you give me
an example how to generate TCP/IP packets? I need to write my first network
program.
Answer: There is no need to write such
program. Java hides this implementation from you. Just use java.net.Socket or
java.net.ServerSocket class and use appropriate constructor. Easy and fast! If you want even faster, use the method
setTcpNoDelay(true) :-)
Question: What is
difference between Java Compiler and Java Interpreter?
Answer: Java compiler is a program that
translates Java language code (you write program x.java) into the bytecode
(x.class) for the Java Virtual Machine.
Another program that actually implements the Java Virtual Machine
specification and runs bytecode is an interpreter program...
Question: Well, you say
(see tip above) that compiler is a program that translates source code (x.java)
into bytecode (x.class). What is JIT
compiler? How can we have two compilers
and where the JIT compiler takes my source code (if I already compiled it)?
Answer: The name "JIT compiler" is
good enough to confuse people! Indeed,
what does it compile, if we have done the compilation after a program was
checked and compiled by javac, for example?
JIT is a part of the JVM and what it does is an optimization of java
bytecode to be able to run it much more efficiently on a current OS. Main
difference from javac compiler is that JIT does it on the fly and taking into
consideration much more things than javac.
Javac just compiles the code into bytecode and actual optimization
happens during a run time in JVM with help of JIT.
Question: I read it on
http://java.sun.com/docs/books/tutorial/java/javaOO/override.html: "Also, a subclass cannot override
methods that are declared static in the superclass. In other words, a subclass
cannot override a class method. A subclass can HIDE a static method in the
superclass by declaring a static method in the subclass with the same signature
as the static method in the superclass. "
My
question: It looks like play with words: override, hide.. Why is it written
HIDE? If I can write a static method in
subclass with the same signature it means that I override that method in
superclass, I really changed that method here in subclass. Am I wrong?
Answer: Let's start from the very beginning -
definition for overriding. It includes three main points that overridden method
must:
*
have the same name
*
have the same signature
*
have the same data type.
In
your case the static method in subclass can have another data type.
Example:
************
Alex.java *************
package
alex;
public
class Alex {
static String al(String name){
return name;
}
}
********************
EOF ***********
************
John.java *************
package
alex;
public
class John extends Alex {
static int al(int name){
return name;
}
}
********************
EOF ***********
It
compiles! You see that in Alex class the method "al" returns String
and in John class - int. It is hiding,
not overriding. Advice: try to avoid
such situation when you hide methods in super class. Use different names
instead and you will save a lot of time.
Question: Constructors are
similar to methods... I know that they do not return any value. Could I say
that they have void type (no return type)?
Answer: Not. Constructors are not methods and
they are different because they:
*
always have the same name as the class
name
*
have no return type, even void!
*
are not inherited and that's why (by the way) you can declare them final.
Question: I know that void
method does not return any value. But I still write the code like this:
void
nothing() {};
void
nothing2() {return;};
Why
can we still use "return" in the body of method?
Answer: To be able to exit method when it is
necessary. You can exit the method when
you reach the end of method and do not need to use "return". If due to some condition program must exit
the method then you use "return".
Question: Protected members
in Java and C++. What is difference?
Answer: C++ also has 3 levels of protection:
private, protected and public. They act
pretty much the same way. There are no packages in C++ and that’s why protected
members are accessible to subclasses only, not to whole package as in Java.
Question: I know that it is
possible to create threads by two different ways. What is essential difference?
What is better and when?
Answer: that's right! We can create a new
thread by subclassing Thread:
public
class MyBestThread extends Thread {...
Also
we can do it by using Runnable interface. The difference is that by
implementing Runnable we change just run() method keeping the possibility to
subclass something more useful...
The
difference between these two methods is really small and often makes no sense.
Q - The Java read() method reads and
returns a single byte from the standard input device. It
stores that byte according to what type. What does the method return if
the user enters an eof?
A - The Java read() method reads and
returns a single byte from the standard input device and stores that byte
in an integer. It returns an integer value
of -1 if the user enters an eof.
Q - What keystroke combination can be used
to simulate an eof at the keyboard of a DOS system?
A - An eof can be simulated on a DOS system
keyboard by holding down the ctrl key and pressing the z key.
Q - Provide a Java code fragment
illustrating how you would read a stream of bytes from the
standard input device until encountering an
eof and quit reading when the eof is encountered.
A - The following Java code fragment will
read a stream of bytes from the standard input device until
encountering an eof.
while(System.in.read() != -1) { //do something
}
This code fragment accesses the
read()method of the object referred to by the class variable named in of the
class named System.
Q - Provide a Java code fragment
illustrating two different ways to display a String argument on the
Java standard output device. Explain how
your code works in object-oriented terms. Make certain
that you explain the difference between the
two.
A - The following two code fragments will
each display a string argument on the Java standard output device.
System.out.println("String
argument")
System.out.print("String argument")
In the first case, the code fragment
accesses the println() method of the object referred to by the class variable
named out of the class named System. In the
second case, the print() method is accessed instead of the println() method.
The difference between the two is that the
println() method automatically inserts a newlineat the end of the
string argument whereas the print() method
leaves the display cursor at the end of the string argument.
===============
OOP
Q - In Object-Oriented Programming, an
object is often said to be an ____________ of a class.
A - An object is often said to be an instance of a class.
Q - In Object-Oriented Programming, an
object is often said to have s_______ and b_______.
Provide the missing words which begin with
the letters shown.
A - In OOP, an object is often said to have
state and behavior.
Q - An object's state is contained in its
________ and its behavior is implemented through its
________.
A - An object's state is contained in its
member variables ( or data members) and its behavior is implemented through its
methods ( or member functions).
Q - The member variables of an object can
be either ____________ or _________ .
A - Its member variables can be either
instance variables or class variables.
Q - What is generally meant by the
terminology "sending a message to an object?"
A - We activate the behavior of an object
by invoking one of its methods (sending it a message).
Q - What are the two things that can
usually happen when an object receives a message?
A - When an object receives a message, it
usually either performs an action, or modifies its state, or both.
Q - What happens to the memory occupied by
an object in Java when the object is no longer
needed, and what do we normally do to make
that happen?
A - When an object is no longer needed in
Java, we simply forget it. Eventually, the garbage collector may (or may not)
come by and pick it up for recycling.
Q - Identify as the stages of an object's
life?
A - The stages of an Object's life are:
Creation
Use
Cleanup
Q -
The creation of an object involves three steps (which are often
combined). What are the three steps?
A - The three steps are:
declaration (providing a name for the object)
instantiation (setting aside memory for the object)
optional initialization (providing initial values for the object's
instance variables)
Q - Java allows the instantiation of
variables of primitive types in dynamic memory: True or False?
If false, explain why and what you might be
able to do to achieve almost the same result.
A - False. Java does not allow the
instantiation of primitive variables in dynamic memory. (However, there are
wrapper classes for primitive types which can be used to turn them into objects
for this purpose.)
Q - An array of objects in Java is
instantiated as an array of reference variables where each
reference variable can then be used to
instantiate an object pointed to by the reference variable:
True or False. If false, explain why and
either provide a code fragment that illustrates your answer
A - True.
Q - In Java, it is always necessary to
declare (give a name to) all new objects: True or False? If
false, explain why and either provide a
code fragment that illustrates your answer
A - It is not always necessary in Java to
declare an object (to give it a name). Consider, for example a case where a
new object is instantiated to be used in an
expression and there is no requirement to be able to access that object outside
of the expression.
Q - Instance variables and instance methods
can be accessed using an object as the access
mechanism. What is the difference in the
syntax used to access an instance variable and an
instance method.
A - None. There is essentially no
difference in the syntax used to access a variable or a method.
Q - Once you have instantiated an object,
it is always possible to access all of the instance
variables and instance methods of that
object by joining the name of the object to the name of the
variable or method using a period: True or
False? If false, explain why.
No comments:
Post a Comment