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

Click For Summary
The discussion focuses on learning Java programming step by step, emphasizing the need for a compiler and a runtime environment. The Java compiler converts source code into bytecode, which is executed by a Java Virtual Machine (JVM), allowing Java programs to run on any platform. Participants are guided through the installation of the Java J2SE 1.4.2 SDK and the process of compiling and running a simple Java program. Clarifications are provided on terminology, such as the difference between source code and object code, and the function of convenience files for compiling and running programs. The conversation also addresses troubleshooting issues related to running Java applets and classpath configurations.
  • #31
turin said:
I tried to invoke the make.bat file, but I got errors... I put the most recent code (the stuff that we're currently discussing) into the lesson2.java file.
A file called lesson2.java must contain a class called lesson2. If the class inside is called Test, the file must be called Test.java. The names must be consistent.
- The programmer (me) can arbitrarily use most combinations of letters (strings; is there a term for the smallest part of code that is still code?) as variables in the source code. The frame in the source code is one such example.
Yes, variable names and method names are arbitrary combinations of alphanumeric characters and some special characters like the underscore. They also cannot begin with a number, only a letter. People have various conventions for style, and prefer names written in the style of loopCounter to other possibilities like loop_counter and LOOPCOUNTER.

The compiler actually recognizes things like variable and method names based on their position in the code; for example, the keyword "class" is a reserved word in the Java language; you cannot use it for your own variable names. Whenever the compiler sees the word "class," it expects a properly-formatted class name (made up by the programmer) to follow it.
There are some combinations of letters that the compiler recognizes for a specific purpose. The JFrame in the source code is one such example.
Yes, there some special words that are used to define structures; these words are called reserved words. A non-exhaustive list includes new, class, public, private, protected, if, while, for, continue, break, do, and so on.

Other words like JFrame are not actually built into the compiler; they are classes written by other people. When you use the word JFrame to indicate the type of a variable (again, the compiler knows it's used as a variable type by its context in the code), the compiler goes out and looks for a class called JFrame.

Most of the combinations of letters in the source code that the compiler recognizes for a specific purpose require the programmer to alert the compiler's attention by declaring the import lines. If the import lines were not included, then the compiler would not recognize combinations of letters such as JFrame, and so such combinations of letters would also be arbitrary like frame.
That is correct; but please note the distinction between words the compiler recognizes internally (like class and for and if), versus words the compiler used to reference other code (like JFrame).
I suppose that learning the combinations of letters and the necessary imported classes that the compiler recognizes will just come with time/experience. Is there a book or (preferably) an online resource that lists these compiler recognized things?
The Java environment provides a wealth of classes that you can use to build your applications; JFrame is just one. The entire API (application program interface) can be viewed here:

http://java.sun.com/j2se/1.4.2/docs/api/

Look in the left-hand frame and view the entry for the JFrame class if you'd like. You might also want to check out some very useful and simple classes like Vector.
I don't see any kind of algorithmic "flow" in the source code; I don't know what else to call it. In Q-BASIC, FORTRAN, and Matlab, there is an algorithmic flow that I recognize.
There definitely still is flow control in Java; once execution enters the top of a method, for example, it runs through that method exactly as you're used to seeing it run in other languages. The flow control is complicated by object orientation, however; constructors are run whenever the "new" reserved word is used, for example. You'll get used to the flow control very quickly, don't worry. Once you know how it works, you'll think it's positively brilliant.
Test is a class, and JFrame is a class, but JFrame is inside Test (by inside, I mean that it follows the openning curly bracket after the class declaration but preceeds the next closing curly bracket). Is this like nesting?
I would not say that JFrame is inside Test. JFrame actually has it's own quite long source code file, called JFrame.java, buried deep in the JDK library. I would simply say that Test uses JFrame, by referencing it. This is how you build applications in Java; objects use other objects.
Is the line of the source code protected JFrame frame; like declaring a variable to be used named frame that is of the data type JFrame and that is protected from something?
Absolutely correct in every way. The variable is in fact protected from the outside world; only code within the Test class can modify it (I'm being a bit sloppy, but that's close enough). The reason people use protection is to enforce good programming habits. Think back to the ChessPiece class -- you wouldn't want any old code anywhere in the world to be able to just arbitrarily set the x and y coordinates to anything they want. Only certain x and y positions are allowed; (-1, 105) would not be a valid position. Instead of trying to make all the code in the entire world aware of those restrictions, you make the variables private, and write a move() method. The move method could verify that the given position is valid before updating the variables. This way, your ChessPiece class is protected from the blunders of other programmers -- or even your own blunders.
I still don't understand what you mean by a Test object being created. You say that the constructor is called automatically when the Test object is created, but then why do you have to type the constructor? Does typing public class Test { ... not constitute creating a Test object?
Typing "public class Test {" does not create an object. You've just written a class -- a blueprint for an object. To actually create an object of the Test class, you use the "new" keyword, like "new Test()". When the "new" keyword is actually executed -- when the program is run -- the memory is allocated and so on to actually create a Test object.

Consider that classes exist in source code, and objects exist in memory at run-time.

Is the syntax A.B().C(some stuff) generally useful, or is it very specific to the JFrame class? This syntax seems to imply an operation of some kind. What is the function of the .B() in this construct? B() and C() seem to resemble mathematical functions of variables. Is there some relationship/significance to this?
Right on target. The JFrame class has variables and methods (remember, that's all a class is -- a collection of variables and methods that operate upon them). Let's say you have two windows, though, not just one. Maybe one is called mainWindow, and the other is called toolPalette. If you want to make one of these windows visible, you have to specify which one to the compiler. You do so by writing one of the following two lines:

mainWindow.setVisible(true);
toolPalette.setVisible(true);

The . loosely translates into "member." When you write mainWindow.setVisible, you are referring to the setVisible member of the mainWindow object. Both mainWindow and toolPalette are of class JFrame.
In the main class, you say we're going to create a Test object, but I thought we had already created one at the beginning of the source code.
Nope, once again, the beginning of the source code defines the blueprint for an object -- a class. A class is a blueprint for an object. You still have to actually use the blueprint to make an object, and that mechanism is the "new" keyword. Think of the "new" keyword as a construction crew which uses a blueprint, which defines what a house is, to build a real house. You can write one blueprint, and the construction crew can go out and build lots of houses from the blueprint that all start identical. After their construction, however, they can be modified independently. One family can put a blue couch in their house, while another can choose a red one.

The JFrame class is a blueprint for a window; you can make lots of windows from that blueprint, and each one is independent. They can have different titles, different contents, and so on.

Let me know if anything is still confusing..

- Warren
 
Technology news on Phys.org
  • #32
chroot said:
turin,

I have indeed taught programming classes in the past; I'm glad you find my writing so helpful, even when it's not all that well-organized and somewhat rushed!

Perhaps, you should think about writing a book. I'd buy it.
 
  • #33
chroot,
I think I'm starting to get it. It is so hard in the beginning (I hope just in the beginning).

So, when one writes a *.java file, the purpose is to create a class? Then after writing 18 thousand (give or take) *.java files, one writes an "umbrella" or "master" (or "main"?) *.java file that takes advantage of the fact that most of the code work has been taken care of by the "sub" files by importing them and simply "calling" or "instantiating" (or "creating"?) them?

When you say that JFrame has its own file called JFrame.java, do you mean JFrame.class? It seems like the extension "java" indicates waiting to be complied (or source code) and the extension "class" indicates compiled code (or object code).

I'll probably try to play with lesson2 tonight (Fri night, I'm such a nerd).
 
  • #34
Yes, you've basically got it... you write a bunch of classes, stick each in its own .java file, and compile them. Then you have one top-level class, which contains a special method called "main," that is the entry point to your entire program. The main method would then go and create whatever objects are used in the program, and so on.

And there was once a JFrame.java file somewhere, that someone wrote. If your JDK distribution includes the java source files, then you actually have a copy of it. If your JDK distribution did not come with the source, then you only have the JFrame.class file, which was compiled from the JFrame.java source code. Keep in mind that Java uses .jar files, basically the same as .zip files, to store large numbers of classes in an efficient way. There is probably a "rt.jar" file somewhere in your JDK directory. It stands for "runtime," and contains all of the classes like JFrame.class. Feel free to open the rt.jar file up with WinZip and look at what's inside.

- Warren
 
  • #35
One thing that I forgot to ask about:

The main program imports all of the other subprograms that are written, but, for instance, JFrame.class is not in the c:\class directory. I'm assuming that I need to put it there? In general, do I need to put all of the supporting *.class files together or specify a path in the main program? How does that part work?
 
  • #36
No, the java.exe program has an envrionment variable called CLASSPATH that includes all the locations where JFrame.class is likely to live. When your program references JFrame, the runtime environment scans the CLASSPATH variable and finds the appropriate code. Unless you've changed the CLASSPATH variable somehow, you don't need to worry about finding it yourself. Just let the runtime environment find it.

- Warren
 
  • #37
I'm beginning to think that java is not what I want. I want to write programs that I can give to people to run on their computers. I don't want to have to give them an entire 50Meg java package.

Incidently, I got the lesson2 window to work. What's next? Here are some other things that I thought of besides animation:
- write a screen saver
- make a font for MS Word
- general file manipulation such as automatically moving/altering text in a *.txt file
 
  • #38
Java is not a suitable language for either making a screensaver or a font.

And yes, your users will need to have a Java runtime environment installed in order to run your Java programs. If I'm not mistaken, all versions of Windows from 98 on include one. It may be out of date, however, so you'd need to write your code to the lowest-common-denominator API.

You can also write your programs as applets and let the user run them within a web browser. Web browsers typically have up-to-date runtime environments, but getting around browser security can be a pain. If you want to manipulate the user's hard drive, for example, it will be tough to do from an applet -- web browsers try to keep applets from doing exactly those kinds of things.

- Warren
 
  • #39
OK. So, back to the animation applet. Lesson3 ...
 
  • #40
Are the lines
import java.awt.*;
and
import javax.swing.*;
analogous to "#include" preprocessor directives in c/c++ (although it looks like in Java they are actually compiled along with the rest of the commands)?

What's special about the "toplevel class"? Is it simply that main() resides there? What considerations are there as to what else does or does not belong in that file?

In "main(String[] argv)" is the argument required by Java syntax even though no command line parameters are being used by this program? I tried it with just "main(){" and it seemed to compile OK but it gave an error when i tried to run it?

And finally...
do you plan to continue this thread?

Thanks Warren.
 
  • #41
More questions:

where can I find a class that contains lines, arrows and circles?

what must be done to place a java program on a web page so it can be executed on-line?

(I'd like to try translating an animation that I wrote from c++ to java.)
 
  • #42
chroot said:
And yes, your users will need to have a Java runtime environment installed in order to run your Java programs. If I'm not mistaken, all versions of Windows from 98 on include one. It may be out of date, however, so you'd need to write your code to the lowest-common-denominator API.

You can't really expect a Java runtime to be installed on any Windows machine. A lot of them have it installed, but a lot of them don't. Because of the legal wrangling between Microsoft and Sun, there have been long periods of time where Microsoft wasn't distributing the runtime along with Windows.
 
  • #43
True, but I suspect that most people do have it anyway. The jre pretty much begs to be installed as soon as a web page containing an applet is loaded, and all it takes for most people to install sun's plugin is a couple of clicks, right?
 
  • #44
gnome said:
True, but I suspect that most people do have it anyway. The jre pretty much begs to be installed as soon as a web page containing an applet is loaded, and all it takes for most people to install sun's plugin is a couple of clicks, right?

Actually, that doesn't happen anymore either. On Windows XP with no Java installed, if you go to a web page with an applet you'll just get nothing.

Depending on the version of Windows and the browser you're using, you may already have the runtime installed, or it may be really easy to install it, or you may just be left wondering why certain web pages don't work on your computer. And even when the runtime is installed, it's anybodys guess which version it is.
 
  • #45
What's your point? Don't bother writing applets anymore? (Or in my case, don't bother learning how in the first place?)
 
  • #46
The import statements just make it easier to type the names of classes by importing packages of classes into the default namespace. Thus, after importing javax.swing.JFrame, you can just call it JFrame. In C/C++, the #include directive actually inserts a file into the current file. That's not true in Java.

The toplevel class contains a main method. Perhaps "toplevel class" is not an official term for it, but it gets the job done. The toplevel class contains the entry point of the program.

And yes, the (String argv[]) is indeed required. If you leave out the arguments, you get a different method, still perfectly valid, but without any arguments. The Java runtime environment is looking for one with arguments.

- Warren
 
  • #47
gnome said:
What's your point? Don't bother writing applets anymore? (Or in my case, don't bother learning how in the first place?)

No, of course not. Lots of great languages require a runtime to be distributed with programs written in them. It's just that Warren said that any version of Windows >= Win98 included a Java runtime, and I wanted to point out that you can't assume that.

If the fact that people may have to download a large runtime to use your program is a problem, then don't use Java to write that program. But there are lots of times when that isn't problem - so you can use Java then.

Normally I wouldn't just jump into a thread like this. But someone specifically mentioned that downloading a large runtime might be a problem, and I just wanted to give them all the facts.
 
  • #48
I have a question. What type of attitude should someone go into this with? I tried to learn java before, and i just got too bored of it. I found that i could never get a program to actually work because the debugger was too general. Any suggestions?
 
  • #49
A good programmer doesn't need a debugger. And no, I'm really not being condescending -- it's true.

What exactly were you having trouble with?

- Warren
 
  • #50
And chroot is sooo right!

Usually the best way to debug is by placing checkpoints.Checkpoints are nothing but placing print statements at some places in the program and see if the program behaves the way we want to...

In java, u can use System.out.println() to print values to the console.

A very useful function in c has always been getch() , so that the execution can be stopped at some point and the values can be carefully monitored...
Unfortunately there is not an equivalent in Java, but u can always make one ...

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class tri
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i;
try
{
i=br.read();
}
catch(Exception e){}
}
}

-- AI
 
  • #51
A good programmer doesn't need a debugger. And no, I'm really not being condescending -- it's true.
Strange statement.

Given some C code that's a couple of thousand lines that compiles fine without any errors at all, yet still gets a segmentation fault at run-time.
What would you do? How would you find that "of by 1" bounds error in some char*? Or that non null-terminated string you are expecting to be null terminated?

Using printf()-statements to check your code is fine, but are you sure you are handling all possible scenarios?

I'd say a debugger is a pretty important and powerfull tool for a programmer.
 
  • #52
It's a matter of philosophy, I suppose. I tend to use a variant of cleanroom software engineering techniques, and have not actually written an off-by-one error or an array bounds error in many years. I would actually be quite happy to accept your challenge in regards to a 1kloc piece of code that segfaults. In fact, I would even be willing to bet money on my ability to find the problem in just a few minutes.

I consider off-by-one errors and array bounds errors to be, well... novice mistakes. A debugger can certainly help a new programmer catch these kinds of mistakes, but, as the programmer gains experience, the debugger really just becomes less and less useful.

Once you throw threads and asynchronous data access into things, debuggers really become just about useless. The only way to write zero-defect code is to truly understand the code as you write it, and that takes experience.

- Warren
 
  • #53
A very useful function in c has always been getch() , so that the execution can be stopped at some point and the values can be carefully monitored...
Checking the backtrace is usually a lot faster. You can only guess where the problems are happening, the backtrace tells you where.

I'd say it would be far more superior just using breakpoints in your debugger and checking variables from there. As opposed to opening your file and commenting/uncommenting a debug-line somewhere in your source-code, recompiling and running again.
 
  • #54
I consider off-by-one errors and array bounds errors to be, well... novice mistakes.
They are done by professional programmers all the time. We are only humans.

I'm really not talking about ability here. Very few people will be able to write something huge that just compiles and works perfectly straight away.

It's more about finding the error or how to debug your code.

I'd say a debugger is far superior to any "insert various print-statements in your code" variants.

Once you throw threads and asynchronous data access into things, debuggers really become just about useless
The more complex code, the more complex datastructures etc. the more complex debugging becomes. Using a debugger with threaded code can tell you what thread is causing problems. I don't understand why this would be useless.

I'd actually say it the other way around:
Using a debugger when you are learning programming is dumb. It has only negative effects on your learning experience, but once you get more experienced a debugger is IMO a good thing.
 
  • #55
Dr-NiKoN said:
They are done by professional programmers all the time. We are only humans.
All programmers make mistakes. Few truly professional programmers make the same mistakes that students would make. The type of mistakes a programmer makes is certainly related to his/her experience. The effectiveness of a debugger is related to the type of errors being made, and thus is also related to the programmers experience.
I'm really not talking about ability here. Very few people will be able to write something huge that just compiles and works perfectly straight away.
I never said that. I said that experienced programmers don't make the kind of mistakes that debuggers are good at exposing.
I'd say a debugger is far superior to any "insert various print-statements in your code" variants.
Once again, it's a matter of philosophy. Many experienced programmers, myself included, think quite poorly of overuse of a debugger.
The more complex code, the more complex datastructures etc. the more complex debugging becomes. Using a debugger with threaded code can tell you what thread is causing problems. I don't understand why this would be useless.
What if the problem does not exist in one thread, but exists in the interdependence or cooperation of more than one thread?
Using a debugger when you are learning programming is dumb. It has only negative effects on your learning experience, but once you get more experienced a debugger is IMO a good thing.
You are welcome to your opinion. I have watched many students cling to the debugger far too long. Using a debugger forces a sort of "tunnel vision," in which students will make a change to their code, observe its behavior in the debugger, edit their code again, and so on. They freely add +1, for example, anytime they're off by one, without really considering the larger reason why their loop wasn't initialized properly in the first place. They place bandaids on open wounds without curing the underlying disease.

In my opinion, weaning oneself from a debugger is one of the first steps one can take to really being able to program. Learning strong, systematic software engineering techniques is the second.

- Warren
 
  • #56
Debuggers tend to be a crutch; they make it easier to avoid thinking about the code you are trying to fix, just using trial-and-error instead. Of course, doing trial-and-error programming by inserting prints or logging everywhere isn't any better.

I do agree that a debugger usually isn't harmful to someone who's already a good programmer. But it usually isn't useful, either. Even if you have to fix a really big chunk of spagetti code written by someone else who isn't a good programmer, you're still better off simplifying the code first and then trying to fix it. And debuggers just aren't very useful for simple code.

Debuggers are only useful if you have code that you can't trace through in your head. This generally means that either the code jumps around alot, or has a large number of variables. Both of those things generally only occur in badly written code. Don't write such code yourself. If the code wasn't written by you, make it into good code before you try and debug it. If that is beyond your abilities, then you are not a good programmer.
 
  • #57
My first Java class

Here's my first stab at Java. No fancy graphics, just a simple queue implemented as a linked list. It actually seems to work :approve: but I'd appreciate any constructive criticism you might offer.

In particular, I'm wondering about my implementation of Empty(). In C or C++ I'd never just "dump" the nodes the way I did here, but I get the impression that this is OK in Java. Yes?

Also, should my deQueue() method provide some protection against the user attempting to remove an object from an empty queue, or is the normal practice to leave that for the main program to deal with (as I did here)?

(It's homework, so please offer criticisms/suggestions, but don't rewrite it for me.)

Thanks.


Here's MyQueue.java:
Code:
//	MyQueue.java

public class MyQueue {
	MyNode first;
	MyNode last;
	int size;

	public MyQueue() {
		first = null;
		last = null;
		size = 0;
	}

	public boolean isEmpty() {
		if (size == 0)
			return true;
		else
			return false;
	}

	public void enQueue(Object o) {
		MyNode nextNode = new MyNode(o);
		if (isEmpty()) {
			first = nextNode;
			last = nextNode;
		}
		else {
			last.next = nextNode;
			last = nextNode;
		}
		size++;
	}

	public Object deQueue() {
		MyNode temp = first;
		if (size == 1) {
			first = null;	
			last = null;
			size --;
		}
		else if (size > 1) {
			first = first.next;
			size --;
		}
		return temp.data;
	}

	public void Empty() {
		first = last = null;
		size = 0;
	}
}
			
	


class MyNode {
	Object data;
	MyNode next;

	MyNode (Object o) {
		data = o;
		next = null;
	}

}

and here's a test driver, testMyQueue.java:
Code:
//	testMyQueue.java
//	test driver for MyQueue class

class testMyQueue {
	public static void main(String[] args) {
		MyQueue q = new MyQueue();
		Integer n;

		for(int j=0; j<4; j++) {
			System.out.println("\nTesting five entries to the queue.");
			for(int i=0; i<5; i++) {
				n = new Integer(2*i*j);
				q.enQueue(n);
			}

			while(!q.isEmpty()){
				n = (Integer) q.deQueue();
				System.out.println(n);
			}
		}

		q.Empty();

		if(q.isEmpty()) {
			System.out.println("The queue is now empty.\n");
			System.out.println("One last trial...");
		}

		for(int i=0; i<5; i++) {
			n = new Integer(10*i);
			q.enQueue(n);
		}

		while(!q.isEmpty()){
			n = (Integer) q.deQueue();
			System.out.println(n);
		}


		System.out.println("Goodbye.");
	}
}
 
Last edited:
  • #58
gnome said:
Here's my first stab at Java. No fancy graphics, just a simple queue implemented as a linked list. It actually seems to work :approve: but I'd appreciate any constructive criticism you might offer.

For a first stab it looks pretty good!
No,you don't need to concern yourself with deallocating memory. This is a job for the garbage collector.

A few things:

1. Trying to dequeue an element from an empty queue should throw an exception. This is the usual practice in Java and it is good practice IMO. The client deals with the exception at whatever level it wants.

2. The Java coding convention is to use camel case names for methods (i.e. use "empty" instead of "Empty").

3. Using a sentinel node would simplify a lot of code. For example the empty check becomes "return first == last" and the enque function doesn't need case-by-case analysis. If you don't need a getSize() method then you could discard the size field.

4. The Node class should probably be nested in the Queue class. It can safely be made private. The user shouldn't know or concern himself with such details.

5. The member variables first, last and size should be private.

I hope that helps.

regards,
radu
 
Last edited:
  • #59
Thanks for the suggestions, Radu. I vaguely remember being briefly introduced to sentinels in my Data Structures class a couple of years ago, but I've never used one since then. I have improvised based on what I think a sentinel should do, but I'm not sure it's what you had in mind, unless you're using first as a reference to the sentinel, so please let me know if there's a better (or more generally accepted) way of implementing it.

Regarding the exception class, I haven't found any explanation of the purpose of the line
Code:
super();
Can you shed any light on that?
Also, I see that the "String s" exception constructor is optional, and I can't figure out what purpose it would serve. What can you tell me about that?

Here's my revised code.

MyQueue.java:
Code:
public class MyQueue {
	private class MyNode {
		Object data;
		MyNode next;

		MyNode () {				//	constructor for sentinel node
			data = null;
			next = null;
		}
		MyNode (Object o) {		//	constructor for other nodes
			data = o;
			next = null;
		}
	};

	private MyNode sentinel, last;

	public MyQueue() {
		last = sentinel = new MyNode();
	}

	public boolean isEmpty() {
		return sentinel == last;
	}

	public void enQueue(Object o) {
		MyNode nextNode = new MyNode(o);
		last.next = nextNode;
		last = nextNode;
	}

	public Object deQueue() throws EmptyQueueException {
		if (last == sentinel)
			throw new EmptyQueueException();

		MyNode temp = sentinel.next;
		sentinel.next = temp.next;
		if (last == temp)
			last = sentinel;
		return temp.data;
	}

	public void empty() {
		last = sentinel;
		last.next = null;
	}
}

EmptyQueueException.java:
Code:
public class EmptyQueueException extends java.lang.Exception {
	EmptyQueueException() {
		super();
	}

	EmptyQueueException(String s) {
		super(s);
	}
}


testMyQueue.java
Code:
class testMyQueue {
	public static void main(String[] args) {
		MyQueue q = new MyQueue();
		Integer n;

		for(int j=0; j<4; j++) {
			System.out.println("\nTesting five entries to the queue.");
			for(int i=0; i<5; i++) {
				n = new Integer(2*i*j);
				q.enQueue(n);
			}

			while(true){
				try {
					n = (Integer) q.deQueue();
					System.out.println(n);
				} catch (EmptyQueueException e) {
					System.out.println("Queue is empty");
					break;
				}
			}
		}

		for(int i=0; i<5; i++) {
			n = new Integer(2*i);
			q.enQueue(n);
		}

		q.empty();

		if(q.isEmpty()) {
			System.out.println("The queue is now empty.\n");
			System.out.println("One last trial...");
		}

		for(int i=0; i<5; i++) {
			n = new Integer(10*i);
			q.enQueue(n);
		}

		while(!q.isEmpty()){
			try {
				n = (Integer) q.deQueue();
				System.out.println(n);
			} catch (EmptyQueueException e) {
				System.out.println("We should never get caught here.");
			}
		}

		System.out.println("Goodbye.");
	}
}
 
  • #60
The line "super()" simply invokes the superclass constructor. In this case, it runs the java.lang.Exception constuctor. It is not necessary to explicitly call the superclass constructor, as it will be called automatically anyway, but it's never a bad idea.

The constructor that takes a String argument allows you to provide a message that might be helpful to the user of your class. In this case, the name of the exception is self-explanatory, so the String argument is not very useful. In some cases though, it's nice to provide a bit more detail as to exactly why the exception was thrown.

- Warren
 

Similar threads

Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 33 ·
2
Replies
33
Views
8K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 13 ·
Replies
13
Views
3K