Java-Logo
* Most of the material is taken from this book and this online course.

Java source code is stored in a file with the extension .java. Compiling the code creates one or more .class files, which contain processor-independent byte codes. The Java Virtual Machine (JVM) translates the byte code into machine-level instructions for the processor on which the Java application is running.

Running Codes in Java


To compile the code, invoke the Java compiler:
$javac SourceCode.java
this will create a new file SourceCode.class
To run the application, invoke the JVM:
$java SourceCode

Structure


/* Comments
   Comments
*/
public class ClassName {
    public static void main(String [] args) {
        System.out.println("Hello World!");
    }
}

Java has two fundamentally different kinds of data. It has primitive data types (boolean, byte, short, int, long, float, double, and char), everything else is an object, whether it's an array or a user-defined class, or a class that you find in a library.

Classes and Objects


Every Java program consists of at least one class. A class is a generic description and an object is a specific item of that class.
ClassName ObjectReference;
objectReference = new ClassName(argument list);

Can be unified in one command:
ClassName ObjectReference = new ClassName(argument list);

For example
Date birthday = new Date(12, 6, 1985);

Here Date(12, 6, 1985) is the object, birthday is the object reference, and 12, 6, 1985 are object data.

Example: (the first code is stored in SimpleLocation.java and the second one in LocationTester.java)
public class SimpleLocation{
  public double latitude;	/* member variables */
  public double longitude;
  public SimpleLocation(double lat, double lon){ /* Constructor */
    this.latitude = lat;
    this.longitude = lon;
  }
  public double distance(SimpleLocation other){		
    return Math.sqrt(Math.pow((this.latitude - other.latitude),2)
	            +Math.pow((this.longitude - other.longitude),2));
  }
} 

public class LocationTester{
    public static void main(String[] args){
        SimpleLocation place1 = new SimpleLocation(1, 2);
        SimpleLocation place2 = new SimpleLocation(4, 8);
        System.out.println(place1.distance(place2));
    }
}

Methods are the things that a class can do (like SimpleLocation and distance above).
A Constructor is a special method that gets called when an objects gets created. It doesn't have a return type, so it simply says public and then next word in the declaration of this method is just the name of the class.
we can oveload methods by defining a method with the same name but different number of arguments (different return type is not enough for overloading).

A private variable or method means that it is only accessible in the enclosing class, public means it is accessible from anywhere. More details here.
We should make member variables private and use getter and setter methods to access and change them.
public class SimpleLocation {
    private double latitude;
    private double longitude;

    public double getLatitude() {
        return this.latitude;
    } 
    public void setLatitude(double lat) {
	if (lat>100) {
	    System.out.println("Illegal value");
	}
	else {
            this.latitude = lat;
	}
    }
}

Packages


Java provides many classes for use in programs. They are grouped into packages:
java.lang (including String and Math class)
java.awt (including Graphics classes, old-style user interface)
java.swing (including Graphics classes, new-style user interface)
java.text (Classes for formatting numeric outputs)
...
Classes in the java.lang package are automatically available to programs, the other packages need to be imported:
import java.text.DecimalFormat;
import java.text.*;
imports the class DecimalFormat
imports all classes in the package

String Class


String s1 = new String("Hello");
String s2 = "World!";
System.out.println(s1 + " " + s2);
int lens1 = s1.length();
System.out.println(lens1 + s2.length());
int indexw = s2.indexOf('W');
System.out.println(s1.substring(0,2));
System.out.println(s1.charAt(4));
Hello World!

11
(0)
He
o

Input/Output


Programs can get the user input in several ways:
Dialog Box
import javax.swing.JOptionPane;

public class DialogBoxDemo {
    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog(null, "Please enter your name");
        JOptionPane.showMessageDialog(null, "Hello, " + name);
	String yearStr = JOptionPane.showInputDialog(null, "At which year you were born?");
	int yearInt = Integer.parseInt(yearStr);
        JOptionPane.showMessageDialog(null, "You are " + (2016 - yearInt) + " years old");
    }
}
Java Console
import java.util.Scanner;

public class JavaConsoleDemo {
    public static void main( String [] args ) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter your first name: ");
        String firstName = scan.next();
	System.out.println("Hello " + firstName);
        System.out.print("At which year you were born? ");
    	int birthYear = scan.nextInt();
        System.out.println("You are " + (2016 - birthYear) + " years old");
    }	
}

Reading Data From a Text File
import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class EchoFileData {
    public static void main( String [] args ) throws IOException {
	int number;
	File inputFile = new File("input.txt");
	Scanner scan = new Scanner(inputFile);
	while (scan.hasNext()) {
	    number = scan.nextInt();
	    System.out.println(number);
	}
	System.out.println("End of File Detected");
    }
}

- We use the File class to convert the filename, input.txt, to a platform-independent filename. If the file is not in the same directory, we need to give the full path. Note that we need to use an escape sequence of two backslashes (e.x. c:\\input.txt).
- scan.hasNext() returns true iff there is another token in the input stream.

Applets


Java applets are run by internet browser or an applet viewer. The JApplet class, an existing Java class of the swing package, provides the basic functionality of an applet. An applet class that we write is an extension of the JApplet class. The main method is not used in applets.
import java.swing.JApplet;
import java.awt.Graphics;

public class ShellApplet extends JApplet {
    public void init() {
    }
    public void paint(Graphics g) {
	super.paint(g);
    }
}

The statement super.paint(g) calls the paint method of the superclass (JApplet class).
import java.swing.JApplet;
import java.awt.Graphics;

public class AppletDemo extends JApplet {
    public void paint(Graphics g) {
	super.paint(g);
	g.drawString("Hello World!", 140, 100);
	g.drawLine(100,150,100,250); // a vertical line
	g.setColor(Color.RED); // From now on the color of drawigs will be red
    }
}

We tell the browser to launch an applet by including an APPLET tag as part of the HTML code.
<APPLET CODE="ClassName.class" CODEBASE="Path to the directory of class file" WIDTH=w HEIGHT=h></APPLET>

Flow of Control (if, if/else, (?:). switch)


if (condition) {
    block }

If block has only one statement we can write as:
if (condition) 
    statement;

The equality operator (==) checks whether the object references point to the same object. To compare the object data, we need to use equals (also equalsIgnoreCase) method.
Date d1 = new Date(12, 6, 1985);
Date d2 = new Date(12, 6, 1985);
Date d3 = d1;
if (d1 == d2)
    System.out.println('yes');
if (d1 == d3)
    System.out.println('yes');
if (d1.equals(d2))
    System.out.println('yes');
if (d1.equals(d3))
    System.out.println('yes');

yes

yes

yes

The conditional operator (?:) while not a statement in itself, can be used as a shoter version of if/else
variable = (condition ? expression1 : expression2);

is equivalent to
if (condition)
    variable = expression1;
else
    variable = expression2;

int door;
if (inputNum == 2)
    door = inputNum;
else door =1;
is equivalent to
int door = (inputNum == 2 ? inputNum : 1)

The switch Statement can be used instead of an if/else if statement when the condition consists of comparing the value of an expression to constant integers or characters.
operationS = scan.next();
operation = operationS.charAt(0); 
switch (operation) {
    case 'a':
    case 'A':
    	// perform the addition
    	break;
    case 's':
    case 'S':
	// perform the subtraction
        break;
    default:
	// print "invalid input" }

Misc.


DecimalFormat Class
import java.text.DecimalFormat;

public class DecimalFormatDemo {
    public static void main(String[] args) {
        DecimalFormat myPattern = new DecimalFormat("0.00%");
	double percent = 0.374;
	System.out.println(myPattern.format(percent));
    }
}
37.40%


Random Numbers
The random method returns a double value between 0 and 1 (not including 1).
double rand = Math.random()

Generate a random integer between 6 and 20:
int rand = 6 + (int) (Math.random() * 20);
Processing Library
import processing.core.*;

public class processingDemo extends PApplet {
    private String URL = "https://...";
    private PImage backgroundImg;
    public void setup() {
       size(300,300);
       backgroundImg = loadImage(URL,"jpg");
       backgroundImg.resize(0, height);
    }
    public void draw()  {
         image(backgroundImg,0,0);
         fill(255,209,0);
         ellipse(width/4,height/4,width/4,height/4);
    }
}