Java Fundamentals
Java Fundamentals
Agenda
1. History of Java
2. Few words about Java
3. Our first application – „Hello, World!”
4. Data types and variables
5. Operators and casts
6. Strings
7. Control Flow
8. Loops
9. Arrays
10. Object-oriented programming
11. Varargs
12. Date, time
13. Regular expressions
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project (initially
called „Oak”) in 1991.
• The small team of sun engineers called Green Team.
• Sun changed the name of the Oak language to Java (from Java coffee), after a trademark
dispute from Oak Technology.
• In 1995 Sun Microsystems released the first public implementation as JDK Alpha and Beta. It
promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular
platforms
• In 1996 At the first-ever JavaOne developer conference, more than 6000 attendees gather to
learn more about Java technology. Sun licenses java to operating systems vendors, including
Microsoft, Apple, IBM, and others.
• JDK 1.1 was released in 1997. It includes JavaBeans API and Java Database Connectivity (JDBC).
• In 1999 HotSpot 1.0 was released and became the default Sun JVM in Java1.3.
• 2017 brought JDK 9 with jshell and reactive streams on board.
4
Basic assumptions of language
1. Architecture neutral 7. Object-Oriented
2. Distributed 8. Platform independent
3. Dynamic 9. Portable
4. High Performance 10. Robust
5. Interpreted 11. Secured
6. Multithreaded 12. Simple
5
Java Environment
• JDK (Java Development Kit) – the software for programmers
who want to write Java programs
• JRE (Java Runtime Environment) – the software for consumers
who want to run Java programs
• IDE (Integrated Development Environment) – a software
application which enables users to more easily write
and debug Java programs
6
First application
Hello, World!
7
Hello, World!
$ javac Application.java
$ java Application
Hello, World!
1. Change default text, that is printed on the console. E.g. „Hello, Mike!”.
Hello, Mike!
2. Print the same text twice.
Hello, World!
Hello, World!
3. Print different text in multiple lines.
Hello, World!
It’s a great day, to learn something new.
4. *Split line in the middle – use only one System.out.println method.
Hello,
World!
10
Data types
• Java is strongly typed language
• Every variable must have a declared type. There are eight primitive
types:
• four are integer types: byte, short, int, long
• two are floating-point number types: float, double
• one is character type char for individual characters: char
• one is a boolean type for truth values: boolean
• 56 – int literal
• 523342.5432 – double literal
• 'g' – char literal
• true – boolean literal
13
Variables
• A variable is a storage location in a computer program.
• Each variable has a name and holds a value.
• In Java, every variable has a type.
• Good practice – use a short, descriptive, meaningful variable name!
• There are four types of variables in java: block, local, instance, static.
Declaration
int width;
boolean done;
double factor;
• A variable name must begin with a letter and must be a sequence of letters or digits.
• A letter is defined as 'A'–'Z', 'a'–'z', '_', '$', or any Unicode character that denotes a letter
in a language.
• Similarly, digits are '0'–'9' and any Unicode characters that denote a digit in a language.
• The first letter should be lowercase, and then normal CamelCase rules should be used.
• All characters in the name of a variable are significant and case is also significant.
1. Define (declare and initialize) two variables: one of type „int” and second of type
„double”. Print theirs values.
Output:
19
187.2342
2. Define variable of type int. What is a maximum and minimum value, that you are able
to store within that variable?
3. Do the same as above for other numeric types (long, double, byte..). Check results.
4. Define the int type variable with maximum value. Add 1 to it. What do you think will
happen?
1. Create two variables of type int with initial values of 6 and 11.
Print sum of those variables.
2. Read any double literal from the console. Print that value rounded to the second
decimal place.
Input: 3.23523
Output: 3.23
3. *Print values: 192, 168, 1, 10 in HEX format XX:XX:XX:XX.
Use System.out.printf() method.
Input: 192, 168, 1, 10
Output: „C0:A8:01:0A”
20
Operators
24
Casts
26
Strings
Definition
String a = "abc";
String b = new String("abc");
Equality
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
Concatenation
String h = "Hello";
String w = "World!";
String text = h + ", " + w;
1. Create variable of type String. Initialize it with value „Lorem ipsum dolor sit amet, consectetur adipiscing
elit”.
a) Convert it to lower case.
b) Convert it to upper case.
c) Replace „o” with „z”.
d) Check if your variable ends with „elit”.
2. Write in a comment on each line what result you expect.
Launch it and verify the results.
String a = "abc";
String b = "abc";
String c = new String("abc");
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(b == c);
System.out.println(b.equals(c));
32
If statement
• The if statement is commonly referred to as decision statements
• Rules for using else and else if:
• You can have zero or one else for a given if, and it must come
after any else ifs.
• You can have zero to many else ifs for a given if and they must
come before the (optional) else.
• Once an else if succeeds, none of the remaining else ifs nor the
else will be tested.
if (booleanExpression) {
// statement or block of code
}
if (booleanExpression) {
// statement or block of code
} else {
// statement or block of code
}
if (booleanExpression) {
// statement or block of code
} else if (booleanExpression) {
// statement or block of code
...
} else
//
}
Example
if (points >= 100) {
System.out.println("You win!");
}
1. Modify the sample application so that the retrieved number (age) comes
from the console. Verify the application for each case (number smaller, equal to or
greater than …).
2. Pick from the console a value from 0 to 5. On the basis of the obtained value, display
any sign. For example, for number 0, display "*", for 1 display "$" (or any other).
3. * As above, but instead of values, operate on strings.
E.g. for the word "star", display "*".
Example
switch (direction) {
case 'n':
System.out.println("You are going North!");
break;
case 's':
System.out.println("You are going South!");
break;
case 'e':
System.out.println("You are going East!");
break;
case 'w':
System.out.println("You are going West!");
break;
default:
System.out.println("Bad direction!");
}
• A switch's expression must evaluate to a char, byte, short, int, an enum, and a String.
• You won't be able to compile if you use types of long, float, and double.
• A case constant must evaluate to the same type that the switch expression can use.
• A case constant must be a compile-time constant!
• The default keyword should be used in a switch statement if you want to run some code
when none of the case values match the conditional value.
41
Loops
Example
int x = 3;
while (x > 1) {
System.out.println(x);
x--;
}
while (true) {
System.out.println("Endless loop...");
}
Every exercise below should be done using while loop. Always add System.out.println(„…”)
inside the loop, to check, if it works as expected.
1. Print your name 5 times.
2. Create while loop that will never execute.
3. Create while loop that will print the same value, to the console, as long, as application
will be active.
4. Within a loop read text from console and print it back (simple „echo”).
5. Within a loop read text from console and print it backwards.
do {
// statement or block of code
} while (expression);
Example
do {
System.out.println("Greetings from do while loop!");
} while (false);
do {
System.out.println("Endless loop...");
} while (true);
Every exercise below should be done using do while loop. Always add
System.out.println(„…”) inside the loop, to check, if it works as expected.
1. Print your name 5 times.
2. Create do-while loop that will execute only once.
3. Create do-while loop that will print the same value, to the console, as long, as
application will be active.
4. Within a loop read text from console and print it back (simple „echo”).
Example
for (int x = 0; x < 10; x++) {
System.out.println("x is " + x);
}
for ( ; ; ) {
System.out.println("Endless loop...");
}
Every exercise below should be done using for loop. Always add System.out.println(„…”) inside the loop, to
check, if it works as expected.
1. Print your name 5 times.
2. The same as above, but your application should also print the actual value of the index.
Output:
Mike: 0
Mike: 1
..
Mike: 4
3. The same as above, but index should be printed from the biggest value (5 included) to the smallest one.
4. *Calculate sum of index value from 10 to 30, using for loop.
5. *Create nested for loop. Print actual values of the iterators.
E.g.:
i=5 : j=0
i=5 : j=1
i=5 : j=2
…
Example
for (Animal a: animals) {
System.out.println(a);
}
Choose the best loop for every task. Always add System.out.println(„…”) inside the loop, to check, if
it works as expected.
1. Do simple „echo” application. Your application should work as long, as you won’t write „quit”.
2. The same as above, but if you’ll write „continue” – your application should go back to the
beginning of your loop, without printing back your text.
3. *Draw rectangle from stars
Use nested for loops – parent loops iterator should be called „row”, child one – „column”.
Output:
****
****
****
4. **Draw rectangle empty inside (only edges).
56
Arrays
• Arrays are the fundamental mechanism in Java for collecting multiple values.
• Arrays can hold primitives or objects, but the array itself is always an object.
• You access each individual value through an integer index.
• Arrays are indexed beginning with zero.
• An ArrayIndexOutOfBoundsException occurs if you use a bad
index value.
• Arrays have a length attribute whose value is the number of array elements.
Example
dataType[] array; // recommended dataType []array;
dataType []array;
dataType array[];
int[] arrayOfInts;
String[] arrayOfStrings;
Example
dataType[] array = new dataType[size]; // recommended
dataType []array = new dataType[size];
dataType array[] = new dataType[size];
Example
declaration, instantiation and initialization
dataType[] array = new dataType[]{el1, el2, ... , eln};
dataType[] array = {el1, el2, ... , eln};
Example
accessing
dataType[] array = new dataType[]{el1, el2, ... , eln};
dataType[] array = {el1, el2, ... , eln};
Example
accessing
int[] arrayOfInts = {10, 15, 20, 25, 30};
System.out.println(arrayOfInts[0]); // prints 10
System.out.println(arrayOfInts[2]); // prints 20
System.out.println(arrayOfInts[4]); // prints 30
// prints 10 15 20 25 30
for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + " ");
}
// prints 10 15 20 25 30
for(int i : arrayOfInts) {
System.out.print(i + " ");
}
© 2019 Software Development Academy All Rights Reserved 62
Exercises – arrays
1. Create int array with the specified size. Fill it with different values. Print all values to the
console using enhanced for loop.
2. The same as above, but array size should come from user.
3. The same as above, but values should also come from user.
4. Print sum of all of the values from your array.
5. *Create a multiplication table. Your application should write all values to the
multidimentional array at first and then print its values.
64
Class
Example
class Bicycle {
// class body
}
69
Access modifiers
There are four access controls (levels of access) but only three
access modifiers:
• public - visible to the world
• protected - visible to the package and all subclasses
• default - visible to the package
• private - visible to the class only
Example
public class Bicycle {
Example
Bicycle bike = new Bicycle(75, 2, 20);
1. Modifier – it defines the access type of the method and it is optional to use.
2. Return type − method may return a value.
3. Method name.
4. Parameter list in parenthesis – it is the type, order and number of parameters
of a method.
5. Method body – defines what the method does with the statements.
Example
public int sum(int a, int b) {
// return a + b;
}
void draw(String s) {
// perform some draw functions
}
Example
public class Bicycle {
Example
Bicycle bike = new Bicycle(75, 2, 20);
bike.getCadence(); // should return 75
System.out.println(bike.getCadence()); // should print 75
Example
package vehicle;
package ro.sdacademy.animals.mammals;
If you want to use a class from a package, you can refer to it by its
full name (package name plus class name). Classes from java.lang
package are imported automatically.
For example, java.util.Scanner refers to the Scanner class in the
java.util package:
java.util.Scanner in = new java.util.Scanner(System.in);
Example
You can import a name with an import statement:
import java.util.Scanner;
88
Static fields and methods
Example
public class Bicycle {
Example
Example
public class Bicycle {
Example
Example
97
Varargs
Example
System.out.println(sum(1, 2, 3, 4)); // 10
System.out.println(sum(1)); // 1
System.out.println(sum()); // 0
100
Date, time
There are two basic ways to represent time:
• represents time in human terms/human time, such as year,
month, day, hour, minute and second,
• machine time, measures time continuously along a timeline
from an origin, called the epoch, in nanosecond resolution.
Some classes in the Date-Time API are intended to represent
machine time, and others are more suited to representing
human time.
Example
Date now = new Date();
// or
long millis = System.currentTimeMillis();
Date now = new Date(millis);
System.out.println(now); // Wed Mar 13 21:38:09 CET 2019
Example
105
Regular expressions
• A regular expression defines a search pattern for strings.
• The search pattern can be anything from a simple character, a
fixed string or a complex expression containing special
characters describing the pattern.
• The pattern defined by the regex may match one or several
times or not at all for a given string.
• Regular expressions can be used to search, edit
and manipulate text.
Is a compiled representation of
a regular expression.
Example
System.out.println(Pattern.matches(".s", "as")); // true
System.out.println(Pattern.matches(".t", "dt")); // true
System.out.println(Pattern.matches(".d", "odt")); // false
System.out.println(Pattern.matches(".d", "oodt")); // false
System.out.println(Pattern.matches("..t", "odt")); // true
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
System.out.println(m.matches()); // true
Open www.regex101.com site. Supply „Test String” with text defined below (or generate it
randomly by yourself here):
Fill Regular Expression to catch every single data into different group (e.g. group(1) should
consist of name, group(2) – surname, group(3) phone number, etc.). Use Quick Reference
to find out how to catch individual chars.