byteshortintlongfloat: ~6-7 decimal digitsdouble: 15 decimal digitschar: surrounded by single quotesboolean
End the value with an "f" for floats and "d" for doubles
String(object): surrounded by double quotes
length(), toUpperCase(), toLowerCase(), indexOf(), concat() or +, see more here.
Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
A primitive type has always a value, while non-primitive types can be
null.If you add a number and a string, the result will be a string concatenation.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
or,
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
min(), max(), abs(), random() see more here.
The ArrayList class is a resizable array.
add(), get(), set(), remove(), clear(), size() Use Collections for sorting lists alphabetically or numerically.
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Collections.sort(myNumbers); // Sort myNumbers
for (int i : myNumbers) {
System.out.println(i);
}
}
}
Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as
int, you must specify an equivalent wrapper class:Integer. For other primitive types, use:Booleanforboolean,Characterforchar,Doublefordouble,Floatforfloat, etc.
The LinkedList class has all of the same methods as the ArrayList class because they both implement the List interface.
The
ArrayListclass has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.The
LinkedListstores its items in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.
addFirst(), addLast(), removeFirst(), removeLast(), getFirst(), getLast()
A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type.
put(), get(), remove(), clear(), size(), keySet(), values()
// Import the HashMap class
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called capitalCities
HashMap<String, String> capitalCities = new HashMap<String, String>();
// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.get("England");
capitalCities.remove("England");
for (String i : capitalCities.keySet()) {
System.out.println(i);
}
}
}
A HashSet is a collection of items where every item is unique.
add(), contains(), remove(), clear(), size()
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
for (String i : cars) {
System.out.println(i);
}
}
}
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.
hasNext(), next(), remove()
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
Integer i = it.next();
if(i < 10) {
it.remove();
}
}
System.out.println(numbers);
}
}
An enum is a special class, cannot be used to create objects.
enum Level {
LOW,
MEDIUM,
HIGH
}
Level myVar = Level.MEDIUM;
for (Level myVar : Level.values()) {
System.out.println(myVar);
}
To inherit from a class, use the
extendskeyword.Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma.
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
(parameter1, parameter2) -> { code block }
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach( (n) -> { System.out.println(n); } );
}
}
Use java.util.regex package to work with regular expressions. The package includes the following classes:
PatternClass - Defines a pattern (to be used in a search)MatcherClass - Used to search for the patternPatternSyntaxExceptionClass - Indicates syntax error in a regular expression pattern
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
Use try, catch, finally:
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
A package in Java is used to group related classes.
import java.util.Scanner;
import java.util.*;
