SE 8
Daniel Reckerth
Content
1. Introduction
2. Structure of a Java class
3. The Java Environment: Compiler and Interpreter
4. Fundamental Building Blocks
5. Memory Allocation in Java
6. Operators and Statements in Java
7. Access Modifiers
8. Core Java APIs: Strings, Arrays
1. Introduction
• Java is a general-purpose programming language
• Follows the Object-oriented programming paradigm
• Announced in may 1995 and started as an internal corporate research by Sun
Microsystem in 1991
• Follows the WORA principle: “Write once, run anywhere”
• One of the most popular languages, especially for client-server web
applications
2. Java Class Structure
• Java is a class-based programming language
structure of a Java Class
3. The Java Environment: Compiler and Interpreter
• compiler: javac
• converts source code into bytecode
• checks all code and displays all errors
javac Hello.java
• interpreter: java
• converts bytecodes into specific OS
machine code
• reads line by line and interrupts itself for
each runtime error
java Hello students
argument
4. Java Fundamental Building Blocks
• Java classes have two primary elements:
• fields known as variables – hold the state of the program
members of the class
• methods – operate on the state
• comments: /**
* Models a student.
*
* @author Daniel Reckerth
*/
public class Student {
// the name of the student
String name;
/* Age of the
* student
*/
int age;
public String getName() {
return name
}
public void setAge(int newAge) {
age = newAge;
}
}
Main method and Packages
• Java starts execution with the main() method
• it is the entry point of a Java process
• Java places classes in packages (similar to file cabinet)
• their names are in a hierarchy like a mail
• java.lang package is automatically imported - it is redundant to import it
package mypackage;
import java.util.*;
public class Main {
public static void main(String[] args) {
Random r = new Random();
System.out.println("Hello number “ + r.nextInt(10));
}
}
Constructors
• a class is a template
• instance of a class is an object
• creating it using new : MyClass myClassName = new MyClass();
• the variable name is a place to store a reference to our object
• by default is null
• we used a constructor, which is a method to create a new object
• it always matches the name of the class
• it has no return type
public class MyClass {
public MyClass() {
System.out.println("This is my class");
}
}
Code Blocks
• code block is the code between { } – have their own scope
• they can be inside a method – run when the method is called
• they can be outside a method – called instance initializers
• they are run in the order in which they appear
public class MyClass {
private String name = "Daniel";
{ System.out.println("set a field"); } // instance initializer
public MyClass() {
System.out.println("This is my class");
}
}
Java Types
Primitive Size Default Wrapper
type value type
boolean - false Boolean
byte 8-bit 0 Byte
short 16-bit 0 Short
int 32-bit 0 Integer
long 64-bit 0L Long
float 32-bit 0.0f Float
double 64-bit 0.0d Double
char 16-bit \u0000 Character
Unicode
Variable Types and Scope
• local variables
• defined within a method, must be initialized before use
• scope local to the method or smaller to the block of code
• instance variables
• called fields
• given default value (0/false – primitives, null- objects)
• available as soon as defined and last for the entire life of the object
• class variables
• shared across multiple object
• contain keyword static before them
• given default value
• go into scope when declared, stay for the entire life of the program
5. Java Memory
• 3 main components Meta-space
• meta-space
• stack
• heap
• Garbage Collector String Pool
• automatic process by which Java
perform memory management
• works on the heap ONLY
• System.gc() – calls it but it is not
guaranteed to run (suggests only)
• finalize() – called if the GC
tries to collect the object; can run
zero or one time Stack Heap
JVM
6. Operators and Statements
• operator = special symbol which can be applied to variables, values, literals
and returns a result operands
• types: unary, binary, ternary
• unless overridden with () Java operators follow the order of operations
• if two operators have the same level of precedence left-to-right evaluation
Precedence Operators Type Associativity
15 () [] . parenthesis, array subscript, member selection left -> right
6. Operator Precedence
14 post ++ -- unary post in/decrement
pre ++ -- unary pre in/decrement
+ - ! ~ unary plus, minus, log. neg. bitwise complement right -> left
13
(type) unary type cast
12 * / % multiplication, division, modulus
11 + - addition, subtraction
<< >> >>> bitwise left, right (with sign extension) shift and right shift
10 with zero extension
< <= > >= relational operators
9 instanceof type comparison (objects only)
8 == != equality
left -> right
7 & bitwise AND
6 ^ bitwise XOR
5 | bitwise OR
4 && logical AND
3 || logical OR
2 ?: ternary
= += -= *= /= %= &= right -> left
1 ^= |= <<= >>= assignment
<<<=
Operators Examples and Numeric Promotion
• if two values have different data types => Java promotes the smaller to the
larger one
• promotion of integral to floating-point
• smaller integral types promoted firstly to int when used with a arithmetic
operator
• after all promotions the result will have the same data type as its promoted
operands
• examples:
int x = 1; short x = 5;
1) promote x to int
long y = 50L; float y = 50;
2) promote int x to float
// int x promoted to long double z = 30;
3) promote x * y to double
long z = x * y; double r = x * y / z;
Java Statements
• complete unit of execution terminated with ;
• control flow statements
• applied to single expressions or code blocks
• examples:
• if, if-then-else
• switch
• while
• do-while
• for
• advanced flow control:
• nested loops
• adding optional labels
• break and continue statements
Java Statements
if, if-then-else switch
if (<condition>) { switch(<test_variable>) {
// code case <label 1>:
} // case body 1
break; <test_variable> must be of type
… char, byte, short, int or
if (<condition>) { case <label n>: String literal
// code // case body n
} else { break;
// code default:
} // default code
}
Java Statements
while loop do-while loop
executed at least once
while (<condition>) { do {
// code // code
} } while(<condition>);
for loop
for(<initialization>; <condition>; <increment>) {
// code enhanced for loop
}
for(<datatype_instance> : <collection>) {
// code
}
Advanced Flow Control
• if statements and loops can be nested, i.e. contain other loops or statements in tem
• if-then statements, switch and loops can have optional labels
OUTER_LOOP: for(int i = 0; i < rows; i++) {
INNER_LOOP: for(int j = 0; j < cols; j++) {
System.out.println(table[i][j] + "\t");
}
}
• break transfer flow of control out to the enclosing statement
• continue causes flow to finish the execution of the current loop (applied to the nearest
inner loop)
• can be used with labels
7. Access Modifiers
• private – "Visible to myself"
• private to the class
• protected – "Visible to the family"
• can be seen by the class, all subclasses, and other classes within the same package
• public – "Visible to all"
• can be seen by all classes
• default access modifier – "Visible in the neighborhood"
• public to members of same package
• private to anyone outside the package
• called package access
8. Core Java APIs: String, Arrays
• core data structures and classes: String, StringBuilder, StringBuffer, Arrays, ArrayList,
Dates and Times
• Java has no primitive type for strings, therefore we have the String class
• a string is a sequence of characters
• it can be given the value of a String object
String name = "Daniel";
String name = new String("Daniel");
• +, += applied on a String operand means concatenation
String fullName = "Daniel" + "Reckerth"; // DanielReckerth
String s = "one" + 1; // one1
• Strings are immutable, i.e. they are not allowed to change once created
• in Java String indexes starts from 0
String Cont'd.
• important methods include:
• length() – returns the number of characters in the string
• charAt() – return the character at the specified index
• substring() – return the part of the string specified in the range
• indexOf() – returns the index of the specified character
• toLowerCase(), toUpperCase() – make characters lower, upper case (original
string does not change)
• equals(), equalsIgnoreCase() – check whether two strings contains exactly the
same characters in the same order
• startsWith(), endsWith() – provided value matches part of the string's beginning/
ending
• contains() – looks for matches in the string
• replace() – replaces the specified character with a new one
• trim() – remove whitespaces from the beginning and end of a string
• method chaining
String result = "AniMaL ".trim().toLowerCase().replace('a','A'); // "Animal"
String str = "Learning";
// length
System.out.println(str.length()); // 8
// charAt()
System.out.println(str.charAt(0)); // L
// substring()
System.out.println(str.substring(3)); // "rning"
System.out.println(str.substring(3,6)); // "ni"
// indexOf()
System.out.println(str.indexOf('a')); // 2
System.out.println(str.indexOf("ear")); // 1
System.out.println(str.indexOf('n', 6)); // 6
System.out.println(str.indexOf("ni", 4)); // -1
// toLowerCase(), toUpperCase()
System.out.println(str.toLowerCase()); // "learning"
System.out.println(str.toUpperCase()); // "LEARNING"
// equals(), equalsIgnoreCase()
System.out.println("abc".equals("ABC")); // false
System.out.println("abc".equalsIgnoreCase("ABC")); // true
// startsWith(), endsWith()
System.out.println("abc".startsWith("a")); // true
System.out.println("abc".endsWith("b")); // false
// contains()
System.out.println("abc".contains("a")); // true
System.out.println("abc".contains("B")); // false
// replace()
System.out.println("abcabc".replace('a', 'A')); // AbcAbc
System.out.println("abcabc".replace("a", "A")); // AbcAbc
// trim()
System.out.println("abc".trim()); // abc
System.out.println("\t a b c\n".trim()); // a b c
StringBuilder and StringBuffer
• provided by Java in order to create strings without storing additional String values
• they are mutable
• reuse the same StringBuilder/StringBuffer without creating additional Strings each time
• they change their own state and return a reference to themselves
• creating a StringBuilder – same goes for StringBuffer
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("learning");
StringBuilder sb3 = new StringBuilder(10);
• they have most of the methods presented before on Strings
• in addition we have:
• append() – add the parameter to the sequence and returns a reference to the current one
• insert() – adds character to the sequence at the requested index and returns a reference to the
current Builder/Buffer
• delete(), deleteCharAt() – remove character from the sequence
• reverse() – reverses the characters in the sequence
• toString() – convert StringBuilder/StringBuffer into a String
StringBuilder and StringBuffer
// append
StringBuilder sb = new StringBuilder();
sb.append("hello").append(" world").append(", ").append(2021); // "hello world, 2021"
// insert
sb.insert(sb.length, "!"); // "hello world, 2021!"
// delete
sb.delete(0,6); // "world, 2021"
sb.deleteCharAt(sb.length – 1); // "world, 2021"
// reverse
sb.reverse(); // "1202 ,dlrow"
// toString
String s = sb.toString();
StringBuilder vs StringBuffer
StringBuilder StringBuffer
not thread safe, i.e. two threads can thread safe, i.e. cannot be accessed by
access its methods at the same time multiple threads simultaneously
non-synchronized methods synchronized-methods
faster performance slower performance
Java Arrays
• indexed collection of data of the same type
• in Java it is a reference data type
• use new operator to allocate the memory
• use indexed expression to refer to individual values
• Java uses zero-based indexing
• an array has a public constant length, i.e. we do not use method call
• fixed-size array declaration (Problems?)
• we can have arrays of primitives or arrays of objects
• however, an array of characters is not a String, but it can be converted
char[] arr = {'A', 'B', 'C'};
String str = a; // Illegal
String str = new String(a); // Legal
String str = new String(a,0,2); // Legal – uses subrange -> "AB"
Java Arrays
• creating an array: int[] data int [] data int data[] int data [] – all valid
int[] data = new int[3]; // array of ints of size 3
data[0] = 56;
data[1] = 272;
String[] names = {"Vlad", "Alexandra", "Tudor"}; // allocates space for a
reference to where the objects are stored
Java Arrays
• sorting an array – import java.util.Arrays
int[] numbers = {7,29,1,3};
String[] strings = {"10", "7", "100"};
Arrays.sort(numbers); • searching – if already sorted
Arrays.sort(strings);
// 1, 3, 7, 29 • found – return index
for (int number : numbers) {
System.out.print(number + " ");
• not found – negative index, one smaller
} than the negative of the index, where
inserted it will keep the order
// 10 100 7 – alphabetic order int[] numbers = {1, 3, 7, 29};
for (String str : strings) { int res = Arrays.binarySearch(numbers,7); // 2
System.out.print(str + " "); res = Arrays.binarySearch(numbers, 1); // 0
} res = Arrays.binarySearch(numbers, 2); // -2
Java Arrays
• multidimensional arrays – 2, 3 or more
• declaration using pairs of []
• examples
char[][] board = new char[3][3]; int[][] sizes = {{1,4}, {3}, {9,8,7}};
char[0][0] = 'O'; System.out.println(int[0][1]); // 4
char[0][1] = 'X';
char[1][1] = 'X';
ArrayList
• fixed-size arrays problems:
• not enough capacity for the task
• wasted space
• not knowing how many elements will be when creating it
• ArrayList is similar to a StringBuilder
• it can change its size at runtime as needed
• creating it:
ArrayList arrList1 = new ArrayList();
ArrayList arrList2 = new ArrayList(10);
ArrayList arrList3 = new ArrayList(arrList2);
ArrayList<String> arrList4 = newArrayList<>(); // using generics allowing type specification
List<String> arrList5 = new ArrayList<>(); // ArrayList implements the List interface
ArrayList
• main methods
• add() – inserts a new value in the array list
• remove() – removes first matching value in the array list or the element specified at an index
• set() – change one of the elements of the list without changing the size
• isEmpty(), size() –returns true if the array list is empty, otherwise false; returns the size
• clear() –discard all elements of the array list
• contains() – checks whether a certain value is in the array list
• equals() – compare two lists to see if they have the same elements in the same order
ArrayList
// add
ArrayList list = new ArrayList();
list.add("Java"); // [Java]
list.add("Daniel"); // [Java, Daniel]
list.add(Boolean.TRUE); // [Java, Daniel, TRUE] – allowed because we have not specified a type
list.add(1, "Adelin"); // [Java, Adelin, Daniel, TRUE]
list.add(2, "Andrei'); // [Java, Adelin, Andrei, Daniel, TRUE]
// remove
System.out.println(list.remove(4)); // TRUE [Java, Adelin, Andrei, Daniel]
System.out.println(list.remove("Daniel")); // Daniel [Java, Adelin, Andrei]
// set
list.set(0, "Victor"); // [Victor, Adelin, Andrei]
// isEmtpy, size()
System.out.println(list.isEmpty()); // false
System.out.println(list.size()); // 3
// contains
System.out.println(list.contains("Andrei")); // true