Java Masterclass CodeWithMosh
Java Masterclass CodeWithMosh
Primitive Types
- byte, short, int, long, float, double, char, boolean
- used for storing simle values
- copied by their value, and these values are independent of each other
Reference Types
- classes eg Array, Date, Point, String
- copied by their references
- used for storing complex objects
==
Strings
==
- immutable // anything that modifies a String returns a new String
eg String name = "Erron";
System.out.println(name.replace("o", "")); // Errn
System.out.println(name); // Erron
==
Escape Sequences
==
use Backslash (\) to use special characters
String message = "Hello \"Erron\""; // Hello "Erron"
==
Arrays
==
int[] numbers = new int[2];
number[0] = 1;
number[1] = 2;
System.out.println(numbers.toString());
==
Math
==
Math.round(1.1F) // 1
Math.ceil(1.1) // 2
Math.floor(1.1) // 1
Math.max(1, 2) // 2
Math.min(1, 2) // 1
Math.random() // any number from 0 - 1
Math.random() * 100 // any number from 0 - 100 with decimal value
Math.round(Math.random() * 100) // any number from 0 - 100 without decimal value
==
NumberFormat currency = NumberFormat.getCurrencyInstance();
String result = currency.format(1234.567) // $1,234.57
NumberFormat.getPercetInstance().format(0.1) // 10%
==
Reading Input
==
Scanner scanner = new Scanner(System.in);
System.out.println("Enter age: ");
byte age = scanner.nextByte(); // eg 12
System.out.println("Age: " + age); // Age: 12
==
String[] fruits = {"Apple", "Mango", "Banana"}
for(String fruit : fruits) {
System.out.print(fruit);
}
==