Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java Cheat Sheet

The document is a comprehensive cheat sheet for the Java programming language, covering fundamental concepts such as data types, control structures (if statements, loops), operators, arrays, object-oriented programming principles (inheritance, polymorphism), and Java collections. It includes code snippets and examples for each concept, making it a useful reference for Java developers. Additionally, it provides insights into generics and common collection classes like ArrayList, LinkedList, and HashMap.

Uploaded by

Radhika Punnam
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)
6 views

Java Cheat Sheet

The document is a comprehensive cheat sheet for the Java programming language, covering fundamental concepts such as data types, control structures (if statements, loops), operators, arrays, object-oriented programming principles (inheritance, polymorphism), and Java collections. It includes code snippets and examples for each concept, making it a useful reference for Java developers. Additionally, it provides insights into generics and common collection classes like ArrayList, LinkedList, and HashMap.

Uploaded by

Radhika Punnam
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
You are on page 1/ 2

Suresh Bishnoi LinkedIn: https://www.linkedin.

com/in/bishnoisuresh/

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
//CONSTRUCTORS
Bitwise Operators: ~ & ^ | << >> >>> ARRAYS: 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
Suresh Bishnoi LinkedIn: https://www.linkedin.com/in/bishnoisuresh/
Suresh Bishnoi LinkedIn: https://www.linkedin.com/in/bishnoisuresh/

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:
boolean methodB(int arg); for(int i=0i<x.size();i++) { java.util.Collections algorithms
} //use x.get(i); Sort Example:
interface I extends H{ } //Assuming List<T> x
void methodC(); Collections.sort(x); //sorts with comparator
} //Assuming List<T>: Sort Using Comparator:
interface K {} for(T e : x) { Collections.sort(x, new Comparator<T>{
class J extends F implements I, K { //use e public int compareTo(T a, T b) {
int bla() { return 5; } //required from F } //calculate which is first
void methodA(){} //required from H //return -1, 0, or 1 for order:
boolean methodB(int a) { //req from A Queue<T>: Remove end, Insert beginning return someint;
return 1; LinkedList implements Queue }
} }
void methodC(){} //required from I Queue Usage: Example of two dimensional array sort:
} T element(); // does not remove public static void main(final String[] a){
Type inference: boolean offer(T o); //adds final String[][] data = new String[][] {
A x = new B(); //OK T peek(); //pike element new String[] { "20090725", "A" },
B y = new A(); //Not OK T poll(); //removes new String[] { "20090726", "B" },
C z = new C(); //Cannot instantiate abstract T remove(); //like poll new String[] { "20090727", "C" },
//Method calls care about right hand type Traversal: for(T e : x) {} new String[] { "20090728", "D" } };
(the instantiated object) Set<T>: uses Comparable<T> for uniqueness Arrays.sort(data,
//Compiler checks depend on left hand type TreeSet<T>, items are sorted new Comparator<String[]>() {
HashSet<T>, not sorted, no order public int compare(final String[]
GENERICS: LinkedHashSet<T>, ordered by insert entry1, final String[] entry2) {
class MyClass<T> { Usage like list: add, remove, size final String time1 = entry1[0];
T value; Traversal: for(T e : x) {} final String time2 = entry2[0];
T getValue() { return value; } Map<K,V>: Pairs where keys are unique return time1.compareTo(time2);
} HashMap<K,V>, no order }
class ExampleTwo<A,B> { LinkedHashMap<K,V> ordered by insert });
A x; TreeMap<K,V> sorted by keys
B y; for (final String[] s : data) {
} V get(K key); System.out.println(s[0]+" "+s[1]);
class ExampleThree<A extends List<B>,B> { Set<K> keySet(); //set of keys }
A list; V put(K key, V value); }
B head; V remove(K key); }
} Int size(); More collections static methods:
//Note the extends keyword here applies as Collection<V> values(); //all values Collections.max( … ); //returns maximum
well to interfaces, so A can be an interface Collections.min( … ); //returns maximum
that extends List<B> Traversal: for-each w/ keyset/values Collections.copy( A, B); //A list into B
Collections.reverse( A ); //if A is list
Suresh Bishnoi LinkedIn: https://www.linkedin.com/in/bishnoisuresh/

You might also like