The rest..Part 3 |
Here are 5 'misc' topics:
Consider following code below - it should result in a compilation error (twice), as we'd expect - reason being that in class R, we can't access Main's private member x:
public class Main {
private int x=8;
}//Main
class R {
public void getX() {
Main n = new Main();
double y = n.x; // not allowed!
}
public static void main(String[] args) {
Main n2 = new Main();
double y = n2.x; // not allowed!
}
}//R
But, the following code compiles, and runs!! Why?
public class Main {
private int x=8;
public static void main(String[] args) {
Main n = new Main();
double y = n.x; //??!! THIS WORKS!
System.out.println(y);
n.x = 24; // "OMG"
System.out.println(n.x); // works, again
}
}//Main
class R {
public void getX(){
Main n = new Main();
//double y = n.x; // compilation error
}
public static void main(String[] args){
Main n2 = new Main();
//double y = n2.x; // compilation error
}
}//R
Reason: inside a class, EVERY function (public, private, protected), EVEN STATIC FUNCTIONS, INCLUDING main(), have access to ALL vars+methods in that class, including private members+methods! So this means that inside Main's main(), we can access (get/set) 'x', a private var. But, main() being static, we can't just access x by saying x, which is going to be inside an object (because x is a regular member, not a static one) - so we need to create an object and use the object's name to access its x, hence the ODD-LOOKING s.x syntax - in no other class will s.x (for example) ever be accessible, given an object s of type Main created in that class!
We know how to read a text file, and examine contents line by line.
import java.io.*;
class readFile {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("c:\\temp\\test.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}// readFile()
But how would we split a line, into 'words' (tokens)? We'd need to do so for extracting numbers and strings from our text files, for further processing (calculating, searching, displaying, counting etc.).
There are two ways: we can either use the StringTokenizer class, or use String's split().
So now we can do things like word counting - eg. number of occurences of 'Alice' in Alice in Wonderland:
import java.io.*;
class wordCount {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("c:\\temp\\Alice.txt");
BufferedReader br = new BufferedReader(fr);
String s;
int nOcc=0;
String tok="Alice";
while((s = br.readLine()) != null) {
// System.out.println(s);
String toks[] = s.split(" ");
for (int j=0; j < toks.length; j++) {
if(toks[j].equals(tok))nOcc++; // if 'Alice', increment
}// next token to examine
}
fr.close();
System.out.println(tok + " count: " + nOcc);
}// main()
}// class wordCount
The above code omits counting 'Alice:', 'Alice,', 'Alice!', 'Alice.', etc. [since it only checks if a word equals 'Alice'] - how would you cause those additonal occurrences to also get counted? Hint - could you use a method that checks if a string "starts with" another string, eg. checks if 'Alice!' starts with 'Alice', 'USC' starts with 'Alice'..? To find out if such a method exists, look up docs for the String class, eg. https://docs.oracle.com/javase/7/docs/api/java/lang/String.html.
Here is how we can run a method on an object that we created by using a classname string (via the 'Reflection API'):
// 4 steps: class, object, method, invoke (call)
Class exampleClass = Class.forName(whatClass); // 1
Object ob = exampleClass.newInstance(); // 2
java.lang.reflect.Method method=null;
try {
method = ob.getClass().getMethod("meth"); // 3
}
catch (SecurityException e) {}
catch (NoSuchMethodException e) {}
try {
method.invoke(ob); // 4 [compare with ob.meth(), which won't even compile!]
}
catch (IllegalArgumentException e) {}
catch (IllegalAccessException e) {}
catch (java.lang.reflect.InvocationTargetException e) {}
//...
// the following works, too, as an alternative to the above - but the
// above can be used to specify a class and a method during RUNTIME,
// whereas what is below is hard-coded into the program (and is therefore
// not flexible at all):
A a = new A();
a.meth();
The Reflection API has more goodies..
You can easily create quite complex 3D scenes via code, by writing out VRML2.0's .wrl ("world") text-based scene files. Before today's VR, there was (is!) VRML (Virtual Reality Modeling Language) that dates back to the early 90s.VRML is simple, fun! Related note - there's also Java3D, X3D and X3DOM, that all descended from VRML.
Save the following text scene as 'sph.wrl' (for example), download instantplayer [Win or Mac binary] to view the scene in 3D :) FYI here are more players/viewers: https://www.vrinternal.com/docs/links.html. Or, simply use one of these online viewers: https://3dviewer.net/ or https://webview.dental/.
#VRML V2.0 utf8 # NEED the above header in every .wrl file! Shape { appearance Appearance { material Material { diffuseColor 1.0 .2 1.0 transparency 0.0 } } geometry Sphere { radius 1.0 } }
Next, examine this cool device :)
What if we created a .wrl containing a bunch of random (x,y,z) points (inside an enclosing, invisible unit cube), and placed a tiny sphere at each (x,y,z) location? In pseudocode form:
open a file to write into, add VRML2.0 header (#VRML V2.0 utf8) loop: create a random x,y,z place [write out] a tiny VRML sphere at x,y,z next close file
This is what the Java code for the above would look like.
HAVE FUN!! You can use VRML2.0 to write out very rich scenes containing a variety of geometry, materials, light sources.. You can even add animation and interactivity! You can examine the simpler scenes in here, which you can use as a starting point for creating 3D scenes.
Mini challenge: write out the sphere data from above, in the 'aframe.io' format:
<html> <head> <script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script> </head> <body> <a-scene> <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box> <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere> <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder> <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane> <a-sky color="#ECECEC"></a-sky> </a-scene> </body> </html>
The above is a modern 'VR' scene (check out http://aframe.io)! You can use Google Cardboard etc. to view it..
The classic 'Fintech' Black-Scholes equation (PDE) and solution formula(e) have to do with calculating the theoretical price of call ("buy") and put ("sell") options.
An option is a 'derivative' "financial instrument": it is something you buy, that gives you the right, without the obligation, to buy (or sell) stocks at a future time, at a pre-determined (at the time of buying the option) price known as the 'strike price'. A right-to-buy option is called a 'call option', and a right-to-sell option is a 'put option'. In options lingo, you can ['currently'] 'buy a call', 'sell a call', 'buy a put' or 'sell a put' :) Deciding to ACTUALLY buy (or sell) the underlying stock, is called 'exercising the option'.
From Economic Times:
From Investopedia:
This is another look at the Nobel-prize-winning formulae.
Below are three different implementations of B-S.
Here is a small package that calculates the call and put values as per the formulae (download, compile, run [be sure provide command line args, eg. 56.25 55 0.34 0.0285 0.28]).
This is another implementation with nicely commented code, all in a single source file :)
This is yet another very compact program [just two fns!] :)
A library with a rich API for financial engg calculations: https://code.google.com/p/maygard/
An Intel article on optimized B-S calcs.
Another extensive library: http://finmath.net/finmath-lib/
If fintech bores you, you could look at an application of the cable equation instead :)
Study all this code, make small mods, then make larger mods, then start adding extra functionality, and become an expert user+coder :)