[Go to site: main page, start]

0% found this document useful (0 votes)
20 views2 pages

Java Arrays and Collections Cheat Sheet

The document provides examples of various Java programming concepts including arrays, loops, conditionals, strings, exceptions, and keywords. Arrays examples demonstrate declaring and initializing arrays of different types as well as accessing elements. Loop examples cover for, while, do-while, and for-each loops. Conditional examples include if/else, ternary operator, and switch statements. String examples show common string methods. Exceptions demonstrate try/catch blocks. Keywords defined include abstract, final, interface, and static.

Uploaded by

Alwi Adam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Java Arrays and Collections Cheat Sheet

The document provides examples of various Java programming concepts including arrays, loops, conditionals, strings, exceptions, and keywords. Arrays examples demonstrate declaring and initializing arrays of different types as well as accessing elements. Loop examples cover for, while, do-while, and for-each loops. Conditional examples include if/else, ternary operator, and switch statements. String examples show common string methods. Exceptions demonstrate try/catch blocks. Keywords defined include abstract, final, interface, and static.

Uploaded by

Alwi Adam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arrays Break / Continue

Animal [] zoo = new Animal [4]; for (int i = 0; i < 10; i++) {
zoo [0] = new Tiger(); if (i == 4) {
zoo [1] = new Giraffe(); continue; //This skips the value of 4
… }
if (i == 6) {
String [] cars = {"Volvo", "BMW", "Ford", "Mazda"}; break; //This jumps out of the for loop
[Link]([Link]); //Outputs 4 }
}
int [][] myNumbers = {{1, 2, 3, 4}, {4, 5, 6}};
int x = myNumbers [1][2];
[Link](x); //Outputs 6
If...Else
[Link](cars);
[Link]([Link](cars)); int time = 22;
//[BMW, Ford, Mazda, Volvo] if (time < 10) {
[Link]("Good morning!");
SORTING OBJECTS WITH MULTIPLE PARAMETERS: } else if (time < 20) {
NATURAL SORTING (Created within class) [Link]("Good day!");
public class Person implements Comparable<Person>{… } else {
@Override [Link]("Good evening!");
public int compareTo(Person o) { }
return [Link]([Link], [Link]); //Outputs "Good evening!"
} ----> Use wrapperclass
variable = (condition) ? expressionTrue : expressionFalse;
[Link](listOfPeople); / [Link](...);
int tine = 20;
ALTERNATIVE SORTING (Created in sepparate class) String result = (time < 18) ? "Good day!" : "Good evening!";
public class SortOnName implements Comparator<Person>{ [Link](result);
@Override //Outputs "Good evening!"
public int compare(Person o1, Person o2) {
return [Link]().compareTo([Link]());
}
Switch...Case
[Link](listOfPeople, new SortOnName());
int day = 4;
switch (day) {
case 1:
Arraylist [Link]("Monday");
break;
import [Link]; case 2:
import [Link]; [Link]("Tuesday");
break;
public class Main { case 3:
public static void main(String[] args) { [Link]("Wednessday");
break;
ArrayList<String> cars = new ArrayList<String>(); case 4:
[Link]("Volvo"); [Link]("Thursday");
[Link]("BMW"); break;
[Link]("Ford"); case 5:
[Link]("Mazda"); [Link]("Other day");
[Link](cars); break;
} }
}

[Link](0); //Acces an item


[Link](0, “Opel”); //Change an item While loop
[Link](0); //Remove an item
[Link](); //Clear full list int i = 0;
[Link](); //Find out number of ellements while (i < 5) {
[Link](i);
[Link](cars); // Sort cars i++;
}
for (String i : cars) {
[Link](i);
}
Do - While loop

int i = 0;
Converting Array to ArrayList do {
[Link](i);
import [Link]; i++
}
String [] names = {"John", "Jack", "Jill", "Jane"}; while (i < 5);

List<String> list = [Link](names);

For loop

Math for (int i = 0; i < 5; i++) {


[Link](i);
[Link](); //Random nr between 0.0(excl) and 1.0 (excl) }

int randomNum = (int)([Link]() * 101); // 0 to 100

[Link](64); //Returns square root For - Each loop

a >= b //Greater than or equal to for (type variableName : arrayName) {


a == b //Equal to // code to be excecuted
a != b //Not equal to }

int nr ++; //nr + 1 String [] cars = {"Volvo", "BMW", "Ford"};


int nr += 5; //nr + 5 for (String i : cars) {
[Link](i);
}

Randomize list
Itterating
import [Link];
Iterator<String> iter = [Link]();
ArrayList<String> mylist = new ArrayList<String>();
[Link]("One"); while ([Link]()) {
[Link]("Two"); [Link]([Link]().toString());
[Link]("Three"); }

[Link](myList); //[Two, One; Three]


String methods Keywords

String name1 = "cheatsheet"; ABSTRACT:


String name2 = "exam"; public abstract class ParentClass { …
//Blocks creating object ParentClass
[Link](); //10 ----> Required use of ChildClasses
[Link](name1); //examcheatsheet FINAL:
[Link]("cheatsheet"); //true //Attribute Once value is obtained, it can't be changed
[Link](name2); //false private final int a = 4;
[Link]('e'); //2 //Methods Cannot be overriden by subclasses
[Link](0); //'c' public final void doSomething() {…}
[Link](); //Class Cannot be used for Childclasses (no extends)
char [] test = [Link](); public final class LockedClass { …
[Link]();
[Link](int 1, int 2, String); INTERFACE:
//Change chars from pos1 to pos2 by string public interface dontForget { …
void method1 ();
}
//NO attribute
Exceptions //NO constructors
//ONLY methods without body
try { //Uses implements (NOT extends)
// Block of code to try
} STATIC:
catch (Exception e) { private static long counter;
// Block of code to handle errors //Fixed value for this class AND all subclasses
ex: [Link]([Link]());
} SUPER:
finally { super() //Calls default constructor
try { super(Parameter...) //Calls matching constructor
// Block of code to try !Must be first line in constructor!
}
catch (Ecxeption o) {
// Block of code to handle errors
} Stacks

TO CREATE SPECIFIC EXCEPTIONCLASS: import [Link];

public class MijnException extends Exception{ Stack <String> games = new Stack <String>();
public MijnException (){ [Link]("Call of Duty");
super("DezeTekstAlsErrorBvb"); [Link]("Guitar hero");
} [Link]("Dragonball Z");
}
bottom middle top
THROW THE EXCEPTION UP: //[ Call of Duty, Guitar Hero, Dragonball Z ]

public boolean check (Persoon x) throws MijnException{ [Link](); //Takes (removes) upper from list
if ([Link]().equals([Link]())){ [Link](); //Shows upper from list
return true; [Link](""); //Boolean
}else { [Link](0); //Use according to index
throw new MijnException();
}
}
Queue

import [Link]
Type casting
Queue <String> bbqLine = new LinkedList<String>();
Widening Casting (automatically) - converting a smaller type to [Link]("Jackson");
a larger type size [Link]("Jason");
byte -> short -> char -> int -> long -> float -> double [Link]("Johnson");

int myInt = 9; //[ Jackson, Jason, Johnson ]


double myDouble = myInt; //Automatic casting: int to double
[Link](); //Takes (removes) first
Narrowing Casting (manually) - converting a larger type to a [Link](); //Shows first
smaller size type
double -> float -> long -> int -> char -> short -> byte

double myDouble = 9.78; Collections


int myInt = (int) myDouble; //Manual casting: double to int
List
ArrayList //List in order of added elements
LinkedList //List of linked lists
Upcasting / downcasting
Set --------> Collection of unique ellements
//UPcasting: HashSet //Unsorted
ParentClass name1 = new ChildClass(Parameters); TreeSet //Sorted !elements use Comparable
interface
Animal name1 = new Cat("Garfield");
[Link](); //Outputs "miauw" Map --------> Collection of unique-Key,all-Value
//Can only acces methods defined in Parent class HashMap //Unsorted
and override-methods in Child class TreeMap //Sorted by key !key class implemented
with Comparable
//DOWNcasting: only works on upcasted objects
ChildClass name2 = (ChildClass) name1;

Cat name2 = (Cat) name1;


[Link](); //outputs "miauw"
//Can acces all methods defined in Child class
AND all methods in Parent class

---> Practical use to avoid errors:


if (name1 instanceof ChildClass) {
ChildClass name2 = (ChildClass) name1;
[Link]();
[Link]();
}

Public - Default - Protected – Private

public Visible for all


default Visible only in package
protected Visible in class- and subclasses
private Visible only in class

Common questions

Powered by AI

ArrayList and LinkedList in Java are both implementations of the List interface but have different performance characteristics. ArrayList is backed by a dynamic array, making it better for frequent retrieval operations and faster when accessing elements by index. LinkedList, however, is a doubly linked list, which makes insertion and deletion of elements faster compared to ArrayList, as these operations only involve adjusting the pointers rather than shifting elements. The choice between them depends on use cases: ArrayList for faster iteration and random access, LinkedList for frequently adding/removing elements .

Constructors in Java can be no-args (without parameters), parameterized (with parameters), or default. A no-args constructor is used to initialize default values, which is critical in frameworks like serialization and Hibernate. Parameterized constructors allow different initializations by providing different sets of input. The default constructor, if not explicitly defined, is provided by Java if no other constructor is present. Having explicit constructors helps in clear initialization strategies and the 'super' keyword is often used to leverage parent class constructor functionalities .

Upcasting in Java involves casting an object to a superclass reference and is implicit. It allows accessing only the superclass methods, including overridden methods in the subclass. Downcasting is casting back to a subclass and is explicit, often requiring a check using 'instanceof' to avoid ClassCastException. Upcasting is useful for polymorphism where a parent reference can point to child objects, while downcasting is necessary when specific child class method access is needed. Care must be taken to ensure the object is actually an instance of the subclass when downcasting .

Stacks and Queues are fundamental data structures in Java. A Stack operates on a last-in, first-out (LIFO) principle, ideal for scenarios requiring reverse order processing like function call management. A typical use is the browser back button implementation, where recent pages are popped off. A Queue, on the other hand, operates on a first-in, first-out (FIFO) principle, suitable for scheduling or buffering scenarios like print queue management, where tasks are processed in the order of arrival .

The 'finally' block in Java is used to execute important code such as closing resources or clean-up code, regardless of whether an exception is thrown or not. It ensures that the code within runs after the execution of a 'try' block and any matching 'catch' block, if present. Unlike 'catch', it cannot catch exceptions; it's primarily for resource management .

Sorting complex objects in Java involves implementing the interface Comparable for natural ordering, where you can override the compareTo method to specify the sorting logic based on properties like weight. For alternative ordering, you can use the Comparator interface, where you specify the ordering logic in a separate class. Arrays.sort() can be used with either Comparable or Comparator to sort the array or collection .

The 'Comparable' interface in Java provides a single method, compareTo, which defines the natural ordering of objects that implement it. This is typically used directly within the class. For instance, a 'Person' class could implement Comparable based on weight. In contrast, 'Comparator' allows for defining multiple sort orders by implementing its compare method in separate classes. For example, sorting people based on name can be done using a Comparator implemented in a class named SortOnName. Comparable is used for one primary natural order, while Comparator is flexible for alternate ordering criteria .

In Java, the 'final' keyword is used to denote constant behavior. When applied to variables, it makes them constant, so their value can only be assigned once. Applied to methods, it prevents overriding in subclasses, ensuring the method's behavior stays unchanged. When applied to classes, it means the class cannot be subclassed, which is crucial for immutability and security purposes. This keyword is used to exert control over inheritance and state mutation .

Type casting in Java is a way to convert a variable of one data type into another. Widening casting is automatic, converting a smaller type to a larger type, such as int to double. Example: int myInt = 9; double myDouble = myInt. Narrowing casting requires explicit conversion, changing a larger type to a smaller type, such as double to int. Example: double myDouble = 9.78; int myInt = (int) myDouble .

In Java, 'public' means the member is accessible from any other class. 'Protected' allows access within the same package and by subclasses. 'Default', also known as package-private, means the member is only accessible within its own package. 'Private' restricts access to within the defining class itself. These modifiers control the visibility and encapsulation of class members, playing a crucial role in data hiding and object-oriented design .

You might also like