Obsah
Basics
Data types
| data type |
size |
primitive/reference |
value |
| boolean |
1 bit |
primitive |
true/false |
| byte |
1 byte |
primitive |
-128 to 127 |
| short |
2 bytes |
primitive |
-32 768 to 32 767 |
| int |
4 bytes |
primitive |
-2 bilion to 2 bilion |
| long |
8 bytes |
primitive |
-9 quintillion to 9 quintillion |
| float |
4 bytes |
primitive |
6-7 digit fractions |
| double |
8 bytes |
primitive |
15 digits fractions |
| char |
2 bytes |
primitive |
single char/letter/ascii value |
| String |
varies |
reference |
string of characters |
Wrapper classes
- provides a way to use primitive types as reference types
- reference types have methods
- can be used for collections (ArrayList etc.)
| primitive |
reference(Wrapper) |
| boolean |
Boolean |
| byte |
Byte |
| short |
Short |
| int |
Integer |
| long |
Long |
| float |
Float |
| double |
Double |
| char |
Character |
- Autoboxing → auto conversion from primitive types to wrapper classes
- Unoboxing → auto conversion from wrapper classes to primitive types
ArrayList
import java.util.ArrayList;
public class Hello{
public static void main(String args[]){
// can only use Reference types
ArrayList<String> l = new ArrayList<String>();
// add item to ArrayList
l.add("Berlin");
l.add("Paris");
l.add("Hongkong");
l.set(2,"Ohio"); // works only when already defined with add
l.remove(1); // remove at index
l.clear(); // clear like in c++
// range based for loop
for (String string : l) {
System.out.println(string);
}
}
}
2D ArrayList
import java.util.ArrayList;
public class Hello{
public static void main(String args[]){
// 2D array
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
ArrayList<String> food = new ArrayList<String>();
food.add("Pizza");
food.add("Cheese");
ArrayList<String> drink = new ArrayList<String>();
drink.add("Cola");
drink.add("Beer");
list.add(food);
list.add(drink);
System.out.println(list); // prints the whole 2D list
System.out.println(list.get(0)); // prints the items of list food
System.out.println(list.get(1).get(0)); // prints the item of list drink
}
}
Quick notes
- overloading methods works as c++
- in static methods only static methods can be called
- printf works as same as in c/c++
- final == const