Let's Get Started with Programming
A minimal program with some activity
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
HelloWorld
) must match file name (HelloWorld.java
)
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");}}
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);
}
}
The compiler does not care, but your colleagues do.
Hello World taken apart
Group logical things together
package com.xceptance.trainings;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
com.xceptance.trainings
=
com/xceptance/trainings/
More important than code ;)
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;
}
}
Comments are source code only.
The base is a class
package com.xceptance.trainings;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
There is not right or wrong, there is only good and bad.
/**
* Classes and Interface Naming
*/
public class CalculatorImpl extends Casio implements Calculator
{
}
public class Calculator99 extends Casio2017 implements Calculator0815
{
}
/**
* 这是真的
*/
public class 你好
{
}
Runtime is not affected by length.
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) ...
}
The entry point to the world of your program
public static void main(String[] args)
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;
}
}
}
; is important
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!
}
Blocks and scope is defined by {}
if
for instance)
Determines visibility
package com.xceptance.trainings;
public class MyClass
{
private void method1()
{
}
void method2()
{
}
protected void method3()
{
}
public void method4()
{
}
}
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | x | x | x | x |
protected | x | x | x | |
(default) | x | x | ||
private | x |
We will get back to that later. Just accept it for now.
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();
}
}
Giving the blueprint power
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);
}
}
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
https://docs.oracle.com/javase/8/docs/api/java/lang/System.html
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)
...
https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html
The Basic Language Constructs
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;
}
}
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;
}
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
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
}
instanceof
special object operator
You mostly never assign the result first.
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
}
You mostly never assign the result later.
Do something when something is or else...
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
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
}
}
}
}
Else-if helps to keep code well-structured.
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
Use carefully!
When if-then-else gets too long
short, byte, char, int
and String
break
is important otherwise we fall throughdefault
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;
}
The break statement is important!
Shorter code
break
and default
nicely
/**
* 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;
}
Keep default all the time.
Even shorter code
/**
* 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;
}
Very simplified example, that would work with ifs too.
Repeat something until...
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)
{
...
}
}
Use carefully!
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();
}
Loop until a condition is reached
Only a Cray computer can calculate the infinite loop in in under two seconds.
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)
Loop until a condition is reached
Rarely used.
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...
}
}
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
Can improve runtime and code layout dramatically.