Discussion Locked

Java Forum (Continued)

0 helpful
14 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Welcome to the Java Forum. This is the place to post your Java questions, share your best techniques, and express your opinion on topics that impact IT development. We also encourage you to post your comments about the Java TechMail.

If you haven't subscribed to the Java TechMail, visit our e-newsletter subscription center to subscribe to this free e-newsletter:
http://nl.com.com/acct_mgmt.jsp?brand=builder

Also, don't miss the discussion from the previous Java Forum. Use the link below to catch up on earlier member comments.
http://builder.com.com/5208-6230-0.html?forumID=18&threadID=121210

Note: When pasting links into your browser, remember to remove any extra spaces that appear.

14 replies

by navneet.java

// Navneet Shrivastava,31/10/2003

?h Case
?h Common way...
?h Need for Dynamic Compilation
?h Pros & Cons

Case:
client sends a request with amount as a parameter.Depending on the type of client.. we have diferent logic to process the request.

Common way...
Approach 1:
1) we havw one source file (source.java) ...this file has our logic
2) we compile this file using java compiler...will have 'source.class' file
3 )we run the java prog. and have our task done

client sends a request with amount as a parameter.Depending on the type of client.. we have diferent logic to process the request.....but wht if you have got huge codes(logical part) to be embedded within...it increases maintenance
...so we opt for modular approach

lets say we have
1)source.java...invokes methods from 'client_logic1.java' and 'client_logic2.java'...depending on type of client.
2)client_logic1.java...having logic for processing request from client of type1
3)client_logic2.java...having logic for processing request from client of type2

Improved Approach...
Approach 2:
1) we have source.java ...this file is creating objects from class defined in 'client_logic1.java' and 'client_logic2.java'
2) we compile these files using java compiler...will have 'source.class' , 'client_logic1.class' and 'client_logic2.class' .
3 )we run 'source' , this at runtime determines the type of client , on basis of type of client it invokes method from corresponding file...... and have our task done

but what if processing logics are very unstable and needs to be updated frequently.....we need to update 'client_logic1.java' and 'client_logic2.java'...and recompile them .....automating these task will facilitate the admin to be concerned about updating logic.....everything else(recompiling the updated files will be taken care by application itself)....

Advanced Approach...
Approach 3:
1) we have source.java ...this file is determines the type of client.....
2) checks for any updation in logic file for corresponding client...
3) recompiles the logic files if any updation is detected in corresponding file....
4) invokes the method required..and get the task done

//////////////////sample code/////////////////////////////////////////////////////////////////
/* this sample code works in the following manner
it reads the property file gets the key values.....
determines if .java file needs to be recompiled...
recompiles the .java file at runtime if required....
invokes the eerquired method ...and get or task done */
//----------------------------------------------------------------------------------------------------------------------------------
/* Class PhilePhilter */
import java.util.*;
import java.io.*;
import java.lang.*;
import java.lang.reflect.*;

public class PhilePhilter {
public static void main(String args[]) {

Properties prop1=new Properties();

/* =========== Using Property file============== */
//property file must be in your working dir.
String file_property = "test.properties";
FileInputStream fStream1 = null;

try{
fStream1 = new FileInputStream(file_property);
prop1.load(fStream1);

}catch(Exception e){
System.out.println("Error in creating object for FileInputStream ");
}

String key1 = "fJava_Path";
String key2 = "fClass_Path";
String key3 = "fDir_Path";

/* ==get file paths from property file== */
String fJavaPath = prop1.getProperty(key1);
String fClassPath = prop1.getProperty(key2);
String fDirPath = prop1.getProperty(key3);

System.out.println("\npath of .java file = " + fJavaPath);
System.out.println("path of .class file = " + fClassPath );
System.out.println("fDirPath = " + fDirPath +"\n");

/* ======calculating last modified time of .java file=====*/
File fJava = new File(fJavaPath);
if(fJava.exists()) {
System.out.println("Java file exists");
System.out.println("Java file was last modified at : " + fJava.lastModified()+"\n");
}
else{System.out.println("Java file does not exists");}

/* =====calculating last modified time of .class file=====*/
File fClass = new File(fClassPath);
if(fClass.exists()) {
System.out.println("Class file exists");
System.out.println("Class file was last modified at : " + fClass.lastModified()+"\n");
}
else{
System.out.println("Class file does not exists");
}

try {
Runtime r = Runtime.getRuntime();

/* =====checking for modification in b.java file after last compilation===== */
if(fJava.lastModified() > fClass.lastModified())
{
/* ====compiling file b.java==== */
Process p1 = r.exec(new String[] {"javac",fJavaPath});
while (p1.waitFor() != 0) { }
System.out.println("b.java has been modified after last compilation....thus is recompiled\n ");
}
else
{
System.out.println("b.java has not been modified after last compilation....thus is NOT recompiled\n");
}

/* ===== invoking method 'print' from 'b' ===== */
Method m = Class.forName("b").getDeclaredMethod("print", new Class[]{});
m.invoke(null, null);

} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}

//----------------------------------------------------------------------------------------------------------------------------------
/* Class b */
public class b {
public static void print() {
System.out.println("Hi it's 'b'again");
}
}
//----------------------------------------------------------------------------------------------------------------------------------

rem ***test.properties***

rem path for java file to be compiled
fJava_Path=C:\\Eclipse\\eclipse\\workspace\\J2EE_Basics\\Dynamic_Compilation\\b.java

rem path for class file
fClass_Path=C:\\Eclipse\\eclipse\\workspace\\J2EE_Basics\\Dynamic_Compilation\\b.class

rem path of directory containing files
fDir_Path=C:\\Eclipse\\eclipse\\workspace\\J2EE_Basics\\Dynamic_Compilation

//----------------------------------------------------------------------------------------------------------------------------------

//////////////////sample code/////////////////////////////////////////////////////////////////

Pros & Cons:

Pros
?h to be modular,
?h to be efficient, and
?h to be easy to use(maintenance)

Cons

?h This method tends user to sacrifice platform independence. By this we lose the portability, but achieve the result.
?h In this way we satisfy the programming needs by executing external utilities and applications from within a Java program. In Java, this means employing the Runtime class exec() method. Runtime.exec() allows you to execute a program; but it does not allow us to directly control the environment (we can't set the classpath for further processing).
?h " In an environment where Java applications must coexist with other non-Java applications this will often be a valid trade-off."
In its simplest form, exec() is quite easy to use:
/* ==============L/Unix envoirnment specific command============== */
Process p = Runtime.getRuntime().exec("/bin/ls");
this won't run on other OS
?h Also the problem with this form is that it gets you nowhere. When Java spans a new process it redirects STDIN, STDOUT and STDERR. Therefore the results of "/bin/ls" do not go to the screen.
?h Also we need to supply a complete path to whatever it is that you are executing.
?h Also .class files being used by system must be kept in same folder....we can't access file from aremote location(except kept in CLASSPATH).

by webmonkeybuilder

I'm interested in learning programming in general, and Java in particular. I am unable to take a formal course on the subject, and would like to know what resources Java Forum members recommend, such as online tutorials, books, and so on. Would Java Forum members please take a moment to clue me in to how to learn the basics of programming and Java?

Many thanks in advance!

by marcvina

Java built in function to the System Load. That is to see the number of processes are in processor and the % of memory usage etc.

by maryweilage

Builder.com member Lyn Greenhill e-mailed us this comment about the 10/16 Java e-newsletter, "Explore static nested classes and inner classes":

The most common use of inner classes is as event handlers for GUI-based
applications. These classes are usually declared anonymously and as
needed for each component that requires an event handler. The advantage of
using an inner class for event handling is that you can avoid large If/else
statements to decide which component is being handled. Each component
gets its own event handler, so each event handler knows implicitly the
component for which it's working.

The snippet below creates an anonymous inner class to handle the events
created by an application's OK button.

Button btn = new Button("Ok");
btn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
okClicked();
}
}
);

If you are using inner classes for event handling, there is a better and much simpler way that I found a while ago on in a Sun forum. Basically, you implement the ActionListener class, then all events can be handled by a single method in your primary class. For instance, here is the definition of a class that sets user preferences:
public class Preferences extends JDialog implements ActionListener {

Now, when you define a control, such as the button above, you don't need to reference an inner class, just the parent class, as in:
Button btn = new Button("Ok");
btn.addActionListener(this);
btn.setActionCommand("accept");

Note that the control also defines an action command, in this case the String "accept". This is important, because the single method to process all events will check this string:

public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("accept")) {
// Process user preferences
.
.
.
dispose();
} else if (event.getActionCommand().equals("cancel")) {
dispose();
} else if (event.getActionCommand().equals("help")) {
.
.
.
dispose();
}
}

You can add numerous controls to your dialog box and process everything with the above method that is switching from the ActionCommand string. Better yet - you don't generate an inner class for each control, which clutters up the generated class files. Each of these inner classes is generating an object which must be managed by the application.

by webmonkeybuilder

Can anyone illuminate me as to how to get a JavaScript menu to unfold above/infront of a flash animation in a web page? I would greatly appreciate any assistance.

Thanks

by rochiron

how do you explain this if parameters are passed by value?

public class SwapTip {
public static void main(String []args) {
Personne p1 = new Personne("toto");
Personne p2 = new Personne("titi");
System.out.println("p1: " + p1);
System.out.println("p2: " + p2);

swap(p1, p2);

System.out.println("Swapped!");
System.out.println("p1: " + p1);
System.out.println("p2: " + p2);

}
public static void swap(Personne o1, Personne o2) {
String t = o1.getName();
o1.setName(o2.getName());
o2.setName(t);
}
}

public class Personne {
private String name = "";
public Personne(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return getName();
}
}

by craig.hilles

Using Petersheim's logic, I can also "prove" that C++ only passes by value:

#include

class Integer {
public:
Integer(int passInteger);
int getInteger();
private:
int theInteger;
};
Integer::Integer(int passInteger)
{
theInteger = passInteger;
}
int Integer::getInteger()
{
return(theInteger);
}

void swap(Integer *o1, Integer *o2);

void main () {
Integer a(4);
Integer b(100);

cout << "a: " << a.getInteger() << "\n";
cout << "b: " << b.getInteger() << "\n";

swap(&a, &b);

cout << "Swapped!\n";
cout << "a: " << a.getInteger() << "\n";
cout << "b: " << b.getInteger() << "\n";
}

void swap(Integer *o1, Integer *o2)
{
Integer *t;

t = o1;
o1 = o2;
o2 = t;
}

OK? We all agree that both C++ and Java only pass by value? Just as Java java passes a copy of the reference, C++ passes a COPY of the pointer. So it passes by value!

But, how do we distinguish between swap(a, b) and swap(&a, &b)? (swap (&a, &b) is what us old-timers call "passing by reference"), but now Petersheim has showed us that we are really passing by value.

What we need is a new name to distinguish between passing a reference or pointer to an object, and passing a copy of an object. So that people like Petersheim will understand. How about 2 names:
"Passing a copy of the object"
"Not passing a copy of the object"

Of course, Java always uses the "not passing a copy of an object" method...

by arctic-diesel

thanks for your feedback, craig.

in fact, i don't believe that c++ passes only by value. i do believe that in c++ you have the option of passing by reference or by value.

below is an example that contains 2 swap methods: swapByValue and swapByReference. swapByReference actually works as a swap method; swapByValue doesn't.

the point of the tip is that you can't write a swap method in java like swapByReference that actually swap the 2 references. if you can, then please provide an example.

dave

#include

class Integer {
int value;

public:
Integer(int val) : value(val) {}
int GetValue() { return this->value; }
void SetValue(int value) { this->value = value; }
};

void swapByValue(Integer i1, Integer i2) {
Integer temp = i1;

i1 = i2;
i2 = temp;
}

void swapByReference(Integer &i1, Integer &i2) {
Integer temp = i1;

i1 = i2;
i2 = temp;
}

void main() {
Integer i1 = Integer(4);
Integer i2 = Integer(5);

cout << "original values\n";
cout << "i1: " << i1.GetValue() << endl;
cout << "i2: " << i2.GetValue() << endl;

swapByValue(i1, i2);
cout << "after swap by value\n";
cout << "i1: " << i1.GetValue() << endl;
cout << "i2: " << i2.GetValue() << endl;

swapByReference(i1, i2);
cout << "after swap by reference\n";
cout << "i1: " << i1.GetValue() << endl;
cout << "i2: " << i2.GetValue() << endl;
}

by arctic-diesel

the method should have been named swapNames not swap. can you write a java method that swaps 2 object references using a method call? here's my best effort without using a 3rd object as a container:

public static void swap(Personne o1, Personne o2) {
Personne temp = o1;
o1 = o2;
o2 = temp;
}

since java passes a copy of the object reference this approach will not work. when the method returns o1 will contain the same reference value that it did before and so will o2. if java passed by reference, the above approach would work.

what your code demonstrates is that you can call an objects method using a reference to that object. my response to that is, "of course you can" i don't believe i said anything to the contrary. maybe there's a better way to say it. a friend of mine says it this way, "Java passes references by value." that makes sense to me and i hope it helps others.

by maryweilage

Note from the editor: The following comments are from member Stephen Kestle.

This article is very misleading - it completely muddies the water of this important issue. In an overly technical sense, it is true that Java only
passes by value, but so does every other language (that I know of). The important issue is whether that value is a reference or not. If I pass an
object (technically a value being the reference to an object), I want to know if modifying that object is going to modify the outside object. If I assign a new reference to my object, I know that it will not, but it is important to know whether the referenced passed is the original reference, or one that is the result of an object.clone() (an automatic action that is
not supported by java at this time).

The shameful thing about this article is that you say it's an important distinction for beginning programmers, but it clearly isn't. Pointers are
one of the most confusing things about c++, and you're introducing that low level detail that isn't required.

On the stack, primitives are stored and passed as an absolute value - objects are stored as references to the information. THIS is the important thing.

Please clear this up in the next newsletter.

by zooble

Here's you c++ code converted to Java

class Integer {
int value;

public Integer(int val){ value = val;}
int GetValue() { return value; }
void SetValue(int value) { this.value = value; }
}

void swapByValue(Integer i1, Integer i2) {
Integer temp = i1;

i1 = i2;
i2 = temp;
}

void swapByReference(Integer i1, Integer i2) {
int temp = i1.getValue;

i1.setValue(i2.getValue);
i2.setValue(temp);
}

//OK, so I couldn't be bothered changing this method
void main() {
Integer i1 = Integer(4);
Integer i2 = Integer(5);

cout << "original values\n";
cout << "i1: " << i1.GetValue() << endl;
cout << "i2: " << i2.GetValue() << endl;

swapByValue(i1, i2);
cout << "after swap by value\n";
cout << "i1: " << i1.GetValue() << endl;
cout << "i2: " << i2.GetValue() << endl;

swapByReference(i1, i2);
cout << "after swap by reference\n";
cout << "i1: " << i1.GetValue() << endl;
cout << "i2: " << i2.GetValue() << endl;
}

And yes, it's not as easy as c++, but then, it's easier to pick up. Of course the downside is that you've got to be able to rely on the documentation, but there's nothing to stop you doing this in c++ anyhow.

It's not as consise, but it's easier to learn, and thats just one of the costs/benefits of Java

Cheers

Stephen Kestle

by craigh15

I didn't mean that C++ REALLY always passes by value. I just translated Petersheim's example to C++ to "prove" that C++ always passes by value, just as he "proved" that Java always passes by value.

When you pass a pointer in C++, you pass a COPY of the pointer, just as in Java, when you pass an object reference, you pass a COPY of the reference. That's all I was showing.

Your example uses primitives. Java can't pass those by reference. C++ can pass them by reference or value.

For the "Java always passes by value. Period." people, the fact that you pass the reference by value means "Java always passes by value".

They are wrong, us normal people know that "passing a reference to an object" is the same as "passing by reference". YES WE CAN AGREE THE REFERENCE IS PASSED BY VALUE!

This discussion is closed to new replies.