SlideShare a Scribd company logo
THE JAVA LANGUAGE CHEAT SHEET
Primitive Types:
INTEGER: byte(8bit),short(16bit),int(32bit),
long(64bit),DECIM:float(32bit),double(64bit)
,OTHER: boolean(1bit), char (Unicode)
HEX:0x1AF,BINARY:0b00101,LONG:8888888888888L
CHAR EXAMPLES: ‘a’,’n’,’t’,’’’,’’,’”’
Primitive Operators
Assignment Operator: = (ex: int a=5,b=3; )
Binary Operators (two arguments): + - * / %
Unary Operators: + - ++ --
Boolean Not Operator (Unary): !
Boolean Binary: == != > >= < <=
Boolean Binary Only: && ||
Bitwise Operators: ~ & ^ | << >> >>>
Ternary Operator: bool?valtrue:valfalse;
Casting, Conversion
int x = (int)5.5; //works for numeric types
int x = Integer.parseInt(“123”);
float y = Float.parseFloat(“1.5”);
int x = Integer.parseInt(“7A”,16); //fromHex
String hex = Integer.toString(99,16);//toHex
//Previous lines work w/ binary, other bases
java.util.Scanner, input, output
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); //stops at whitespace
String line = sc.nextLine(); //whole line
System.out.println(“bla”); //stdout
System.err.print(“bla”); //stderr,no newline
java.lang.Number types
Integer x = 5; double y = x.doubleValue();
double y = (double)x.intValue();
//Many other methods for Long, Double, etc
java.lang.String Methods
//Operator +, e.g. “fat”+”cat” -> “fatcat”
boolean equals(String other);
int length();
char charAt(int i);
String substring(int i, int j); //j not incl
boolean contains(String sub);
boolean startsWith(String pre);
boolean endsWith(String post);
int indexOf(String p); //-1 if not found
int indexOf(String p, int i); //start at i
int compareTo(String t);
//“a”.compareTo(“b”) -> -1
String replaceAll(String str, String find);
String[] split(String delim);
StringBuffer, StringBuilder
StringBuffer is synchronized StringBuilder
(Use StringBuilder unless multithreaded)
Use the .apend( xyz ) methods to concat
toString() converts back to String
java.lang.Math
Math.abs(NUM),Math.ceil(NUM),Math.floor(NUM)
,Math.log(NUM),Math.max(A,B),Math.min(C,D),
Math.pow(A,B),Math.round(A),Math.random()
IF STATEMENTS:
if( boolean_value ) { STATEMENTS }
else if( bool ) { STATEMENTS }
else if( ..etc ) { STATEMENTS }
else { STATEMENTS }
//curly brackets optional if one line
LOOPS:
while( bool ) { STATEMENTS }
for(INIT;BOOL;UPDATE) { STATEMENTS }
//1INIT 2BOOL 3STATEMENTS 4UPDATE 5->Step2
do{ STATEMENTS }while( bool );
//do loops run at least once before checking
break; //ends enclosing loop (exit loop)
continue; //jumps to bottom of loop
ARRAYS:
int[] x = new int[10]; //ten zeros
int[][] x = new int[5][5]; //5 by 5 matrix
int[] x = {1,2,3,4};
x.length; //int expression length of array
int[][] x = {{1,2},{3,4,5}}; //ragged array
String[] y = new String[10]; //10 nulls
//Note that object types are null by default
//loop through array:
for(int i=0;i<arrayname.length;i++) {
//use arrayname[i];
}
//for-each loop through array
int[] x = {10,20,30,40};
for(int v : x) {
//v cycles between 10,20,30,40
}
//Loop through ragged arrays:
for(int i=0;i<x.length;i++)
for(int j=0;j<x[i].length;j++) {
//CODE HERE
}
//Note, multi-dim arrays can have nulls
//in many places, especially object arrays:
Integer[][] x = {{1,2},{3,null},null};
FUNCTIONS / METHODS:
Static Declarations:
public static int functionname( … )
private static double functionname( … )
static void functionname( … )
Instance Declarations:
public void functionname( … )
private int functionname( … )
Arguments, Return Statement:
int myfunc(int arg0, String arg1) {
return 5; //type matches int myfunc
}
//Non-void methods must return before ending
//Recursive functions should have an if
//statement base-case that returns at once
CLASS/OBJECT TYPES:
INSTANTIATION:
public class Ball {//only 1 public per file
//STATIC FIELDS/METHODS
private static int numBalls = 0;
public static int getNumBalls() {
return numBalls;
}
public static final int BALLRADIUS = 5;
//INSTANCE FIELDS
private int x, y, vx, vy;
public boolean randomPos = false;
//CONSTRUCTORS
public Ball(int x, int y, int vx, int vy)
{
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
numBalls++;
}
Ball() {
x = Math.random()*100;
y = Math.random()*200;
randomPos = true;
}
//INSTANCE METHODS
public int getX(){ return x; }
public int getY(){ return y; }
public int getVX(){ return vx; }
public int getVY(){ return vy; }
public void move(){ x+=vx; y+=vy; }
public boolean touching(Ball other) {
float dx = x-other.x;
float dy = y-other.y;
float rr = BALLRADIUS;
return Math.sqrt(dx*dx+dy*dy)<rr;
}
}
//Example Usage:
public static void main(String[] args) {
Ball x = new Ball(5,10,2,2);
Ball y = new Ball();
List<Ball> balls = new ArrayList<Ball>();
balls.add(x); balls.add(y);
for(Ball b : balls) {
for(Ball o : balls) {
if(b != o) { //compares references
boolean touch = b.touching(o);
}
}
}
}
® 2013 Kapparate, © 2013 Kapparate Operating LLC
POLYMORPHISM:
Single Inheritance with “extends”
class A{ }
class B extends A{ }
abstract class C { }
class D extends C { }
class E extends D
Abstract methods
abstract class F {
abstract int bla();
}
class G extends F {
int bla() { //required method
return 5;
}
}
Multiple Inheritance of interfaces with
“implements” (fields not inherited)
interface H {
void methodA();
boolean methodB(int arg);
}
interface I extends H{
void methodC();
}
interface K {}
class J extends F implements I, K {
int bla() { return 5; } //required from F
void methodA(){} //required from H
boolean methodB(int a) { //req from A
return 1;
}
void methodC(){} //required from I
}
Type inference:
A x = new B(); //OK
B y = new A(); //Not OK
C z = new C(); //Cannot instantiate abstract
//Method calls care about right hand type
(the instantiated object)
//Compiler checks depend on left hand type
GENERICS:
class MyClass<T> {
T value;
T getValue() { return value; }
}
class ExampleTwo<A,B> {
A x;
B y;
}
class ExampleThree<A extends List<B>,B> {
A list;
B head;
}
//Note the extends keyword here applies as
well to interfaces, so A can be an interface
that extends List<B>
JAVA COLLECTIONS:
List<T>: Similar to arrays
ArrayList<T>: Slow insert into middle
//ArrayList has fast random access
LinkedList<T>: slow random access
//LinkedList fast as queue/stack
Stack: Removes and adds from end
List Usage:
boolean add(T e);
void clear(); //empties
boolean contains(Object o);
T get(int index);
T remove(int index);
boolean remove(Object o);
//remove uses comparator
T set(int index, E val);
Int size();
List Traversal:
for(int i=0i<x.size();i++) {
//use x.get(i);
}
//Assuming List<T>:
for(T e : x) {
//use e
}
Queue<T>: Remove end, Insert beginning
LinkedList implements Queue
Queue Usage:
T element(); // does not remove
boolean offer(T o); //adds
T peek(); //pike element
T poll(); //removes
T remove(); //like poll
Traversal: for(T e : x) {}
Set<T>: uses Comparable<T> for uniqueness
TreeSet<T>, items are sorted
HashSet<T>, not sorted, no order
LinkedHashSet<T>, ordered by insert
Usage like list: add, remove, size
Traversal: for(T e : x) {}
Map<K,V>: Pairs where keys are unique
HashMap<K,V>, no order
LinkedHashMap<K,V> ordered by insert
TreeMap<K,V> sorted by keys
V get(K key);
Set<K> keySet(); //set of keys
V put(K key, V value);
V remove(K key);
Int size();
Collection<V> values(); //all values
Traversal: for-each w/ keyset/values
java.util.PriorityQueue<T>
A queue that is always automatically sorted
using the comparable function of an object
public static void main(String[] args) {
Comparator<String> cmp= new LenCmp();
PriorityQueue<String> queue =
new PriorityQueue<String>(10, cmp);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0)
System.out.println(queue.remove());
}
class LenCmp implements Comparator<String> {
public int compare(String x, String y){
return x.length() – y.length();
}
}
java.util.Collections algorithms
Sort Example:
//Assuming List<T> x
Collections.sort(x); //sorts with comparator
Sort Using Comparator:
Collections.sort(x, new Comparator<T>{
public int compareTo(T a, T b) {
//calculate which is first
//return -1, 0, or 1 for order:
return someint;
}
}
Example of two dimensional array sort:
public static void main(final String[] a){
final String[][] data = new String[][] {
new String[] { "20090725", "A" },
new String[] { "20090726", "B" },
new String[] { "20090727", "C" },
new String[] { "20090728", "D" } };
Arrays.sort(data,
new Comparator<String[]>() {
public int compare(final String[]
entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
for (final String[] s : data) {
System.out.println(s[0]+" "+s[1]);
}
}
}
More collections static methods:
Collections.max( … ); //returns maximum
Collections.min( … ); //returns maximum
Collections.copy( A, B); //A list into B
Collections.reverse( A ); //if A is list
® 2013 Kapparate, © 2013 Kapparate Operating LLC
Ad

More Related Content

What's hot (20)

Scala best practices
Scala best practicesScala best practices
Scala best practices
Alexander Zaidel
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Array notes
Array notesArray notes
Array notes
Hitesh Wagle
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
Paulo Morgado
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
Muthu Vinayagam
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
John De Goes
 
PDBC
PDBCPDBC
PDBC
Sunil OS
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
Paulo Morgado
 
C# 7
C# 7C# 7
C# 7
Mike Harris
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
tdc-globalcode
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
tdc-globalcode
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
Hammurabi
HammurabiHammurabi
Hammurabi
Mario Fusco
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
stasimus
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
John De Goes
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
ssuserd6b1fd
 
Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?
Andrey Akinshin
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
John De Goes
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
Paulo Morgado
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
tdc-globalcode
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
tdc-globalcode
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
 
Groovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony CodeGroovy vs Boilerplate and Ceremony Code
Groovy vs Boilerplate and Ceremony Code
stasimus
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
John De Goes
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
ssuserd6b1fd
 
Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?Что нам готовит грядущий C#7?
Что нам готовит грядущий C#7?
Andrey Akinshin
 

Similar to Java cheatsheet (20)

C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
Array
ArrayArray
Array
Vivian Chia En Chiang
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
Aveic
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android Developers
Hassan Abid
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
league
 
C++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdfC++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdf
fqerwqdfad
 
CppQuickRef.pdf
CppQuickRef.pdfCppQuickRef.pdf
CppQuickRef.pdf
kurimaru1
 
Arrays
ArraysArrays
Arrays
archikabhatia
 
Array
ArrayArray
Array
Malainine Zaid
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
ilesh raval
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
Arduino Aficionado
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang Zhao
 
CS50 Lecture4
CS50 Lecture4CS50 Lecture4
CS50 Lecture4
昀 李
 
Pre zen ta sion
Pre zen ta sionPre zen ta sion
Pre zen ta sion
Sajid Alee Mosavi
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exception
Sajid Alee Mosavi
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
Aveic
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
Kotlin for Android Developers
Kotlin for Android DevelopersKotlin for Android Developers
Kotlin for Android Developers
Hassan Abid
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
league
 
C++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdfC++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdf
fqerwqdfad
 
CppQuickRef.pdf
CppQuickRef.pdfCppQuickRef.pdf
CppQuickRef.pdf
kurimaru1
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 
Core csharp and net quick reference
Core csharp and net quick referenceCore csharp and net quick reference
Core csharp and net quick reference
ilesh raval
 
Core c sharp and .net quick reference
Core c sharp and .net quick referenceCore c sharp and .net quick reference
Core c sharp and .net quick reference
Arduino Aficionado
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
Hang Zhao
 
CS50 Lecture4
CS50 Lecture4CS50 Lecture4
CS50 Lecture4
昀 李
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exception
Sajid Alee Mosavi
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Ad

Recently uploaded (20)

How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Vaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without HallucinationsVaibhav Gupta BAML: AI work flows without Hallucinations
Vaibhav Gupta BAML: AI work flows without Hallucinations
john409870
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Ad

Java cheatsheet

  • 1. THE JAVA LANGUAGE CHEAT SHEET Primitive Types: INTEGER: byte(8bit),short(16bit),int(32bit), long(64bit),DECIM:float(32bit),double(64bit) ,OTHER: boolean(1bit), char (Unicode) HEX:0x1AF,BINARY:0b00101,LONG:8888888888888L CHAR EXAMPLES: ‘a’,’n’,’t’,’’’,’’,’”’ Primitive Operators Assignment Operator: = (ex: int a=5,b=3; ) Binary Operators (two arguments): + - * / % Unary Operators: + - ++ -- Boolean Not Operator (Unary): ! Boolean Binary: == != > >= < <= Boolean Binary Only: && || Bitwise Operators: ~ & ^ | << >> >>> Ternary Operator: bool?valtrue:valfalse; Casting, Conversion int x = (int)5.5; //works for numeric types int x = Integer.parseInt(“123”); float y = Float.parseFloat(“1.5”); int x = Integer.parseInt(“7A”,16); //fromHex String hex = Integer.toString(99,16);//toHex //Previous lines work w/ binary, other bases java.util.Scanner, input, output Scanner sc = new Scanner(System.in); int i = sc.nextInt(); //stops at whitespace String line = sc.nextLine(); //whole line System.out.println(“bla”); //stdout System.err.print(“bla”); //stderr,no newline java.lang.Number types Integer x = 5; double y = x.doubleValue(); double y = (double)x.intValue(); //Many other methods for Long, Double, etc java.lang.String Methods //Operator +, e.g. “fat”+”cat” -> “fatcat” boolean equals(String other); int length(); char charAt(int i); String substring(int i, int j); //j not incl boolean contains(String sub); boolean startsWith(String pre); boolean endsWith(String post); int indexOf(String p); //-1 if not found int indexOf(String p, int i); //start at i int compareTo(String t); //“a”.compareTo(“b”) -> -1 String replaceAll(String str, String find); String[] split(String delim); StringBuffer, StringBuilder StringBuffer is synchronized StringBuilder (Use StringBuilder unless multithreaded) Use the .apend( xyz ) methods to concat toString() converts back to String java.lang.Math Math.abs(NUM),Math.ceil(NUM),Math.floor(NUM) ,Math.log(NUM),Math.max(A,B),Math.min(C,D), Math.pow(A,B),Math.round(A),Math.random() IF STATEMENTS: if( boolean_value ) { STATEMENTS } else if( bool ) { STATEMENTS } else if( ..etc ) { STATEMENTS } else { STATEMENTS } //curly brackets optional if one line LOOPS: while( bool ) { STATEMENTS } for(INIT;BOOL;UPDATE) { STATEMENTS } //1INIT 2BOOL 3STATEMENTS 4UPDATE 5->Step2 do{ STATEMENTS }while( bool ); //do loops run at least once before checking break; //ends enclosing loop (exit loop) continue; //jumps to bottom of loop ARRAYS: int[] x = new int[10]; //ten zeros int[][] x = new int[5][5]; //5 by 5 matrix int[] x = {1,2,3,4}; x.length; //int expression length of array int[][] x = {{1,2},{3,4,5}}; //ragged array String[] y = new String[10]; //10 nulls //Note that object types are null by default //loop through array: for(int i=0;i<arrayname.length;i++) { //use arrayname[i]; } //for-each loop through array int[] x = {10,20,30,40}; for(int v : x) { //v cycles between 10,20,30,40 } //Loop through ragged arrays: for(int i=0;i<x.length;i++) for(int j=0;j<x[i].length;j++) { //CODE HERE } //Note, multi-dim arrays can have nulls //in many places, especially object arrays: Integer[][] x = {{1,2},{3,null},null}; FUNCTIONS / METHODS: Static Declarations: public static int functionname( … ) private static double functionname( … ) static void functionname( … ) Instance Declarations: public void functionname( … ) private int functionname( … ) Arguments, Return Statement: int myfunc(int arg0, String arg1) { return 5; //type matches int myfunc } //Non-void methods must return before ending //Recursive functions should have an if //statement base-case that returns at once CLASS/OBJECT TYPES: INSTANTIATION: public class Ball {//only 1 public per file //STATIC FIELDS/METHODS private static int numBalls = 0; public static int getNumBalls() { return numBalls; } public static final int BALLRADIUS = 5; //INSTANCE FIELDS private int x, y, vx, vy; public boolean randomPos = false; //CONSTRUCTORS public Ball(int x, int y, int vx, int vy) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; numBalls++; } Ball() { x = Math.random()*100; y = Math.random()*200; randomPos = true; } //INSTANCE METHODS public int getX(){ return x; } public int getY(){ return y; } public int getVX(){ return vx; } public int getVY(){ return vy; } public void move(){ x+=vx; y+=vy; } public boolean touching(Ball other) { float dx = x-other.x; float dy = y-other.y; float rr = BALLRADIUS; return Math.sqrt(dx*dx+dy*dy)<rr; } } //Example Usage: public static void main(String[] args) { Ball x = new Ball(5,10,2,2); Ball y = new Ball(); List<Ball> balls = new ArrayList<Ball>(); balls.add(x); balls.add(y); for(Ball b : balls) { for(Ball o : balls) { if(b != o) { //compares references boolean touch = b.touching(o); } } } } ® 2013 Kapparate, © 2013 Kapparate Operating LLC
  • 2. POLYMORPHISM: Single Inheritance with “extends” class A{ } class B extends A{ } abstract class C { } class D extends C { } class E extends D Abstract methods abstract class F { abstract int bla(); } class G extends F { int bla() { //required method return 5; } } Multiple Inheritance of interfaces with “implements” (fields not inherited) interface H { void methodA(); boolean methodB(int arg); } interface I extends H{ void methodC(); } interface K {} class J extends F implements I, K { int bla() { return 5; } //required from F void methodA(){} //required from H boolean methodB(int a) { //req from A return 1; } void methodC(){} //required from I } Type inference: A x = new B(); //OK B y = new A(); //Not OK C z = new C(); //Cannot instantiate abstract //Method calls care about right hand type (the instantiated object) //Compiler checks depend on left hand type GENERICS: class MyClass<T> { T value; T getValue() { return value; } } class ExampleTwo<A,B> { A x; B y; } class ExampleThree<A extends List<B>,B> { A list; B head; } //Note the extends keyword here applies as well to interfaces, so A can be an interface that extends List<B> JAVA COLLECTIONS: List<T>: Similar to arrays ArrayList<T>: Slow insert into middle //ArrayList has fast random access LinkedList<T>: slow random access //LinkedList fast as queue/stack Stack: Removes and adds from end List Usage: boolean add(T e); void clear(); //empties boolean contains(Object o); T get(int index); T remove(int index); boolean remove(Object o); //remove uses comparator T set(int index, E val); Int size(); List Traversal: for(int i=0i<x.size();i++) { //use x.get(i); } //Assuming List<T>: for(T e : x) { //use e } Queue<T>: Remove end, Insert beginning LinkedList implements Queue Queue Usage: T element(); // does not remove boolean offer(T o); //adds T peek(); //pike element T poll(); //removes T remove(); //like poll Traversal: for(T e : x) {} Set<T>: uses Comparable<T> for uniqueness TreeSet<T>, items are sorted HashSet<T>, not sorted, no order LinkedHashSet<T>, ordered by insert Usage like list: add, remove, size Traversal: for(T e : x) {} Map<K,V>: Pairs where keys are unique HashMap<K,V>, no order LinkedHashMap<K,V> ordered by insert TreeMap<K,V> sorted by keys V get(K key); Set<K> keySet(); //set of keys V put(K key, V value); V remove(K key); Int size(); Collection<V> values(); //all values Traversal: for-each w/ keyset/values java.util.PriorityQueue<T> A queue that is always automatically sorted using the comparable function of an object public static void main(String[] args) { Comparator<String> cmp= new LenCmp(); PriorityQueue<String> queue = new PriorityQueue<String>(10, cmp); queue.add("short"); queue.add("very long indeed"); queue.add("medium"); while (queue.size() != 0) System.out.println(queue.remove()); } class LenCmp implements Comparator<String> { public int compare(String x, String y){ return x.length() – y.length(); } } java.util.Collections algorithms Sort Example: //Assuming List<T> x Collections.sort(x); //sorts with comparator Sort Using Comparator: Collections.sort(x, new Comparator<T>{ public int compareTo(T a, T b) { //calculate which is first //return -1, 0, or 1 for order: return someint; } } Example of two dimensional array sort: public static void main(final String[] a){ final String[][] data = new String[][] { new String[] { "20090725", "A" }, new String[] { "20090726", "B" }, new String[] { "20090727", "C" }, new String[] { "20090728", "D" } }; Arrays.sort(data, new Comparator<String[]>() { public int compare(final String[] entry1, final String[] entry2) { final String time1 = entry1[0]; final String time2 = entry2[0]; return time1.compareTo(time2); } }); for (final String[] s : data) { System.out.println(s[0]+" "+s[1]); } } } More collections static methods: Collections.max( … ); //returns maximum Collections.min( … ); //returns maximum Collections.copy( A, B); //A list into B Collections.reverse( A ); //if A is list ® 2013 Kapparate, © 2013 Kapparate Operating LLC