Hello everybody. I have experience with c++ and c programming. I wasn't expecting Java to give me such a difficult time, but I am having a hard time grasping in.
In c/c++, you have a main function and other functions that come up as you call them from your main function. I see this isn't the case in Java. For example, I am studying the following code from Sam's Teach yourself java in 24 hours:
import java.awt.*; import javax.swing.*; import java.awt.event.*; class PrimeFinder extends JFrame implements Runnable, ActionListener { Thread go; JLabel howManyLabel = new JLabel("Quantity: "); JTextField howMany = new JTextField("400", 10); JButton display = new JButton("Display primes"); JTextArea primes = new JTextArea(8, 40); PrimeFinder() { super("Find Prime Numbers"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); BorderLayout bord = new BorderLayout(); setLayout(bord); display.addActionListener(this); JPanel topPanel = new JPanel(); topPanel.add(howManyLabel); topPanel.add(howMany); topPanel.add(display); add(topPanel, BorderLayout.NORTH); primes.setLineWrap(true); JScrollPane textPane = new JScrollPane(primes); add(textPane, BorderLayout.CENTER); setVisible(true); } public void actionPerformed(ActionEvent event) { display.setEnabled(false); if (go == null) { go = new Thread(this); go.start(); } } public void run() { int quantity = Integer.parseInt(howMany.getText()); int numPrimes = 0; // candidate: the number that might be prime int candidate = 2; primes.append("First " + quantity + " primes:"); while (numPrimes < quantity) { if (isPrime(candidate)) { primes.append(candidate + " "); numPrimes++; } candidate++; } } public static boolean isPrime(int checkNumber) { double root = Math.sqrt(checkNumber); for (int i = 2; i <= root; i++) { if (checkNumber % i == 0) { return false; } } return true; } public static void main(String[] arguments) { PrimeFinder fp = new PrimeFinder(); } }
I see that main calls PrimeFinder(), but from there the other functions aren't called. Why does this work? does run() start up on its own because Runnable is implemented at the top? In c/c++ I would call the run() from withing my main(). actionPerformed isn't even called from what I can see. What makes this work? Sorry for the newb question. I just really want to learn this stuff. Thanks in advance