Cannot clear java class from memory - java

I have a simple java class as shown below:
public class Add2Numbers
{
public static void main(String[] args)
{
int num1=2, num2=4, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
I compile the class and run in matlab using:
obj = Add2Numbers;
javaMethod('main', o,"");
and I get the output: Sum of these numbers: 6 which is, of course, correct.
Next I change the code in my text editor (e.g. set num1=4) compile, execute the clear statements below:
clear all
clear java
clear import
clear CLASSES
clear ALL
clear
then run again:
obj = Add2Numbers;
javaMethod('main', o,"");
But the calculation result remains the same as before. If I close and restart MATLAB the modified java class runs correctly. So how on earth do I clear a java class without having to close MATLAB and restart it?
set

Related

Using Java package from command line - cannot locate or load main

I'm looking for a way to run a cluster of classes under the same package from the command line, but despite successfully compiling, I keep getting "could not load main" errors. I've changed the path and classpath to what they need to be, as well as tried building a subfolder named for the package I'm using ("com.company"), but to no avail. I've tried the following on command line while in the package-named subfolder directory, as well as the folder above that:
>java com.company.myclassname
>java myclassname
>java com\company\myclassname
>java -cp . com.company.myclassname
All have left me with the same "Error: Could not find or load main class".
At this point I've been poring over StackOverflow questions and tutorials for 3 hours to avoid having a repeat question, but I'm desperate. I've got to turn this homework assignment in in two hours. It works just fine within my IDE, and even through my backup beta IDE, but not command line. Can anyone please shed some light on this for me?
Edit: Source code:
package com.company;
import static com.company.myclassname.quantInput;
import static com.company.myclassname.costInput;
public class GroceryList {//This is the parent class for the program.
private static int counter = 0;//Used to ensure that the number of items is limited to ten.
private static GroceryList[] List = new GroceryList[10];//Used to hold the first ten grocery items in the add method.
public GroceryList(){//Basic constructor
}
.... Plus a few methods.
Client code:
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class myclassname {
private static String[] nameInput = new String[10];//for holding names from each line, then gets sent to constructor by index
public static int[] quantInput = new int[10];//for holding quantity from each line, then gets sent to constructor by index
public static double[] costInput = new double[10];//for holding price from each line, then gets sent to constructor by index
public static GroceryItemOrder[] GIOList = new GroceryItemOrder[10];//for holding GroceryItemOrder objects, then gets sent to toString() for printing
public static double TotalCost = 0;//initializes total cost variable
public static DecimalFormat f = new DecimalFormat("#####0.00");//Ensures proper output format for doubles
private static int counter;//Used for indexing
private static String target;//File path
public static void main(String[] args) throws FileNotFoundException, NullPointerException {
target = args[0];//User-supplied file path is assigned to variable "target"
try {//protects against NullPointerException
input();//Sends file path to input method, which sends that data to all other relevant methods and classes
System.out.printf("%-20s", "Item");//These lines provide headers for output message
System.out.printf("%-10s", "Quantity");
System.out.printf("%-10s", "Price");
System.out.printf("%-12s", "Total Price");
System.out.println();
for (int i = 0; i < counter; i++) {//Ensures only correct objects are printed to user
System.out.println(GIOList[i].toString());//public object array sends data to the toString() method, which
//then prints formatted output string, limited by counter in order to ensure only proper data prints
}if (counter<10){//If the file contains under 11 items, this prints to the user
System.out.println("Total cost: $" + f.format(TotalCost));}
else{//if the file contains 11 or more lines, this statement makes clear that only the first 10 items
//will be included in the total cost.
System.out.println("Total cost of the first ten items in your file: $" + f.format(TotalCost));
}
} catch (NullPointerException e){//safeguard against printing null strings to user
}
}
Plus an input method
Please try this quick workaround.
create a folder hierarchy com\company or com/company (depending on you OS).
Put the myclassname.class file inside the com\company folder.
from top level folder (which is at same level as com folder), run
java com.company.myclassname
Regards,
Ravi

BigDecimal.valueOf caching mechanism

I heard that the BigDecimal.valueOf() method is better than calling new BigDecimal() because it caches common values. I wanted to know how the caching mechanism of valueOf works.
Looking at the JDK 1.8 sources, it looks like it's just a static array which is initialized as part of class initialization - it only caches the values 0 to 10 inclusive, but that's an implementation detail. For example, given dasblinkenlight's post, it looks like earlier versions only cached 0 and 1.
For more detail - and to make sure you're getting information about the JDK which you're actually running - look at the source of the JDK you're using for yourself - most IDEs will open the relevant source code automatically, if they detect the source archive has been included in your JDK installation. Of course, if you're using a different JRE at execution time, you'd need to validate that too.
It's easy to tell whether or not a value has been cached, based on reference equality. Here's a short but complete program which finds the first non-negative value which isn't cached:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
for (long x = 0; x < Long.MAX_VALUE; x++) {
if (BigDecimal.valueOf(x) != BigDecimal.valueOf(x)) {
System.out.println("Value for " + x + " wasn't cached");
break;
}
}
}
}
On my machine with Java 8, the output is:
Value for 11 wasn't cached
Of course, an implementation could always cache the most recently requested value, in which case the above code would run for a very long time and then finish with no output...
If I m not wrong it caches only zero,one, two and ten, Thats why we have only
public static final BigInteger ZERO = new BigInteger(new int[0], 0);
public static final BigInteger ONE = valueOf(1);
private static final BigInteger TWO = valueOf(2);
public static final BigInteger TEN = valueOf(10);
That also calls valueOf(x) method.

How do I call java code from a Matlab program

I would like to calling my own Java program from Matlab.
This is my java program:
public class TestArgu{
public static void main(String[] args){
System.out.println("Test passing arguments!");
}
public void addNumber(int aNumber){
ansNumber = aNumber+5;
chk = aNumber;
System.out.println("input number = " + chk + ".\n");
System.out.println("ans = " + ansNumber + ".\n");
}
public int ansChk(){
return ansNumber;
}
private int ansNumber;
private int chk;
}
I did step by step from this link
http://www.mathworks.nl/support/solutions/en/data/1-URS0E/?...1...
but it is not working with my program.
I'm running Matlab program from the Server computer.
So I cannot edit the classpath.txt.
How to fix this problem?
First, delete the main function from your class. Then add the line
package mypackage.release;
before your class definition. Then compile it using the command
javac -verbose -cp /home/javaclasses -d /home/javaclasses /home/javasource/TestArgu.java
In matlab type
javaaddpath('/home/javaclasses');
clear java;
import mypackage.release.*;
test=TestArgu;
test.addNumber(6);
test.ansChk();
Remember that everytime you make changes and compile the java class, you must call clear java in matlab before the changes are available. This also has the unfortunate side effect of clearing all the variables in your workspace so make sure you don't have anything important to save before calling it.

How to modify Java code while running in debug mode?

How can I enable this "Debugging in Runtime" Notch is talking about in this video in Eclipse?
As a test, I'd like to be able to edit the output of the following code and change it to "Hello Runtime Debugging" while it's running.
public class HelloWorld {
public static void main(String[] args) throws InterruptedException {
doIt();
}
private static void doIt() throws InterruptedException {
for (int i = 0; i < 1000; ++i) {
System.out.println("Hello World " + i);
Thread.currentThread().sleep(100);
}
}
}
EDIT: I modified the code, now I get the results I was looking for. Suraj Chandran's answer below explains it.
private static void doIt() throws InterruptedException {
for (int i = 0; i < 1000; ++i) {
print(i);
Thread.currentThread().sleep(100);
}
}
private static void print(int i) {
System.out.println("Hello Sir " + i);
}
Eclipse supports hot swapping code during debugging , out of the box.
While debugging, just change any code and save it, Eclipse will automatically transfer the modified code to the target VM.
Note that you can't make structural changes to the code, like adding new methods, changing method signature or adding new fields. But you can change the code within a method.
EDIT: Note that changing the code during deubgging will make that method re-execute form the beginning, resetting the local variables in that method.
You need to make sure that Project > Build Automatically is checked.
Otherwise it might not work.
After enable Project-> Build Automatically, hot swapping code in debug mode is ok to me
I may misunderstand the question, but if you run a program in Eclipse in debug mode (Run/Debug), you can edit the content of methods during the program runs (if JVM supports it). Regularly you can not change the imports, method signatures, class definitons, etc, just the content of the methods.

A simple Vector in Java that produces some tricky output

A very simple Vector in Java that produces the output that is somewhat difficult to follow. The code snippet is as show below.
package main;
import java.util.Vector;
final public class Main
{
public static void main(String[] args)
{
Vector<String> r = new Vector<String>();
r.addElement("O");
r.addElement("Y");
r.insertElementAt("A",0);
r.addElement("B");
r.addElement("F");
r.addElement("I");
r.addElement("X");
r.removeElement("F");
r.insertElementAt("G",3);
System.out.println(r);
}
}
The above simple Java code produces the output that is different than it actually appears to be. The actual output the above code produces is surprisingly, [A, O, Y, G, B, I, X]. Actually, it contains 9 elements. The output however, contains only 7 elements. How?
Did you notice that one of them was removeElement?
Actually you would have forget about the statement removeElement("F"). Since it is called it was removed and remaining elements alone shown. If you comment this line and try again, your expected result will come. Cheers up!!!

Categories