Show Menu

Java + OOP concept Cheat Sheet by

Created by Information Technology, KMITL students #IT14

Hello World!

Start your Java day with Hello World program
public class HelloWorld {
public static void main(S­tring[] args) {
// Prints "­Hello, World" to the terminal window.
System.ou­t.p­rin­tln­("Hello, World");

When you want to run the program, choose this class as main class.

Run your code

Compile from single class up HelloWorld class
javac HelloW­orl­
java HelloWorld

Compile from multiple classes and choose main class
javac *.java
java HelloWorld // HelloWorld is your preferred main class


Default Value
Memory Allocation
8 bits
16 bits
32 bits
64 bits
32 bits (decimal)
64 bits (decimal)
varies on impliment
depends on character count
16 bits (unicode)


What they do
Assign value
Check value/­address similarity
More than
More than or equals
Move bit to the right by
Increment by 1
inverse of these operands still working the same.
For example : != is not equal

Defining variable

Defining new variable attributes
int x = 12;
int x; // will be defined as 0

Define by creating new instances
String x = new String;

Type Casting (decre­asing bit use)
Expanding data types will not require type casting. Narrowing does.
double x = 10; // Expanding data types
int y = (int) 10.222222; // Narrowing data types


If statement
if (state­ment) {}
If - else statement
if (state­ment) {} else{}


switch (num) {
  case 1: doSomething();
  default: doThis();


for (int i: someArray) {}
while (somet­hing) {}
do {somet­hing} while (true)

Prime number function

if (n < 2) { return false; }
for (int i=2; i <= n/i; i++)
  if (n%i == 0) return false;
return true;
returns a boolean

String Pool - Optimi­zations

String pool is created to make the same value string use the same address. By doing that, it will save memory and time for compiler to do stuff

Basic testing
String s1 = "­Hello World";
String s2 = "­Hello World;

Check it using "­=="
System.ou­t.p­rin­tln(s1 == s2);
"­==" will check its address

Allocate a new address using new
String s1 = "­Hello World";
String s2 = new String;
s2 = "­Hello World";
System.ou­t.p­rin­tln(s1 == s2);

Allocate new address by changing its value
String s1 = "­Hello World";
String s2 = "­Hello World";
s2 = "­Hello Thaila­nd";
System.ou­t.p­rin­tln(s1 == s2);

Naming Grammars

Naming should be regulated for easier recogition from others

Use Upper Camel Case for classes: Veloci­tyR­esp­ons­eWriter
Use Lower Case for packages:­mpa­ny.p­ro­ject.ui
Use Lower Camel Case for variables: studen­tName
Use Upper Case for constants: MAX_PA­RAM­ETE­R_COUNT = 100

Use Camel Case for enum class names
Use Upper Case for enum values
Don't use '_' anywhere except constants and enum values (which are consta­nts).

Receiving user input

There is normally 2 ways to receive user keyboard input

1. java.u­til.Sc­anner
Scanner x = new Scanne­r(S­yst­;
String inputS­tring =; // for String type input
int inputI­nteger =­Int(); // for Integer type input

2. String[] args from public static void main()
NOTE: args is already in a array. It can receives unlimited amount of arguments.
String inputS­tring = args[0]; // for String type input
Int inputS­tring = (int) args[0]; // for Integer type input
To use Scanner, importing Scanner library is required : import java.O­bje­ct.S­canner

All types of input can be received. (not just String or int)

Access Modifier

- Java uses <de­fau­lt> modifier when not assigning any.
- public modifier allows same class access
- Works in inherited class means itself and the classes that inherit from it.

Attribute modifier

Attribute Type
Access Grants
Allows only in class where variable belongs
Allows any class to have this attribute
Attribute that dependent on class (not object)
Defined once. Does not allow any change­/in­her­itance


Methods are fucking easy, dud.
<mo­d> <re­tur­n> mthdName (<a­rgs­>) { }

public double getAge () {
 ­ ­return someDo­uble;


Constr­uctors allow you to create an object template. It consists of complete procedures.

Create a blank constr­uctor to allow its extension classes to inherit this super constr­uctor.
<mo­dif­ier> Person () {}
But will be created automa­tically by not writing any constr­uctor

Create an argume­nt-­defined constr­uctor
<mo­dif­ier> Person (String name) {
 ­ ­thi­ = name;

Abstract Class

Abstract is a type of class but it can consist of incomplete methods.

Create new abstract
<ac­ces­s_m­odi­fie­r> abstract class HelloWorld () {}


Interface is different from constr­uctor. It consists of incomplete assign­ments

Interface allows you to make sure that any inherited class can do the following methods. (It's like a contract to agree that this thing must be able to do this shit.) The method is then completed in the class that implements it.

Creating a new interface
interface Bicycle {
 ­ void speedUp (int increm­ent);
class fuckBike implements Bicycle {
 ­ ...
 ­ void speedUp (int increment) {
 ­ ­ ­ ­speed += increment;
 ­ }
 ­ ...


Encaps­ulation allows individual methods to have different access modifier.
Creating setters and getters is one way to use encaps­ulation

For example
private void setTim­e(int hour, int minuite, int second){
this.hour = hour;
this.m­inuite = minuite;
this.s­econd = second;


Inheri­tance helps class to import the superc­lass' method.

Importing superclass
class HelloWorld extends Object {}

Normally, the class that does not inherit any class will inherit Object class.*

Class can only inherit 1 class/­abs­tract

Importing Interface
class HelloWorld inherits Interf­ace­Thing {}

Class can inherit unlimited amount of interface


We use overload when you want different input to work differ­ently, but remains the same name.

Example of Overload
public printe­r(S­tring x){}
public printe­r(S­tring x, String y){}

If the input is 2 string, it will go to the second method instead of first one.

But you cannot overload by using the same input type sequence. For example
public printe­r(S­tring x){}
public printe­r(S­tring x, String y){} // conflict
public printe­r(S­tring y, String x){} // conflict

Java will not allow this to be run, because it cannot determine the value.


When you have inherit some of the class from parents, but you want to do something different. In override feature, all the subcla­ss/­class object will use the newer method.

To make sure JDK knows what you are doing, type @Override in front of the public name. If the override is unsucc­essful, JDK will returns error.

Example of overriden helloW­orld() method :
Class Student
public void helloW­orld(){

Class GradSt­udent extends Student
public void helloW­orld(){
System.ou­t.p­rin­tln­("Hello World");

Rules of Overridden methods
1. Access modifier priority can only be narrower or same as superclass
2. There is the same name method in superclass / libraries


Print with new line
System.ou­t.p­rin­tln­("Hello World");
System.ou­t.p­rin­t("Hello World");


Create a Scanner object
Scanner sc = new Scanne­r(S­yst­;
Accept input
double d = sc.nex­tDo­uble()


Math.m­ax(­<va­lue­1>, <va­lue­2>)
Return maximum value
Math.m­in(­<va­lue­1>, <va­lue­2>)
Return minimum value
Return unsigned value
Math.p­ow(­<nu­mbe­r>, <ex­pon­ent>
Return value of a numberexponent
Return square root of a value


Find the length -> int
To lower/­upp­ercase -> String­Low­erC­ase()­Upp­erC­ase()
Replace a string -> String­pla­ceA­ll(­String a, String b)
Split string between delimeter -> array
msg.sp­lit­(String delimeter)
Start/end with -> boolean­art­sWi­th(­String pre)
msg.en­dsW­ith­(String post)
String format -> String­rma­t(S­tring format, Object... args)


charAt(int index)
Returns the char value at the specified index
compar­eTo­(String otherS­tring)
Compare 2 strings lexico­gra­phi­cally
concat­(String str)
Concat­enate specified string
endsWi­th(­String suffix)
Test if the string ends with specified suffix
equals­(String andObject)
Test if strings values are the same
Convert string to character array
Convert string to lowercase
Convert string to uppercase
Convert things to string
Return the repres­ent­ation of argument
Return length of the string
replac­eAl­l(S­tring a, String b)
Replace string a to string b
split(­String delimeter)
Split string between delimeter
starts­Wit­h(S­tring prefix)
Test if string starts with specified prefix
format­(String format, Object arg)
Format strings to the format given

java.u­til.Co­lle­ction (Colle­cti­onAPI)

Provides ways to keep variables and access it faster

Ways to keep data
1. Set - Care about duplicity, not queue (eg. HashSet)
2. List - Care about queue, not duplicity (eg. Linked­List)
3. Map - Care about both queue and key duplicity (eg.Ha­shMap)

Methods that will be included
boolean add(Object element);
boolean remove­(Object element);
int size();
boolean isEmpty();
boolean contai­ns(­Object element);
Iterator Iterat­or();

HashList - Collec­tionAPI

void add (int index, Object element)
Add value to list
Object remove(int index)
Remove item #index from list
Object get(int index)
Retrieve item #index from list
void set(int index, Object element)
Set data to correspond #index
int indexO­f(O­bject element)
Find the #index from element
ListIt­erator listIt­era­tor()
It also includes all Collec­tionAPI methods

Create new HashList by using
List x = new HashLi­st();

HashMap - Collec­tionAPI



Create List of 1, 2, 3 on-the-fly­List(1, 2, 3)
Convert primitive array to Stream­rea­m(p­rim­iti­veA­rray)
Convert ArrayList to Stream

LinkedList - Collec­tionAPI

Create empty LinkedList of Integer
LinkedList myList = new Linked­Lis­t<I­nte­ger­>t()
Create LinkedList with values in it
new Linked­Lis­t<>­(Ar­ray­s.a­sLi­st(1, 2, 3)))
Add an object to LinkedList­d(50)


thanks a lot

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          OO_Java Cheat Sheet
          Selenium WebDriver Cheat Sheet Cheat Sheet
          ISTQB Test Automation Engineering Cheat Sheet