0% found this document useful (0 votes)
43 views

Java Cheatsheet

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Java Cheatsheet

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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
System.out.println(cars.length); //Outputs 4 }
}
int [][] myNumbers = {{1, 2, 3, 4}, {4, 5, 6}};
int x = myNumbers [1][2];
System.out.println(x); //Outputs 6
If...Else
Arrays.sort(cars);
System.out.println(Arrays.toString(cars)); int time = 22;
//[BMW, Ford, Mazda, Volvo] if (time < 10) {
System.out.println("Good morning!");
SORTING OBJECTS WITH MULTIPLE PARAMETERS: } else if (time < 20) {
NATURAL SORTING (Created within class) System.out.println("Good day!");
public class Person implements Comparable<Person>{… } else {
@Override System.out.println("Good evening!");
public int compareTo(Person o) { }
return Double.compare(this.weight, o2.weight); //Outputs "Good evening!"
} ----> Use wrapperclass
variable = (condition) ? expressionTrue : expressionFalse;
Arrays.sort(listOfPeople); / Collections.sort(...);
int tine = 20;
ALTERNATIVE SORTING (Created in sepparate class) String result = (time < 18) ? "Good day!" : "Good evening!";
public class SortOnName implements Comparator<Person>{ System.out.println(result);
@Override //Outputs "Good evening!"
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
Switch...Case
Arrays.sort(listOfPeople, new SortOnName());
int day = 4;
switch (day) {
case 1:
Arraylist System.out.println("Monday");
break;
import java.util.ArrayList; case 2:
import java.util.Collections; System.out.println("Tuesday");
break;
public class Main { case 3:
public static void main(String[] args) { System.out.println("Wednessday");
break;
ArrayList<String> cars = new ArrayList<String>(); case 4:
cars.add("Volvo"); System.out.println("Thursday");
cars.add("BMW"); break;
cars.add("Ford"); case 5:
cars.add("Mazda"); System.out.println("Other day");
System.out.println(cars); break;
} }
}

cars.get(0); //Acces an item


cars.set(0, “Opel”); //Change an item While loop
cars.remove(0); //Remove an item
cars.clear(); //Clear full list int i = 0;
cars.size(); //Find out number of ellements while (i < 5) {
System.out.println(i);
Collections.sort(cars); // Sort cars i++;
}
for (String i : cars) {
System.out.println(i);
}
Do - While loop

int i = 0;
Converting Array to ArrayList do {
System.out.println(i);
import java.util.Arrays; i++
}
String [] names = {"John", "Jack", "Jill", "Jane"}; while (i < 5);

List<String> list = Arrays.asList(names);

For loop

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


System.out.println(i);
Math.random(); //Random nr between 0.0(excl) and 1.0 (excl) }

int randomNum = (int)(Math.random() * 101); // 0 to 100

Math.sqrt(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) {
System.out.println(i);
}

Randomize list
Itterating
import java.util.Collections;
Iterator<String> iter = naamArrayList.iterator();
ArrayList<String> mylist = new ArrayList<String>();
myList.add("One"); while (iter.hasNext()) {
mylist.add("Two"); System.out.println(iter.next().toString());
myList.add("Three"); }

Collections.shuffle(myList); //[Two, One; Three]


String methods Keywords

String name1 = "cheatsheet"; ABSTRACT:


String name2 = "exam"; public abstract class ParentClass { …
//Blocks creating object ParentClass
name1.length(); //10 ----> Required use of ChildClasses
name2.concat(name1); //examcheatsheet FINAL:
name1.equals("cheatsheet"); //true //Attribute Once value is obtained, it can't be changed
name1.equalsIgnoreCase(name2); //false private final int a = 4;
name1.indexOf('e'); //2 //Methods Cannot be overriden by subclasses
name1.charAt(0); //'c' public final void doSomething() {…}
name1.toCharArray(); //Class Cannot be used for Childclasses (no extends)
char [] test = name1.toCharArray(); public final class LockedClass { …
test.toString();
name1.replace(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: System.out.println(e.getMessage());
} 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 java.util.Stack;

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

public boolean check (Persoon x) throws MijnException{ games.pop(); //Takes (removes) upper from list
if (x.getAchternaam().equals(y.getAchternaam())){ games.peek(); //Shows upper from list
return true; games.contains(""); //Boolean
}else { games.get(0); //Use according to index
throw new MijnException();
}
}
Queue

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

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


double myDouble = myInt; //Automatic casting: int to double
bbqLine.poll(); //Takes (removes) first
Narrowing Casting (manually) - converting a larger type to a bbqLine.peek(); //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");
name1.makeSound(); //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;


name2.makeSound(); //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;
name2.makeSound();
name2.uniqueChildClassMethod();
}

Public - Default - Protected – Private

public Visible for all


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

You might also like