Hello World

Let's Get Started with Programming

Some Lines of Code

A minimal program with some activity

public class HelloWorld
{
   public static void main(String[] args)
   {
       System.out.println("Hello, World");
   }
}
  • Class name (HelloWorld) must match file name (HelloWorld.java)
  • Just copy the code as shown here
  • Use IDE auto-complete and formatting!

Code Style

The look and feel of code.

public class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("Hello, World");
   }
}

public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello, World");
   }
}

public class HelloWorld{
public static void main(String[]args){System.out.println("Hello, World");}}
  • Spaces and braces layout is not important for the compiler
  • Very important for the human in front of the computer
  • Compiled code is the same
  • Some braces are required, some aren't
  • Semicolon usually rules in Java
  • Spaces are needed when the meaning otherwise changes
  • Casing is important (PUBLIC vs. public)

Code Style

Personal taste or a standard set by the company your work for.

/**
 * Sun-Style
 */
public int lastIndexOf(int ch, int fromIndex) {
    if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
        // handle most cases here (ch is a BMP code point or a
        // negative value (invalid code point))
        final char[] value = this.value;
        int i = Math.min(fromIndex, value.length - 1);
        for (; i >= 0; i--) {
            if (value[i] == ch) {
                return i;
            }
        }
        return -1;
    } else {
        return lastIndexOfSupplementary(ch, fromIndex);
    }
}
/**
 * The Other-Style
 */
public int lastIndexOf(final int ch, final int fromIndex)
{
	if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT)
	{
		// handle most cases here (ch is a BMP code point or a
		// negative value (invalid code point))
		final char[] value = this.value;
		final int pos = Math.min(fromIndex, value.length - 1);

		for (int x = pos; x >= 0; x--)
		{
			if (value[x] == ch)
			{
				return x;
			}
		}
		return -1;
	}
	else
	{
		return lastIndexOfSupplementary(ch, fromIndex);
	}
}

Line by Line

Hello World taken apart

Packages

Group logical things together

package com.xceptance.trainings;

public class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("Hello, World");
   }
}
  • Packages are hierarchical groups
  • File directory hierarchy has to match
    com.xceptance.trainings = com/xceptance/trainings/
  • Classes per package unique, not necessarily across packages
  • Best practice: Within a project, classes should be unique
  • Package names should be all lowercase
  • Package indicates mostly project, company, subproject, API, and logical grouping

Comments

More important than code ;)

  • Comment everything
  • There are never enough comments
  • You do it for yourself and your colleagues
  • After two month, you will forget why you wrote it that way
package com.xceptance.trainings;

public class HelloWorld
{
    /**
     * This is the main method to start the program and
     * it also shows a Javadoc comment for later automatic
     * generation of documentation and improved IDE
     * suggestions.
     *
     * @param args command line parameters
     */
    public static void main(String[] args)
    {
        // line comment
        /* Single line comment */
        System.out.println("Hello, World"); // print something

        /*
            This is a block of comment and the compiler
            will happily ignore everything here.

            int a = 0;
        */

        // int a = 1;
        // int b = a + 1;
    }
}

Our First Class

The base is a class

package com.xceptance.trainings;

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello, World");
    }
}
  • Everything in Java is class, even the simplest program
  • public to be able to reach it from the outside
  • class hints the compiler, we are describing a class
  • HelloWorld is the name to be able to later find it again, refer to it, or create objects from
  • Name has to match the file name!

HelloWorld - Naming Classes

There is not right or wrong, there is only good and bad.

  • All unicode letters and digits _, $, starts with a letter or _, $
  • Recommended: A-Z, a-z, 0-9
  • Nothing protected (public, class, private, int)
  • Starts uppercase
  • CamelCasing
  • It should talk!
  • English only please
/**
 * Classes and Interface Naming
 */
public class CalculatorImpl extends Casio implements Calculator
{
}

public class Calculator99 extends Casio2017 implements Calculator0815
{
}

/**
* 这是真的
*/
public class 你好
{
}
package com.xceptance.trainings;

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello, World");
    }
}
package com.xceptance.trainings;

public class HelloWorld
{
    // That doesn't fly!
    public void main(String[] args)
    {
        System.out.println("Hello, World");
    }

    // That doesn't fly!
    public static void main() ...

    // This does
    public static void main(String[] arguments) ...

    // This doesn't.
    public static int main(String[] args) ...

}

Main

The entry point to the world of your program

  • public static void main(String[] args)
  • Only possible signature
  • public for reach
  • static before an instance of HelloWorld exists
  • String[] passed argument list, each command line parameter per array field (length 3 for -f 10 foobar)
package com.xceptance.trainings;

public class HelloWorld
{
   public static void main(String[] args)
   {
        int a = 3; int b = 4;
        int c = 5;

        if (a == 3)
        {
           a = 4;
        };

        if (a == 3)
        {
           a = 4;
        }

        if (a == 3) a = 4;

        if (a == 3)
            a = 4;

        if (a == 3); // !!!
        {
            a = 4;
        }
   }
}

The Semicolon

; is important

  • Semicolon terminates a command
  • Not required to be at the end
  • Best practice to end the line with it
  • A few ; are optional, some are breaking :)
public static void main(String[] args)
{
    int a = 3;
    {
        int a = 4; // Compiler rejects that
    }
    System.out.println(a);
}
public static void main(String[] args)
{
    {
        int a = 3;
    }

    {
        int a = 4;
    }

    // Compiler doesn't know a!
    System.out.println(a);
}
public static void main(String[] args)
{
    int a = 3;

    {
        a = 4;
        int b = 1;
    }

    System.out.println(a + b); // b unknown!
}

Curly Braces

Blocks and scope is defined by {}

  • Some are optional (single command if for instance)
  • Can be set to form a scope
  • Always use them even when optional
  • Correctly indent (auto-formatting of IDE helps)
  • Indent with 4 spaces, not tabs

Access Level

Determines visibility

package com.xceptance.trainings;

public class MyClass
{
    private void method1()
    {
    }

    void method2()
    {
    }

    protected void method3()
    {
    }

    public void method4()
    {
    }
}
  • Defines who can see and use what
  • For packages, methods, fields
  • Helps to structure
  • Important for API definition

Modifier Class Package Subclass World
public x x x x
protected x x x
(default) x x
private x
package com.xceptance.trainings;

public class StaticData
{
	public static int fooStatic = 0;
	public int foo = 0;

    public void increase()
    {
        fooStatic++;
        foo++;
    }

    public void print()
    {
        System.out.println("fooStatic:" + fooStatic);
        System.out.println("foo      :" + foo);
    }

    public static void main(String[] args)
    {
        // System.out.println("fooStatic:" + fooStatic);
//        System.out.println("foo:" + foo);

        StaticData data1 = new StaticData();
        StaticData data2 = new StaticData();

        data1.print();
        data2.print();

        data1.increase();
        System.out.println("====================");

        data1.print();
        data2.print();
    }
}

Static

Giving the blueprint power

  • Blueprint learns fields and methods
  • No need to create objects
  • SHARED, dangerous when done incorrectly
  • Slightly outside OO concepts, no inheritance and such things

System.out.println

Light on the mysterious line

public static void main(String[] args)
{
    System.out.println("Hello, World");
}
public final class System {
    public final static PrintStream out = null;

    private static void initializeSystemClass() {
        setOut0(newPrintStream(
                    fdOut,
                    props.getProperty("sun.stdout.encoding")));
    }
}
public class PrintStream extends FilterOutputStream
    implements Appendable, Closeable {

    public void println(String s) {
        newLine(s);
    }
}
  • System.java is from java.lang and automatically available
  • static field out, initialized during class loading with a special method called by the JVM (not recommended for public use!)
  • PrintStream out is an object you can directly work with

PrintStream

Print what you want to

void	print(boolean b)
void	print(char c)
void	print(char[] s)
void	print(double d)
void	print(float f)
void	print(int i)
void	print(long l)
void	print(Object obj)
void	print(String s)
// A convenience method to write a formatted string to this output
// stream using the specified format string and arguments.
PrintStream	printf(Locale l, String format, Object... args)
// A convenience method to write a formatted string to this output
// stream using the specified format string and arguments.
PrintStream	printf(String format, Object... args)
void	println()
void	println(boolean x)
void	println(char x)
void	println(char[] x)
void	println(double x)
void	println(float x)
void	println(int x)
void	println(long x)
void	println(Object x)
void	println(String x)
...
  • Utility stream with many convenience methods
  • Stream is connected to something hence the data ends up somewhere (System.out, System.err, ...)
  • new PrintStream(...) works too, needs file or file names or other streams as parameter (will get back to that when talking Java I/O)

More Coding

The Basic Language Constructs

Assignments

Store something somewhere

public void show()
{
    {
        int a = 0;
        int c = a;

        int d = a = b = 3;
    }

    {
        int a = (0);
        int c = (a);

        int d = (a = (b = (3)));
    }

    {
        boolean foo = true;
        double number = 1.0;
        String s = "Meier";
        Car vw = new Car("VW");
        Car vw2 = vw;
    }
}
  • = means "result of" or "assign right to left"
  • Assign a value or result to a variable
  • Internal language handling is not exposed (memory, register, not stored at all)
  • Most right side is always evaluated first

Mathematics

Calculation done easy

public void show()
{
    int a = 1 + 3; // addition
    int b = 1 - 3; // subtraction
    int c = 1 * 3; // multiplication
    double d = 1 / 3; // division
    a++; // increment aka addition of one a = a + 1;
    a--; // decrement aka subtraction of one a = a - 1;

    int m = 1 % 3; // modulus aka remainder of division

    // What is?
    int x = 1 / 3;
    double x = 1 / 3;
}
  • This is pure mathematics
  • Same rules such as parenthesis evaluation and */ precedence over +-
  • Left to right!

More Complex Assignments

public void show()
{
    int a = 0;
    a++; // a = a + 1
    a--; // a = a - 1

    a += 2; // a = a + 2;
    a -= 2; // a = a - 2;
    a /= 2; // a = a / 2;
    a *= 2; // a = a * 2;

    int b = 1;

    // postfix operand
    a = b++; // a = b; b = b + 1;
    a = b--; // a = b; b = b - 1;

    // prefix operand
    a = ++b; // a = b = b + 1;
    a = --b; // a = b = b - 1;

    {
        // this is horribly wrong and stays unnoticed!!!!
        a =+ 2; // compiles into a = +2;
        a =- 2; // compiles into a = -2;
    }
}

Store and do something at the same time

  • Usually short hand operators to write less
  • Usage not mandatory, some are even a little dangerous
  • Some bit-wise operators exists, but bit-mess is for another day
  • Don't do fancy stuff, rather longer than shorter code, most people don't get it right except a++ and a--;

Conditions

Will be used to determine the control flow later, called Relational Operators

public void test()
{
    boolean a1 = (1 < 3);   // less than
    boolean a2 = (1 <= 3);  // less than or equals to
    boolean b1 = (1 > 3);   // larger than
    boolean b2 = (1 >= 3);  // larger than or equals to
    boolean c1  = (1 == 3); // equals to
    boolean c2  = (1 != 3); // not equals to

    boolean d  = (3 * 2 < 6); // full meaning: (( 3 * 2 ) < ( 6 ))

    String s = "Test";
    boolean z = s instanceof String; // is s of type String
}
  • Basic logical operation needed everywhere
  • Always results in a boolean
  • Hence true and false are the only possible states
  • Has a left and right side
  • instanceof special object operator

Logical Operators

Make more complex conditions

public void test()
{
    boolean a = (1 < 3) && (1 > 3); // and
    boolean d = (1 < 3) || (1 > 3); // or
    boolean c = !(1 < 3); // not
}
  • Combine conditions logically
  • AND: true when both are true, false otherwise
  • OR: true when one is true, false otherwise
  • NOT: Negates the boolean - not(false) == true

Control-Flow: Conditionals

Do something when something is or else...

IF/ELSE/ELSE IF

When you need to execute code based on a condition

public void show()
{
    if (<condition>)
    {
        // do this
        // you have to have one and only one if this
    }
    else if (<condition>)
    {
        // do this
    }
    else if (<condition>)
    {
        // you can have many else-if blocks
    }
    else
    {
        // if all of the before has not been evaluated to true,
        // do this code
        // you can have only one else
    }
}
  • if, execute the code in curly braces when the condition is true
  • else if, evaluate this condition when condition before was false
  • else, execute this code when the if-conditions(!) all evaluated to false
  • else and else-if are optional
  • Can be useful to declare empty else blocks and put a comment into it to describe why this is not needed

ELSE-IF Rewritten

Without else-if

public void show()
{
    if (i == 1)
    {
        // 1
    }
    else if (i == 2)
    {
        // 2
    }
    else if (i == 3)
    {
        // 3
    }
    else
    {
        // > 3
    }
}
public void show()
{
    if (i == 1)
    {
        // 1
    }
    else
    {
        if (i == 2)
        {
            // 2
        }
        else
        {
            if (i == 3)
            {
                // 3
            }
            else
            {
                // > 3
            }
        }
    }
}

Ternary Operator

Shorthand if-then-else, ternary means three

public void show(int a)
{
int c = 0;

if (a < 10)
{
    c = 10;
}
else
{
    c = 20;
}

// or the short version
int c = (a < 10) ? 10 : 20;
}
  • ?: can replace simple if statements when the result is an assignment
  • You can squeeze in more code, but should not, hard to read
  • Both right hand statements have to have a result and the same type that matches the left side of the assignment

Switch Statement

When if-then-else gets too long

  • When if-then-else-if gets too long
  • Limited to short, byte, char, int and String
  • Supports the wrapper around primitives: Short, Byte, Char, Integer
  • break is important otherwise we fall through
  • default is the last else basically
/**
 * Is this a workday for me?
 * 
 * @param dayOfWeek the day of the week as 1 to 7 (Mon to Sun)
 * @return true if yes, false when this is a lazy day
 */
public boolean doIhaveToWork(final int dayOfWeek)
{
    boolean result = false;
    
    switch(dayOfWeek)
    {
        case 1: result = true;
                break;
        case 2: result = true;
                break;
        case 3: result = true;
                break;
        case 4: result = true;
                break;
        case 5: result = true;
                break;
        case 6: result = false;
                break;
        case 7: result = false;
                break;
        default: break;
    }
    
    return result;
}

Switch Optimized I

Shorter code

  • Use break and default nicely
  • But makes code harder to read and maintain
/**
 * Is this a workday for me?
 * 
 * @param dayOfWeek the day of the week as 1 to 7 (Mon to Sun)
 * @return true if yes, false when this is a lazy day
 */
public boolean doIhaveToWork(final int dayOfWeek)
{
    boolean result = false;
    
    switch(dayOfWeek)
    {
        case 1: 
        case 2: 
        case 3: 
        case 4: 
        case 5: result = true;
                break;
        case 6: 
        case 7: result = false;
                break;
        default: break;
    }
    
    return result;
}

Switch Optimized II

Even shorter code

  • Cut to the bone version
  • No default, because we have result already set
/**
 * Is this a workday for me?
 * 
 * @param dayOfWeek the day of the week as 1 to 7 (Mon to Sun)
 * @return true if yes, false when this is a lazy day
 */
public boolean doIhaveToWork(final int dayOfWeek)
{
    switch(dayOfWeek)
    {
        case 6: 
        case 7: return false;
        default: return true;
    }
    
    return result;
}

Control-Flow: Loops

Repeat something until...

for-loop

Simple counting up and down

public void show(int a)
{
// for (initialization; termination; increment)
for (int i = 0; i < 10; i++)
{
    ...
}

for (int i = 0; i < 10; i = i - 3)
{
    ...
}

for (int i = 0; i < 10; i = i * 3)
{
    ...
}
}
  • Init a variable or reuse one
  • When to terminate or better how long to run
  • How to change the state of the variable
  • The loop might never start when the condition already returns false
public void show(int a)
{
    while (<condition>)
    {

    }
}
public void show(int a)
{
    int i = 0;

    while (i < 100)
    {
        i++;

        // more code here
    }
}
public String show(List<String> list)
{
    Iterator<String> iterator= list.iterator();

    StringBuilder result = new StringBuilder();
    while (iterator.hasNext() && result.size() < 25)
    {
        result.append(iterator.next());
    }

    return result.toString();
}

While-Loop

Loop until a condition is reached

  • As long as the condition is true, the loop is processed
  • If condition is false in the beginning, loop code will never be executed
  • If condition never becomes false, the loop never terminates!
public void show()
{
    do
    {
        // your code here
    }
    while (<condition>)
}
public void show()
{
    int i = 0;

    do
    {
        i++;

        // more code here
    }
    while (i < 100)
}
StringBuilder sb = new StringBuilder();

do
{
    int random = (Math.random() * 10000) + 1;
    sb.append(Math.random());
}
while (sb.size() < 5)

Do-While-Loop

Loop until a condition is reached

  • Works like a while-loop
  • But the code is at least executed once!
  • Might also never terminate
public String show()
{
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < 100; i++)
    {
        if (sb.size() < 50)
        {
            sb.append(i);
        }
        else
        {
            break;
        }
    }

    return sb.toString();
}
public void show(String s)
{
    for (int i = 0; i < s.length(); i++)
    {
        if (s.charAt(i) = ' ')
        {
            continue;
        }

        doSomethingVeryExpensive();

        // do more here...
    }
}

Loop Control

Control statements to control the loop from within.

  • break terminates a loop instantly and the code will continue to be executed after the loop
  • continue instantly starts a new loop iteration if and only if the condition still evaluates to true
  • Works for all three types of loops