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

KT Byte Java Cheat Sheet

The document provides a summary of key Java language concepts including: 1) Primitive data types, operators, and casting methods. It describes common types like int, float, boolean, and char along with assignment, arithmetic, comparison, and bitwise operators. 2) Control flow structures such as if/else statements, while, for, and do-while loops, and how to break or continue execution. 3) Class/object concepts including instantiation, fields, constructors, inheritance, polymorphism and abstract classes/methods. 4) Common collection types from the Java library like List, Stack, Queue and their usage along with examples of ArrayList and LinkedList implementations.

Uploaded by

ChinmayD
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

KT Byte Java Cheat Sheet

The document provides a summary of key Java language concepts including: 1) Primitive data types, operators, and casting methods. It describes common types like int, float, boolean, and char along with assignment, arithmetic, comparison, and bitwise operators. 2) Control flow structures such as if/else statements, while, for, and do-while loops, and how to break or continue execution. 3) Class/object concepts including instantiation, fields, constructors, inheritance, polymorphism and abstract classes/methods. 4) Common collection types from the Java library like List, Stack, Queue and their usage along with examples of ArrayList and LinkedList implementations.

Uploaded by

ChinmayD
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

THE JAVA LANGUAGE CHEAT SHEET IF STATEMENTS: CLASS/OBJECT TYPES:

Primitive Types: if( boolean_value ) { STATEMENTS } INSTANTIATION:


INTEGER: byte(8bit),short(16bit),int(32bit), else if( bool ) { STATEMENTS } public class Ball {//only 1 public per file
long(64bit),DECIM:float(32bit),double(64bit) else if( ..etc ) { STATEMENTS } //STATIC FIELDS/METHODS
,OTHER: boolean(1bit), char (Unicode) else { STATEMENTS } private static int numBalls = 0;
HEX:0x1AF,BINARY:0b00101,LONG:8888888888888L //curly brackets optional if one line public static int getNumBalls() {
CHAR EXAMPLES: ‘a’,’\n’,’\t’,’\’’,’\\’,’\”’ LOOPS: return numBalls;
while( bool ) { STATEMENTS } }
Primitive Operators public static final int BALLRADIUS = 5;
Assignment Operator: = (ex: int a=5,b=3; ) for(INIT;BOOL;UPDATE) { STATEMENTS }
Binary Operators (two arguments): + - * / % //1INIT 2BOOL 3STATEMENTS 4UPDATE 5->Step2
do{ STATEMENTS }while( bool ); //INSTANCE FIELDS
Unary Operators: + - ++ -- private int x, y, vx, vy;
Boolean Not Operator (Unary): ! //do loops run at least once before checking
break; //ends enclosing loop (exit loop) public boolean randomPos = false;
Boolean Binary: == != > >= < <=
Boolean Binary Only: && || continue; //jumps to bottom of loop
ARRAYS: //CONSTRUCTORS
Bitwise Operators: ~ & ^ | << >> >>> public Ball(int x, int y, int vx, int vy)
Ternary Operator: bool?valtrue:valfalse; int[] x = new int[10]; //ten zeros
{
Casting, Conversion int[][] x = new int[5][5]; //5 by 5 matrix
this.x = x;
int x = (int)5.5; //works for numeric types int[] x = {1,2,3,4};
this.y = y;
int x = Integer.parseInt(“123”); x.length; //int expression length of array
this.vx = vx;
float y = Float.parseFloat(“1.5”); int[][] x = {{1,2},{3,4,5}}; //ragged array
this.vy = vy;
int x = Integer.parseInt(“7A”,16); //fromHex String[] y = new String[10]; //10 nulls
numBalls++;
String hex = Integer.toString(99,16);//toHex //Note that object types are null by default
}
//Previous lines work w/ binary, other bases Ball() {
//loop through array:
java.util.Scanner, input, output for(int i=0;i<arrayname.length;i++) {
x = Math.random()*100;
Scanner sc = new Scanner(System.in); y = Math.random()*200;
//use arrayname[i];
int i = sc.nextInt(); //stops at whitespace randomPos = true;
}
String line = sc.nextLine(); //whole line }
System.out.println(“bla”); //stdout //for-each loop through array
System.err.print(“bla”); //stderr,no newline //INSTANCE METHODS
int[] x = {10,20,30,40};
java.lang.Number types public int getX(){ return x; }
for(int v : x) {
Integer x = 5; double y = x.doubleValue(); public int getY(){ return y; }
//v cycles between 10,20,30,40
double y = (double)x.intValue(); public int getVX(){ return vx; }
}
//Many other methods for Long, Double, etc public int getVY(){ return vy; }
public void move(){ x+=vx; y+=vy; }
java.lang.String Methods //Loop through ragged arrays:
public boolean touching(Ball other) {
//Operator +, e.g. “fat”+”cat” -> “fatcat” for(int i=0;i<x.length;i++)
float dx = x-other.x;
boolean equals(String other); for(int j=0;j<x[i].length;j++) {
float dy = y-other.y;
int length(); //CODE HERE
float rr = BALLRADIUS;
char charAt(int i); }
return Math.sqrt(dx*dx+dy*dy)<rr;
String substring(int i, int j); //j not incl }
boolean contains(String sub); //Note, multi-dim arrays can have nulls
boolean startsWith(String pre); //in many places, especially object arrays:
}
boolean endsWith(String post); Integer[][] x = {{1,2},{3,null},null};
int indexOf(String p); //-1 if not found FUNCTIONS / METHODS: //Example Usage:
int indexOf(String p, int i); //start at i Static Declarations: public static void main(String[] args) {
int compareTo(String t); public static int functionname( … ) Ball x = new Ball(5,10,2,2);
//“a”.compareTo(“b”) -> -1 private static double functionname( … ) Ball y = new Ball();
String replaceAll(String str, String find); static void functionname( … ) List<Ball> balls = new ArrayList<Ball>();
String[] split(String delim); Instance Declarations: balls.add(x); balls.add(y);
StringBuffer, StringBuilder public void functionname( … ) for(Ball b : balls) {
StringBuffer is synchronized StringBuilder private int functionname( … ) for(Ball o : balls) {
(Use StringBuilder unless multithreaded) Arguments, Return Statement: if(b != o) { //compares references
Use the .apend( xyz ) methods to concat int myfunc(int arg0, String arg1) { boolean touch = b.touching(o);
toString() converts back to String return 5; //type matches int myfunc }
java.lang.Math } }
Math.abs(NUM),Math.ceil(NUM),Math.floor(NUM) //Non-void methods must return before ending }
,Math.log(NUM),Math.max(A,B),Math.min(C,D), //Recursive functions should have an if }
Math.pow(A,B),Math.round(A),Math.random() //statement base-case that returns at once

® 2019 KTBYTE Computer Science Academy


POLYMORPHISM: JAVA COLLECTIONS: java.util.PriorityQueue<T>
Single Inheritance with “extends” List<T>: Similar to arrays A queue that is always automatically sorted
class A{ } ArrayList<T>: Slow insert into middle using the comparable function of an object
class B extends A{ } //ArrayList has fast random access
abstract class C { } LinkedList<T>: slow random access public static void main(String[] args) {
class D extends C { } //LinkedList fast as queue/stack Comparator<String> cmp= new LenCmp();
class E extends D Stack: Removes and adds from end PriorityQueue<String> queue =
Abstract methods new PriorityQueue<String>(10, cmp);
abstract class F { List Usage: queue.add("short");
abstract int bla(); boolean add(T e); queue.add("very long indeed");
} void clear(); //empties queue.add("medium");
class G extends F { boolean contains(Object o); while (queue.size() != 0)
int bla() { //required method T get(int index); System.out.println(queue.remove());
return 5; T remove(int index); }
} boolean remove(Object o); class LenCmp implements Comparator<String> {
} //remove uses comparator public int compare(String x, String y){
Multiple Inheritance of interfaces with T set(int index, E val); return x.length() – y.length();
“implements” (fields not inherited) Int size(); }
interface H { }
void methodA(); List Traversal: java.util.Collections algorithms
boolean methodB(int arg); for(int i=0i<x.size();i++) { Sort Example:
} //use x.get(i); //Assuming List<T> x
interface I extends H{ } Collections.sort(x); //sorts with comparator
void methodC(); Sort Using Comparator:
} //Assuming List<T>: Collections.sort(x, new Comparator<T>{
interface K {} for(T e : x) { public int compareTo(T a, T b) {
class J extends F implements I, K { //use e //calculate which is first
int bla() { return 5; } //required from F } //return -1, 0, or 1 for order:
void methodA(){} //required from H return someint;
boolean methodB(int a) { //req from A Queue<T>: Remove end, Insert beginning }
return 1; LinkedList implements Queue }
} Example of two dimensional array sort:
void methodC(){} //required from I Queue Usage: public static void main(final String[] a){
} T element(); // does not remove final String[][] data = new String[][] {
Type inference: boolean offer(T o); //adds new String[] { "20090725", "A" },
A x = new B(); //OK T peek(); //pike element new String[] { "20090726", "B" },
B y = new A(); //Not OK T poll(); //removes new String[] { "20090727", "C" },
C z = new C(); //Cannot instantiate abstract T remove(); //like poll new String[] { "20090728", "D" } };
//Method calls care about right hand type Traversal: for(T e : x) {} Arrays.sort(data,
(the instantiated object) Set<T>: uses Comparable<T> for uniqueness new Comparator<String[]>() {
//Compiler checks depend on left hand type TreeSet<T>, items are sorted public int compare(final String[]
GENERICS: HashSet<T>, not sorted, no order entry1, final String[] entry2) {
class MyClass<T> { LinkedHashSet<T>, ordered by insert final String time1 = entry1[0];
T value; Usage like list: add, remove, size final String time2 = entry2[0];
T getValue() { return value; } Traversal: for(T e : x) {} return time1.compareTo(time2);
} Map<K,V>: Pairs where keys are unique }
class ExampleTwo<A,B> { HashMap<K,V>, no order });
A x; LinkedHashMap<K,V> ordered by insert
B y; TreeMap<K,V> sorted by keys for (final String[] s : data) {
} System.out.println(s[0]+" "+s[1]);
class ExampleThree<A extends List<B>,B> { V get(K key); }
A list; Set<K> keySet(); //set of keys }
B head; V put(K key, V value); }
} V remove(K key); More collections static methods:
//Note the extends keyword here applies as Int size(); Collections.max( … ); //returns maximum
well to interfaces, so A can be an interface Collection<V> values(); //all values Collections.min( … ); //returns maximum
that extends List<B> Collections.copy( A, B); //A list into B
Traversal: for-each w/ keyset/values Collections.reverse( A ); //if A is list

® 2019 KTBYTE Computer Science Academy

You might also like