Java Basics Presentation
Java Basics Presentation
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
• 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;
package mypackage;
import java.util.*;
public MyClass() {
System.out.println("This is my class");
}
}
Java Types
Primitive Size Default Wrapper
type value type
boolean - false Boolean
• 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
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
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");
}
}
• 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
// 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
// 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
• 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