Welcome to Java Class: Learn Java One Bit at a Time

In summary, in this conversation, the speaker introduces the concept of Java and explains that to make use of Java programs, a compiler and a runtime environment are needed. The compiler converts human-readable source code into machine-readable object code, while the runtime environment executes the bytecode. The speaker recommends downloading the Java J2SE 1.4.2 SDK and explains how to compile and run a simple Java program using the command line. The terms "program," "object code," and "machine code" are discussed, as well as the purpose of a compiler and the limitations of a physical processor.
  • #106
prime factorizations

ek said:
So how do I make all 30 prime factorizations happen? I've been staring at this code for some time now and I can't figure it out.

Now, that is a nice problem..
So, you are given a number [tex]N[/tex] and you want to produce all tuples [tex](p_1, \ldots, p_k)[/tex] such that forall i the number p_i is prime and [tex]p_1 \ldots p_k = N[/tex]. Well, take all prime numbers [tex]p_1[/tex] such that [tex]N' = N / p_1[/tex] is an integer and complete the tuple with all solutions for [tex]N'[/tex]. The case when [tex]N[/tex] is prime is trivial.

You need one extra twist to ensure uniqueness.

Code:
factoring(min_prime, number)
  if number = 1 return {()} /* one empty factoring */
  sol = {} /* empty set */
  for i = min_prime to number, where i is prime and a divisor of number
    append to sol the result of prepending i to each factoring(i, number / i)
  return sol
 
Technology news on Phys.org
  • #107
Here's what I would do.

Look at this line of code:

for (number=432731; number > 432701; number--)

System.out.println("Prime factors of " + number + ":");

Try something like this:

for (number=432731; number > 432701; number--)
{
System.out.print("Prime factors of " + number + ":");
factor(number);
}

"factor" would print out the factors, and at the end, before returning, would print a '\n'. The reason that you're not printing out all the factors of all the numbers is that it's simply not included in that "for" loop.
 
  • #108
exception handling

Getting back to Java:

I don't really understand the "object-orientedness" of Java's code related to exceptions.

For example, if I have a
Code:
try {
//blah, blah. blah
System.out.println(s1);
//blah, blah. blah
}
catch([some kind of exception] e1) {
// "e1" handling code
}
catch(NullPointerException e2) {
// "e2" handling code
}
.
.
.
catch(Exception e6){
// "catch-all" handling code
}

// and so on...
that list of "catches" looks roughly -- very roughly-- like a C switch statement, but different...
So what is the difference? What exactly is the statement
catch(NullPointerException e2) doing that's different from a switch? Is NullPointerException e2 a constructor of some object?

In this example, e2 seems to be an identifier; is it a reference to a "NullPointerException" object? In the examples I've seen, it looks like each "catch" statement has a unique identifier. But what purpose does it serve? I haven't seen any code that makes use of it.
 
  • #109
java: null character

What do you use for a null char in java?

I'm using '\0' and it seems to work. Was I just lucky?
 
  • #110
gnome,

The exception handling mechanism in Java is almost (!) the same as a switch statement in C.

The principal ideas are:

1) all exceptions are subclasses of a single class, java.lang.Exception.

2) each catch statement acts more or less like a method declaration.

3) the first catch clause encountered with a matching type is run.

Let's imagine that we have a piece of code that looks through a phone book; if you give it a phone number, it will figure out the name of the person who owns it. This piece of code might throw two kinds of exceptions: a NumberFormatException, if the provided phone number is not a valid phone number, or a NoSuchPersonException, if the phone number was valid but not in the phone book. Let's say the method was defined somewhere in this fashion:

PHP:
String reverseLookup(String phoneNumber) throws NumberFormatException, NoSuchPersonException
{
...
}

If you made use of this piece of code in a GUI program, you would probably want to tell your user about each kind of error differently. If the user typed the phone number incorrectly, you might want to remind the user how phone numbers should be entered. If the phone book entry was not found, you'd want to tell the user the phone number was valid, but not assigned.

On the other hand, if you were writing some kind of a database utility that does automated processing of phone book data, you wouldn't necessarily want to deal with the two kinds of errors differently. You might just want to make a note in the log indicating a failure and move on.

Here's the code that you might use in the GUI app:

PHP:
try
{
	String name = reverseLookup(phoneNumber)
}
catch (NumberFormatException e1)
{
	System.out.println("Make sure phone numbers are entered as (xxx) xxx-xxxx.");
}
catch (NoSuchPersonException e2)
{
	System.out.println("Sorry, the owner of that phone number was not found.");
}

And here's the code you might use in the database application:

PHP:
try
{
	String name = reverseLookup(phoneNumber)
}
catch (Exception e)
{
	System.out.println("An error occurred on phone number " + phoneNumber + ": " + e);
}

The GUI example has separate catch clauses for both kinds of possible exceptions, since it handles them differently. When an exception is thrown, the first matching catch clause is run.

In the database example, there is only one catch clause, and it catches any kind of exception. (Remember, both NumberFormatException and NoSuchPersonException are both subclasses of Exception, so this single catch clause will catch either.)

The catch clause receives (in much the same way as a method) an argument, the exception object itself that was thrown. If the reverseLookup() method needs to throw an exception, it first creates the exception object, then throws it, as such:

PHP:
if (...)
{
  throw new NumberFormatException("This is not a valid phone number.");
}

That NumberFormatException is created with one argument, a human-readable message. It is then thrown, and automatically passed to the first catch clause that matches its type. That catch clause can examine the exception to see what action needs to be taken. In the case of the GUI example I provided above, neither exception is actually examined; the program prints a different error message solely based on the type of exception thrown. In the database example I provided above, the message of the exception, which is presumably meaningful to the operator, is simply printed to standard output. As you can guess, it's a good practice to provide some kind of human-readable message anytime you throw an exception.

- Warren
 
  • #111
The null char (the character with ASCII code 0, NUL) in Java is indeed '\0', just like it is in C. Of course, Java Strings don't have much in common with null-terminated C-style strings, so '\0' find much less purpose in Java.

- Warren
 
  • #112
Thanks very much, Warren. Now I see why that identifier is useful.

After reading your explanation, I tried some experiments and it all makes much more sense now. The 'e' in "catch(EmptyQueueException e)" is indeed an identifier (I know that because when I tried omitting it I got a compile error -- "<identifier> expected". And specifically, it is a reference to an EmptyQueueException (a class I defined, which of course extends the Exception class).

And when (following your example) you write
Code:
System.out.println("blah blah blah" + e);
you are invoking e.toString().
Which means that the built-in Exception class must implement its toString() method as the equivalent of
Code:
String toString() {return this.getClass().getName();}
Correct?

And when my Queue class throws an EmptyClassException, the combination of that "throw" and the catch(EmptyQueueException e) is equivalent to a command
Code:
EmptyQueueException e = new EmptyQueueException();
Correct?

------------------------------------------------------------------------

As to the '/0', I was playing around with a getLine() method, using a char variable "in"
Code:
in = (char)System.in.read();
and wanted to be sure "in" was initiated to null (in case there turned out to be nothing to read).


Anyway, thanks again for your help. I hate to just mimic code without understanding what it's actually doing.
 
  • #113
gnome said:
The 'e' in "catch(EmptyQueueException e)" is indeed an identifier (I know that because when I tried omitting it I got a compile error -- "<identifier> expected". And specifically, it is a reference to an EmptyQueueException (a class I defined, which of course extends the Exception class).
Yep, 'e' is just a name for thrown argument -- it becomes a variable local to the catch clause itself. You can name it anything you'd like -- unfortunately, two catch clauses cannot use the same name.
Which means that the built-in Exception class must implement its toString() method as the equivalent of... Correct?
Yes, except you might want to provide more information in the String you produce beyond just the name of the class. The Exception class includes a "message" field that contains a (human-readable) descriptive String so that you can customize the Exception.

For example, if a piece of code can throw the same kind of exception from multiple places, it's a good idea for each for each thrown exception to contain a descriptive string specific about each place.

And when my Queue class throws an EmptyClassException, the combination of that "throw" and the catch(EmptyQueueException e) is equivalent to a command... Correct?
Yes, you can think of the throw-catch system as a fancy "break" statement. When an exception is thrown, the try block or method containing the throw is immediately exited, and the nearest agreeable catch block is sought. When it is found, it is immediately run. If none is found, the exception will propagate all the way out to the interpreter itself, which will generally shut down your program.

- Warren
 
  • #114
Some additional information: Exceptions aren't the only things that can be thrown -- anything implementing the interface Throwable is fair game. There are two branches by default. One has the parent class Exception, and the other Error. In general, though, you won't bother with Errors.

(It is Error, right? It's been so long I forget... I've always just manipulated Throwables when I got that high level)
 
  • #115
Yes, Hurkyl, you got it right. The difference is that Errors are generally not intended to be catchable. When an Error is thrown, the program should terminate immediately.

- Warren
 
  • #116
It sounds like you are talking about two different descriptive strings:

For example, if a piece of code can throw the same kind of exception from multiple places, it's a good idea for each for each thrown exception to contain a descriptive string specific about each place.

Here I think I place that descriptive string as an argument to the "throw", as in
Code:
throw new EmptyQueueException("The queue is empty, stupid");
...(except, well, maybe a more informative string would be better) so the same exception gives a different message specific to the section of code that threw the exception.

------------------------------------------------------------

The Exception class includes a "message" field that contains a (human-readable) descriptive String so that you can customize the Exception.
Here, are you saying that if I define my own exception class I can give it an attribute:
(private?? public??) message "The queue is empty, stupid";
And then what? Would System.out.print(e); then print that message instead of or in addition to the name of the Exception?
 
  • #117
gnome said:
It sounds like you are talking about two different descriptive strings:
Nope, just one.

Let's look at some relevant bits of the Exception class's source:

PHP:
/*
 * @(#)Exception.java	1.30 03/01/23
 *
 * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

/**
 * The class <code>Exception</code> and its subclasses are a form of 
 * <code>Throwable</code> that indicates conditions that a reasonable 
 * application might want to catch.
 *
 * @author  Frank Yellin
 * @version 1.30, 01/23/03
 * @see     java.lang.Error
 * @since   JDK1.0
 */
public class Exception extends Throwable {
    static final long serialVersionUID = -3387516993124229948L;

    ...

    /**
     * Constructs a new exception with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for 
     *          later retrieval by the {@link #getMessage()} method.
     */
    public Exception(String message) {
	super(message);
    }

    ...
}

There's a constructor for the Exception class which accepts a message -- something intended to be human-readable, to describe what happened.

The Exception class is a subclass of Throwable. Let's look at the abbreviated Throwable source:

PHP:
/*
 * @(#)Throwable.java	1.51 03/01/23
 *
 * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;
import  java.io.*;

public class Throwable implements Serializable {
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -3042686055658047285L;

   ...

    /**
     * Specific details about the Throwable.  For example, for
     * <tt>FileNotFoundException</tt>, this contains the name of
     * the file that could not be found.
     *
     * @serial
     */
    private String detailMessage;
    
    ...

    /**
     * Constructs a new throwable with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * <p>The {@link #fillInStackTrace()} method is called to initialize
     * the stack trace data in the newly created throwable.
     *
     * @param   message   the detail message. The detail message is saved for 
     *          later retrieval by the {@link #getMessage()} method.
     */
    public Throwable(String message) {
        fillInStackTrace();
        detailMessage = message;
    }
    
    ...
    
    /**
     * Returns the detail message string of this throwable.
     *
     * @return  the detail message string of this <tt>Throwable</tt> instance
     *          (which may be <tt>null</tt>).
     */
    public String getMessage() {
        return detailMessage;
    }

    /**
     * Creates a localized description of this throwable.
     * Subclasses may override this method in order to produce a
     * locale-specific message.  For subclasses that do not override this
     * method, the default implementation returns the same result as
     * <code>getMessage()</code>.
     *
     * @return  The localized description of this throwable.
     * @since   JDK1.1
     */
    public String getLocalizedMessage() {
        return getMessage();
    }
    
    ...
    
    /**
     * Returns a short description of this throwable.
     * If this <code>Throwable</code> object was created with a non-null detail
     * message string, then the result is the concatenation of three strings: 
     * <ul>
     * <li>The name of the actual class of this object 
     * <li>": " (a colon and a space)
     * <li>The result of the {@link #getMessage} method for this object 
     * </ul>
     * If this <code>Throwable</code> object was created with a <tt>null</tt>
     * detail message string, then the name of the actual class of this object
     * is returned. 
     *
     * @return a string representation of this throwable.
     */
    public String toString() {
        String s = getClass().getName();
        String message = getLocalizedMessage();
        return (message != null) ? (s + ": " + message) : s;
    }
    
    ...
}

As you can see, it contains a field, called detailMessage, to store the human-readable explanation. When you create an Exception with such a message, it is passsed to the Throwable constructor, which stores it. When the Throwable's toString() method is called, it will include that message in its output, if one is available.
Here I think I place that descriptive string as an argument to the "throw", as in
It's not an argument to throw, it's an argument to the Exception's constructor. Remember, it says "throw new EmptyQueueException". You're creating a new EmptyQueueException object, with the specified message string, then throwing it.
Here, are you saying that if I define my own exception class I can give it an attribute:
(private?? public??) message "The queue is empty, stupid";
And then what? Would System.out.print(e); then print that message instead of or in addition to the name of the Exception?
You got it -- as the source of the Throwable class shows.

- Warren
 
  • #118
Got it. Thanks again.

It's a heckuva lot clearer after seeing those source-code snippets. The API on Sun's website shows how (very briefly), but not why.
 
Last edited:
  • #119
Help!

I would like to encrypt an object to a cypher in Java and then retrieve it some later time. However the encryption methods in Java take byte arrays as arguments. Is there any way in Java to convert an object to a byte array and later convert the byte array to an object? I know that serialization is done with streams, but I don't know with byte arrays.
Thanks!
 
  • #120
EUROPE1 said:
I would like to encrypt an object to a cypher in Java and then retrieve it some later time. However the encryption methods in Java take byte arrays as arguments. Is there any way in Java to convert an object to a byte array and later convert the byte array to an object? I know that serialization is done with streams, but I don't know with byte arrays.
Thanks!

The only way I would imagine to do it would be to define a custom method called toByteArray() and fromByteArray() (or a constructor) which converts your object to and from arrays of bytes.
 
  • #121
I think you can use classes ByteArrayInputStream and ByteArrayOutputStream, which write bytes to or from byte arrays with streams. Then you can utilize the writeObject() and readObject() methods of the stream classes.
 
  • #122
There are two classes, ByteArrayInputStream and ByteArrayOutputStream, that place stream interfaces around a byte[] array.

You can use standard Java serialization, writing to such a ByteArrayOutputStream.

- Warren
 
  • #123
Hello, everyoone, i am a linguist teacher studying math as my second degree,
i don't know computer much, i have a little problem writing a java program to draw graph simultanously to reading raw datafrom a file. graph illustrate data read in.
Can u help give me the code or show me how to code it ? I read only a few pages of java2 self study guides.

I hope what you helps me might help someone who searchs a lot these days but unable to find anything.
Thank you very much.
 
  • #124
boteet said:
Can u help give me the code or show me how to code it ? I read only a few pages of java2 self study guides.

Read some more. I doubt very much that you'll get people writing code for you.
 
  • #125
Sorry, although i read , i still can't have time to to finish it because I busy with teaching, my girlfriend needs it, i see she searched internet a lot. i just nneed hints you can tell so i can tell her then.
I need you just give a bit of help for me, please.
 
  • #126
I'm learning Java bymyself using The complete reference of java 2, fifth edition, Herbert Schildt..

I don't use sun's SDK, instead I'm using eclipse..

I was trying to make a small array thingy and here's the code

public class twod {
public static void main(String args[]) {
int twod [][] = new int [4][5];
int i, j, k = 0;

for (i=0; i < 4; i++)
for (j=0; j < 5; j++) {
twod[j]= k;
k++;

}
for (i=0; i < 4; i++){
for (j=0; j < 5; j++);

System.out.print( twod [j] + " "); System.out.println();

}

}


}



And here's the error...
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException:5
at arrays.twod.main(twod.java:29)

Which is in bold above...It seems to me that the code is correct, i still don't understand what's wrong with the print code..
 
  • #127
Nomy,

The line "for (j=0; j < 5; j++);", just above your System.out.println() call, is wrong. You should not have a semicolon there; instead, you should have an open brace. The semicolon indicates that the for loop is an empty loop, with nothing inside it.

The problem is that a for loop that increments j from 0 to less-than-5 will actually leave the value 5 in the j variable when it's done. The foor loops runs until the condition fails, and the variable j has to contain the value 5 for the condition to fail.

The System.out.println() call is being made -after- the for loop, since the loop is empty. At that point, j contains 5, and you're accessing the array outside its bounds.

- Warren
 
  • #128
Thanks a lot Chroot, now i understand...
 
  • #129
Your algorithm looks like what you did try to implement than it inadvertently turns out to be like that...:biggrin:

Chroot :wink:, I guess nomy wanted to print out the matrix with a semi-colon unfortunately appeared after the second for-loop as an apparent failure for the program to compile, and an exception is thrown right then to indicate the mistake.
 
  • #130
help!

hi, do u have any idea how i can cover the entire screen including the taskbar with an image as soon as a client starts, till a password is provided by the server? The client should not be able to see anything, not even the taskbar till the administrator provides the right password. This has to be done in java... and soon... can u help?
 

Similar threads

  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Programming and Computer Science
Replies
33
Views
8K
  • Quantum Physics
Replies
9
Views
1K
  • STEM Academic Advising
Replies
5
Views
1K
  • STEM Academic Advising
Replies
13
Views
2K
Back
Top