Intro

JRE / JDK / IDE

  • JRE (Java Runtime Environment): includes the JVM (java virtual machine) and libraries. To run a program!
  • JDK (Java Development Kit): Includes the java compiler, needed to develop java programs!
  • IDE (Integrated Development Environment): a program like eclipse or netbeans, that automatically compiles the sourcecode before running the program.

Compiler

Java is a compiled language, meaning that the source code needs to be transformed into bytecode by the java compiler! After compilation, the program can be run by the java virtual machine! Java files look like this:

  • test.java: sourcecode written in java-syntax! humanly readible!
  • test.class: bytecode (machine code), which can only be read and executed by the java virtual machine!
  • .java files are usually stored in src (source), while .class files are stored in bin (binary) directory.

Commandline

# check if java is installed (shows version)
java -version 

# compiles a .java file (creates .class file)
javac Test.java

# run compiled .class file (no file extension)
java Test

Basic Commands

Comments

// line comment 

/* block comment
 * this is still part of the comment
 * third line of comment
/* 

/** Java-doc comment */  // used to auto generate documentation!

Example Code

// import packages
import javax.swing.JOptionPane;   // only «JOptionPane» 
import javax.swing.*;             // whole package «swing»

// class declaration
public class Test () {
    // main method (to make the program runnable)
    public static void main(String[] args) {  
        // print message to console
        System.out.println("Hello World!");
    }
}

Printing to Console

// console out
System.out.print(X);      // prints X (no newline)
System.out.println(X);    // prints X (with newline at end)
System.out.printf();      // more advanced console log method

Operators

/*  LOGICAL OPERATORS       | MATH OPERATORS
----------------------------|-------------------------------
==  ist gleich              | =  Zuweisung	
!=  ist ungleich            | +  Addition / Konkatenation
>=  grösser-gleich          | -  Subtraktions-operator
<=  kleiner-gleich          | *  Multiplikations-operator
&   und                     | /  Divisions-operator
&&  und (Short-Circuit)     | %  Modular-operator
|   oder                    |
||  oder (Short-Circuit)    |	


INCREMENT / DECREMENT

x++;    increment, then execute expression
++x; 	execute expression, then increment
x--;	decrement, then execute expression
--x;	execute expression, then decrement


SHORTHAND ASSIGNING

x += 5;	  // same as: x = x + 5
x -= 5;	  // same as: x = x – 5
x /= 5;	  // same as: x = x / 5
x *= 5;	  // same as: x = x * 5
x %= 5;	  // same as: x = x % 5
/*

Datatypes

Primitive Datatypes

byte byte1 = 127;                   // Byte [-128, 127]
short short1 = 32000;               // Short [-32'000, 32'000]
int int1 = 2100000000;              // Integer [-2.1 Mia, 2.1 Mia]
long long1 = 9200000000000000000L;  // Long [-9.2 Trio, 9.2 Trio], with "L"
float float1 = 3.14f;               // Float, add "f" at end
double double1 = 3.14157;           // Double (higher precision)
boolean boolean1 = (10>2);          // bollean [true, false]
char char1 = 'a';                   // Character
char char2 = '\uXXXX';              // Character (UNICODE STYLE)
String s1 = "hello!";               // String (NOT A PRIMITIVE TYPE)
// DECLARATION
double taxRate;
// INITIALIZATION
taxRate = 0.57;
// IMMUTABLE VARIABLES -> CONSTANTS
final float pi = 3.14f;
// GLOBAL VARIABLES
static int count = 0;          // visible inside the class
static final float pi = 3.14f; // global constant

Access Modifiers

MODIFIERclassPackageSubclassWorld
public
protectedx
no modifierxx
privatexxx

Converting Datatypes

// convert -> STRING
String s = Integer.toString(int1);         // int -> String
String s = "" + int1;                      // int -> String
String s = Double.toString(double1);       // double -> String
String s = "" + double1;                   // double -> String
String s = String.format("%.1f", double1); // double -> String (1 decimal place)
String s = new String(chAr);               // char[] -> String
char[] chAr = s.toCharArray();             // String -> char[]

// Array -> String
import java.util.Arrays;  // import Array Class
Arrays.toString(iArr);    // convert

// convert -> INTEGER
Integer.parseInt(s);            // String -> int 
Double.parseDouble(s);          // String -> double
Character.getNumericValue(ch);  // char -> int

// CASTEN
(int)x                // x will be casted to int
(double)x             // x will be casted to double
(datatype)variable    // general syntax

Strings

String s1 = new String("Hallo Welt");     // Stringvariable
String s2 = "Hallo Welt";                 // Kurzschreibweise
StringBuffer sb  = new StringBuffer();    // Erstellt StringBuffer
StringBuffer sb2 = new StringBuffer(s1);  // Erstellt StringBuffer aus s1

Escaping

System.out.println("\n");      // newline
System.out.println("\t");      // tab
System.out.println("\\");      // backslash
System.out.println("\"");      // double quotes
System.out.println("\'");      // single quotes
System.out.println("\uXXXX");  // inser unicode character

String functions

// teststring
String s = "Hello World";

// basic stringfunctions
s.length();                 // returns 11
s.substring(0,4);           // returns "Hello"


// string comparison
s.equals("HelloWorld!");    // true
s.contains("World");        // true

String Formatting

// print formatted string
System.out.printf();  // no newline!

// store formatted string
float f1 = 2.346f;
String s = String.format("my number: %.2f", f1);

// formatting options
%d    // integer				
%f    // float
%.2f  // float with 2 digits		
%s    // string	
%S    // string in capital letters
%c    // character
%C    // CHARACTER capital print
%b    // boolean
%B    // BOOLEAN capital print

// predefined string length:
%-15s // left align  -> puts spaces at end untill s.length() = 15
%15s  // right align -> puts spaces in front untill s.length() = 15 

// example
String s = String.format("%-15s", "hallo");

String Buffer

// initialize empty string buffer
StringBuffer sb = new StringBuffer();

// initialize string buffer and fill with string str
StringBuffer sb = new StringBuffer(str);

x = alle primitiven Datentypen od. char[] s = String b = StringBuffer sb.length(); Länge des StringBuffers b sb.append(x); Hängt x an b an sb.insert(pos, x); einfügen von x an der Position pos! sb.replace(from, to, str); ersetzt Buffer an Position from bis to mit str. sb.delete(from, to); lösche Buffer an der Position from bis to! sb.setCharAt(pos, 'a'); setzt b[pos] auf 'a' sb.charAt(pos); Gibt die Stelle pos von b als char an den Rufer sb.substring(from); Liefert Teilstring ab Index from sb.substring(from, to); Liefert Teilstring ab Index from bis to sb.length(); Länge des Buffers sb.toString(); Liefert Ihnalt des StringBuffers b als String

s.substring(from); Liefert Teilstring ab Index from s.substring(from, to); Liefert Teilstring ab Index from bis to s.length(); Liefert Stringlänge s.contains(s2); Patternmatching: liefert true/false int i = s.indexOf(s2); Patternmatching: Integer i gibt Position wieder (oder -1 falls nicht gefunden)

Arrays

// 2 step initialization
int[] intArr;           // declaration
intArr = new int[2];    // initialization with null's

// direct initialization with nulls
int[] intArr = new int[2];

// direct initialization with values
int[] intArr = {1,2,45};

Matrices

// 2 step initialization
int[][] matrix;           // declaration
matrix = new int[][];     // initialization

// direct initialization with null's
int[][] matrix = new int[2][4]; 

// direct initialization with values

Math

// HOW TO USE MATH LIBRARY
Math.function(inputs...);
Math.random();
// MATH FUNCTIONS
Math.abs(input);         // absolute value
Math.round(input);       // round
Math.ceil(double);       // round up
Math.floor(double);      // round down
Math.random(double);     // generates random double in range (0,1)
Math.pow(2, 1.5);        // power function: 2^(1.5)
Math.sqrt(double);       // square root (wurzel)
Math.exp(5);             // exponential function e^5

Loops / Conditionals

if else

if (condition == true) {
    System.out.println("Do something...");
} else if (condition2 == true) {
    System.out.println("Do something else...");
} else {
    System.out.println("no condtition true!");
}

switch

// example input
int day = 5;

/* dont forget to BREAK after each statement! otherwise 
 * all the statements below will be executed as well!
 */ 
switch (day) {
    case 1: 
        System.out.println("monday");
        break;                                 // break after each case
    case 2: 
        System.out.println("tuesday");
        break;                                 // break after each case
    case 3:
        System.out.println("wednesday");
        break;                                 // break after each case
    case 4:
        System.out.println("thursday");
        break;                                 // break after each case
    case 5:
        System.out.println("friday");
        break;                                // break after each case
    case 6: case: 7                       // combine two cases
        System.out.println("weekend!");
        break;                                // break after each case
    // DEFAULT will be run when no case is chosen! (similar to else)
    default:
        System.out.println("illegal input!");
        // if default is last case no need to break
        // add BREAK only when default is not last!
}

while

boolean condition = true;
while (condition == true) {
    System.out.println("i will print this unless condition is met");
    if (Math.random()<0.1) {  // condition will be met with 10% probability
        condition = false;
    }
}

for

for (int i=0; i<=10; i++) {     // increment +1 each round
    System.out.println("current run: " + i);
}
for (int i=0; i<=10; i+=2) {    // increment +2 each round
    System.out.println("current run: " + i);
}
for (int i=100; i>=0; i-=10) {  // decrement +10 each round
    System.out.println("current run: " + i);
}

for each

// int[]
int[] zahlen = {1,4,7,2};
for (int zahl : zahlen) {
    System.out.println(zahl);
}
// possible also for other more complex datatypes like HashMap, ArrayList or Objects!
ArrayList<String> arrListStr = new ArrayList<String>();
arrListStr.add("first string");
arrListStr.add("second string");
arrListStr.add("third string");
for (String s : arrListStr) {
    System.out.println(zahl);
}

break

// Loop1 is a label for the first loop
Loop1: 
for (;;) {  // for (;;){} is an endless loop, same as while(true)
    for (;;) {
        statement; 
        if (condition) { 
             break Loop1;
        }
    }
}

Snippets

ScreenCapture

  • example that reads each pixel of the screen
  • input: each pixed
  • output: manipulated pixels (overlay structure)
    • converts pixel into black and white.
    • red border to show manipulated pixels!
import java.awt.*;
import java.awt.image.*;

public class Test {

    public static void main(String[] args) throws AWTException {
        int xLen = 1000;    // width of the layer
        int yLen = 1000;    // height of the layer
        Robot r = new Robot();
        BufferedImage img = r.createScreenCapture(new Rectangle(0,0,xLen,yLen));

        // create overlayer Window
        Window w=new Window(null) {
            @Override
            public void update(Graphics g) {
                paint(g);
            }
            @Override
            public void paint(Graphics g) {
                // compute for each pixel corresponding greyscale
                for (int x=0; x<xLen; x++) {
                    for (int y=0; y<yLen; y++) {
                        // search for border-pixels!
                        if (x==0 || y==0 || x==xLen-1 || y==yLen-1) {
                            g.setColor(Color.RED);  // set borderColor to RED (255,0,0)
                        } else {
                            int rgb   = img.getRGB(x, y);
                            int red   = (rgb >> 16) & 0xFF;
                            int green = (rgb >>  8) & 0xFF;
                            int blue  = (rgb      ) & 0xFF;
                            int grey  = ((red+green+blue)/3);
                            g.setColor(new Color(grey, grey, grey));
                        }
                        // paint pixel 
                        // (@toDo: check if method for painting single pixel exists)
                        g.fillRect(x, y, 1, 1);		
                    }
                }
            }
        };
        w.setAlwaysOnTop(true);
        w.setBounds(w.getGraphicsConfiguration().getBounds());
        w.setBackground(new Color(0, true));
        w.setVisible(true);
    }
}

Robot

  • class can control keyboard and mouse of computer
// import needed classes
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
// Initialization
Robot robot = new Robot();

Keyboard Controller

// PRESSING THE KEYBOARD
// with key codes! -> use KeyListener to find out int value of each key!
robot.keyPress(10)    // press "enter" (enter keycode = 10)
robot.keyRelease(10)  // release "enter"

// with KeyEvent class
robot.keyPress(KeyEvent.VK_ESCAPE);   // presses ESC
robot.keyRelease(KeyEvent.VK_ESCAPE); // releases ESC

// some Keys
// see full documentation for KeyEvent for all keys
KeyEvent.VK_ENTER;   // enter
KeyEvent.VK_ESCAPE;  // ESC

KeyEvent.VK_UP;      // arrow: up
KeyEvent.VK_DOWN;    // arrow: down 
KeyEvent.VK_LEFT;    // arrow: left
KeyEvent.VK_RIGHT;   // arrow: right

KeyEvent.VK_PERIOD;  // .
KeyEvent.VK_EQUALS;  // =

KeyEvent.VK_ALT;     // alt
KeyEvent.VK_SHIFT;   // shift
KeyEvent.VK_CONTROL; // crtl ? (not sure)

KeyEvent.VK_NUMPAD0; // NUMPAD0 - NUMPAD9
KeyEvent.VK_F1;   // F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12

Mouse Clicker

// CLICKING MOUSE
robot.mousePress(InputEvent.BUTTON1_MASK);   // press leftclick
robot.mouseRelease(InputEvent.BUTTON1_MASK); // release leftclick

InputEvent.BUTTON1_MAST; // leftclick
InputEvent.BUTTON2_MAST; // middlemouse
InputEvent.BUTTON3_MAST; // rightclick

robot.mouseWheel(1);  // scroll down
robot.mouseWheel(3);  // scroll down (faster)
robot.mouseWheel(-1); // scroll up 
robot.mouseWheel(-3); // scroll up (faster)

JFrame

// initialize JFrame
JFrame jf = new JFrame("TITLE");

// JFrame methods
jf.setTitle("changed title")     // sets new title
jf.setVisible(true);             // make JFrame visible
jf.setSize(width, heigth);       // set size of canvas	
jf.setResizable(false);          // JFrame can be resized by user (Y/N?)
jf.setLocation(xPos, yPos);      // set location of JFrame on the users screen!
jf.setLocationRelativeTo(null);  // JFrame will appear in the middle of the screen. 
                                 // Must be called after setting the size, but 
                                 // before setting visible
// set closing parameter (end program when user closes JFrame!)
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)	

Selenium

Selenium