Table of Contents
Related topics on additional pages, please click on the following links.
Introduction
Java is a structured, object-oriented programming language most similar to C++. The main differences between Java and C++ are:
- Platform-Independent: It is compiled for a Java Virtual Machine (JVM) for each platform
- In C++ you can point to specific memory locations, in Java there are no pointers
This is for standard Java code and not embedded code. The two differences are tightly related. Java runs on a virtual machine (JVM) to be able to execute without recompiling on multiple platforms. Because Java depends on being able to allocate space and assign all storage to specific locations, pointers would break that agreement. Therefore pointers are not allowed in Java. Like everything else, there are trade-offs. James Gosling and the ‘Green Team’ decided to create a way to help consumers better access technology in their own lives. This team developed the Java language at Sun Microsystems, now owned by Oracle. There are various expressions about giving someone too much flexibility, James Gosling was trying to use C++ to developed a user interface for a smart TV at Sun Microsystems.1 C++ is a very flexible language in which you can do almost anything you want to do (including writing awful C code). He decided to write a new language that kept the good parts of C++ (like Object-Oriented Programming), but stripped out areas of code that could cause problems (like pointers). Sun first released a package in 1993 to create applets that could be run on the Netscape Navigation browser (the only browser available at the time). As the language progressed, James Gosling added a new feature that would help programs run on multiple platforms and not be dependent on Netscape by creating the Java Virtual Machine (JVM). With platform-neutrality, Java was easier to learn and use than either C or C++ and protected the user and consumer form stupid/malicious mistakes or designs. One benefit of forcing the user to actually create and reference variables and other storage locations by name instead of by reference (pointers) is that Java and track memory usage and release memory when it is no longer needed. Many of languages, especially those that require pointers, require the programmer to keep track memory usage and then program routines to free up memory when it is no longer needed. Also, in Java you can only inherit from one object.
Some helpful definitions of the key pieces of OOP is available here. In Java, the two parts of a Class are Attributes and Behaviors (instead of Attributes and Methods). Its syntax is very similar to C++, except for the altered features (like no pointers) as described previously.
Downloading
There are two possible download sites. The one I am giving first is the one I use for my class. I currently use Java 14.02 through the Oracle distribution. The official Oracle Java 14.02 download page is available. Go to that page and scroll down to choose the version that will run on your system. The JVM is compiled for specific hardware and operating system, so be sure to download the correct version.
Java is now open source, meaning there is independent development of the language outside of Oracle. The Oracle site is about while there is also an “official” Java page. The en at the end indicates it is the English page. It should be able to detect your browser and operating system and bring up the correct download for your system. If it does not, then select the download for the O/S that is on your system.
Processor Bus Width
One problem I have encountered is that Java will detect the proper O/S, but not the bus width (32 vs 64). If you what to use an IDE, like Eclipse or IntelliJ Idea, then the Java and Eclipse or IntelliJ Idea installs must be for the same O/S and Bus Width. If the Bus Width is a mismatch, then Java will install correctly, but Eclipse will not. It will exit with an Error 13. I believe that IntelliJ Idea has a better downloading mechanism. We use IntelliJ Idea in class.
To show how to download both, I have created the following video:
Make sure that the Java bin directory is in your execution path. If the installation worked correctly, it should be. Otherwise you will need to add the directory. If you are on a LINUX/UNIX system, I will assume you will know how to add a new path to your $PATH environment variable. For a Windows 10 system, right click the Windows icon and select the System entry. In the System dialog box, Click on the Advanced System Settings on the left. In the System Properties dialog box, click on the Environment Variables… button on the bottom. In the Environment Variables dialog box, click the Path entry and then press the [Edit] button. In the Path dialog box look carefully at the paths already present. If it was installed, then you do not need to add the Java path. If it is not installed, then press the [New] button. Do not browse before you do this, because the file you browse will replace the line that is selected. Aftre pressing [New] the highlighted line should now be the last line on the list. First open up a browser and see where your Java bin\ directory is located. It will either be under Program Files or Program Files (x86) Please check both. The newest copy was under the (x86) directory. The entry could be either depending the version you have installed. I used:
C:\Program Files (x86)\Java\jre1.8.0_144\bin
or for Java 14.02:
C:\Program Files\Java\jdk-14.0.2\bin
Set up Java in your favorite Development Environment. In Eclipse, I downloaded the Java Environment. Make sure that the version you are downloading matches the bus width of your processor and of the Java you installed. When I started Eclipse Neon and started a new Java project, it did label the JRE as JavaSE-1.8. My set-up looked like:
Press finish when you are done. Be careful about modifying files outside of Eclipse, especially deleting a file. I had an extra file that I deleted outside of eclipse and Eclipse would not start properly after that. I reloaded Eclipse, which fixed the problem but erased my project.
First Project
IntelliJ Idea
Try to think as simply as possible. Create and empty project and then create your one line program.
Eclipse
I decided to write a simple Java program using the Eclipse Neon environment. My first project was named FirstProject and had two files, Convert and Testing. the Java in Eclipse environment looks like:
Java requires each file to have one and only one wrapper class. See I wanted a Convert class to convert between km and miles and the main program to not be included in this class. Since the main program could not be in the Convert class and it had to be in its own class, I created a Testing class for the main procedure. The files are:
Convert.java
package FirstProject; /* Convert.java - Wayne Cook - 15 October 2016 */ public class Convert { double miToKm = 1.6; /* Set up conversion vactor */ /* Create a converting method for miles to km */ public double converMiToKm(double inVar) { double km = inVar * miToKm; return(km); } /* Create a converting method for km to miles */ public double converKmToMi(double inVar) { double miles = inVar / miToKm; return(miles); } }
Testing.java
package FirstProject; public class Testing { public static void main(String[] args) { double inVar = 372.45; Convert convert= new Convert(); /* Constructors automatically created. */ double miles = convert.converKmToMi(inVar); System.out.print(inVar + " 372.45 kilometersis 232.78124999999997 miles. 372.45 miles is 232.78124999999997 372.45 kilometersis 232.78124999999997 miles. 372.45 miles is 232.78124999999997 kilometers. . is " + miles + " miles.\n"); double km = convert.converKmToMi(inVar); System.out.print(inVar + " miles is " + km + " kilometers.\n"); } /* Destructor for instants of Convert class called on exit */ }
Results
372.45 kilometers is 232.78124999999997 miles. 372.45 miles is 232.78124999999997 kilometers.
Looping
Looping in Java is very similar to Looping in any other structured Language. The two most commonly used loops are the for and while loops. the best way to show how to use them is to give examples. To keep the examples similar, these are the same three modules that were used in the Python description, modified to work in Java. Even though Java does not require template files for using other classes defined in the same package or defined in standard System files/classes, Java does require naming the class.method to access all methods outside the file and class that contains the main program. Java does require a full formatting of all content of a print statement. If you want a space, you need to insert a space as ” “ and a new line as “\n”. Eclipse has its own Java based Scanner tool instead of the standard Console. This is found on the bottom of the Eclipse IDE and shows the standard output. The first implementation of the common code does not use standard input, instead it loops through three numbers using the for loop.
Fibonacci.java
package Fibonacci; /** Finonacci.java - 15 October 2016 * Calculate the Fibonacci Sequence, given any number * @author Wayne Cook * */ public class Fibonacci { /* Function to create a Fibonacci sequence - receives integer, returns array of integers */ public int[] fibonacci(int n) { int[] list = new int[100]; /* Create storafe for array of 100 integers */ int index = 2; /* Keep track of what member of the array to fill. */ if (n <= 0) { list[0] = 0; /* I prefer to have only one return per function */ } else if ( n < 2 ) { list[0] = 1; /* You may prefer return's though, your choice */ list[1] = 0; } else { int current, next; /* Needed for calculating the sequence */ current = 1; next = 2; list[0] = current; list[1] = next; while (next < n) { list[index] = current + next; current = next; next = list[index]; index++; if (next > n) { /* There is a chance that next will be larger than n */ break; /* Do not include it in the list. */ } } } list[index] = 0; /* Set endflag */ return(list); /* This is my one return for this function */ } }
MyBasics.java
/** MyBasic.hjava - 15 October 2016 * Wayne Cook * Some Basic routines I would like in multiple projects */ package Fibonacci; /** MyBasics - 15 October 2016 * @author WAYNEW * Basic math routines * Functions I find basic and needed in multiple modules */ public class MyBasics { // Count the number of digits in a number int countDigits(int n) { return(Integer.toString(n).length()); } // Check if input is integer public static boolean isInteger(String n) { boolean returnVal = true; // Set the answer is True, unless an exception occures try { int number = Integer.parseInt(n); if (number <= 0) { returnVal = false; // Sometimes atoi reurns 0 for a non-integer input. } } catch (NumberFormatException e) { returnVal = false; // A non - integer input was found } return(returnVal); } // Check if input is a perfect number (sum of factors, except for self, = self // The option prFactors allows the users to print all of the factors and sum. public static Boolean isPerfect(int n,Boolean prFactors) { int sum = 0; if (prFactors) { System.out.print("Factors for " + n + ": "); } for (int factor = 1; factor <= (n/2); factor++) { if (n%factor == 0) { if (prFactors) { System.out.print(factor + " "); } sum += factor; } } if (prFactors) { System.out.print("with sum " + sum + "\n"); } if (sum == n) { return(true); } else { return(false); } } // Overload isPerfect so individual factors do not have to be pronted. public static Boolean isPerfect(int n) { return(isPerfect(n,false)); } } }
TestingFib.java
/** testing -- 15 October 2016 * Author: Wayne Cook * */ package Fibonacci; /** TestingFib.java - Main program - 15 October 2016 * @author WAYNEW * */ public class TestingFib { /** * @param args */ public static void main(String[] args) { Fibonacci fibonacci = new Fibonacci(); for (int number = 100; number <= 10000; number *= 10) { int[] list = fibonacci.fibonacci(number); // Print the sequence System.out.print("The number " + number + " has the Fibonacci sequence of:\n"); for (int i=0;i<100;i++) { if (list[i] > 0) { System.out.print(list[i] + " "); } else { System.out.print("End\n"); break; } } // Determine the perfect numbers (sum of factors == number) in this range System.out.print("The perfect numbers are: "); for (int factor = 1; factor <= number; factor++) { if (MyBasics.isPerfect(factor)) { System.out.print(factor +" "); } } System.out.print("\n"); // Use the optional parameter to print the factors of the number String perfTest; if (MyBasics.isPerfect(number,true)) { perfTest = " is "; } else { perfTest = " is not "; } System.out.print("Number " + number + perfTest + "a perfect number\n"); } } }
Results
The number 100 has the Fibonacci sequence of: 1 2 3 5 8 13 21 34 55 89 144 End The perfect numbers are: 6 28 Factors for 100: 1 2 4 5 10 20 25 50 with sum 117 Number 100 is not a perfect number The number 1000 has the Fibonacci sequence of: 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 End The perfect numbers are: 6 28 496 Factors for 1000: 1 2 4 5 8 10 20 25 40 50 100 125 200 250 500 with sum 1340 Number 1000 is not a perfect number The number 10000 has the Fibonacci sequence of: 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 End The perfect numbers are: 6 28 496 8128 Factors for 10000: 1 2 4 5 8 10 16 20 25 40 50 80 100 125 200 250 400 500 625 1000 1250 2000 2500 5000 with sum 14211 Number 10000 is not a perfect number
Common Code
I now allow input through the Eclipse Scanner pane, instead of using the more common Console dialog box. The code and results are as follows:
TestingFib.java
/** TestingFib.java - Main program - 15 October 2016 * @author WAYNEW * */ package Fibonacci; import java.io.BufferedReader; import java.io.Console; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class TestingFib { /** * @param args */ // Workaround for System.console() always returning null /* Ignore this code for now, it was supposed to be the solution //private static String readLine(String format, Object... args) throws IOException { // if (System.console() != null) { // return System.console().readLine(format, args); // } // System.out.print(String.format(format, args)); // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // return reader.readLine(); } * End of ignored coed */ public static void main(String[] args) { Fibonacci fibonacci = new Fibonacci(); boolean notInteger = true; String inLine; Scanner in = new Scanner(System.in); // Alternative to Console int number = 0; //Number must be initialized, but will be reset during while loop. Console console = System.console(); // This is supposed to crete the console. while (notInteger) { //inLine = console.readLine("Enter your number for Fibonacci evaluation: "); // This was suppose to work, but it does not System.out.print("Enter your number for Fibonacci evaluation: "); inLine = in.nextLine(); if (MyBasics.isInteger(inLine)) { notInteger = false; number = Integer.parseInt(inLine); // number must be set here, because inLine not valid outside while loop. } else { System.out.print("Your entry was not an integer, please try again.\n"); } } int[] list = fibonacci.fibonacci(number); // Print the sequence System.out.print("The number " + number + " has the Fibonacci sequence of:\n"); for (int i=0;i<100;i++) { if (list[i] > 0) { System.out.print(list[i] + " "); } else { System.out.print("End\n"); break; } } // Determine the perfect numbers (sum of factors == number) in this range System.out.print("The perfect numbers are: "); for (int factor = 1; factor <= number; factor++) { if (MyBasics.isPerfect(factor)) { System.out.print(factor +" "); } } System.out.print("\n"); // Use the optional parameter to print the factors of the number String perfTest; if (MyBasics.isPerfect(number,true)) { perfTest = " is "; } else { perfTest = " is not "; } System.out.print("Number " + number + perfTest + "a perfect number\n"); } }
Results
Enter your number for Fibonacci evaluation: This is a string Your entry was not an integer, please try again. Enter your number for Fibonacci evaluation: Still another string Your entry was not an integer, please try again. Enter your number for Fibonacci evaluation: 10000 The number 10000 has the Fibonacci sequence of: 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 End The perfect numbers are: 6 28 496 8128 Factors for 10000: 1 2 4 5 8 10 16 20 25 40 50 80 100 125 200 250 400 500 625 10 00 1250 2000 2500 5000 with sum 14211 Number 10000 is not a perfect number
Footnotes
1. Information form Sam’s Teach Yourself Java 2 in 21 Days, Roger Cadenhead & Laura Lemay, Library of Congress Catalog Number: 2003110452, May 2004.PythonPython