Java is an object-oriented programming language that’s popular among web developers. It is one of the most popular programming languages in the world and has existed for over 25 years. Java’s popularity and ease of use leads many corporations and programmers to practice the language. Since its compatible on PCs, MacIntosh computers, mobile phones and Linux computers, a lot of corporations use Java, such as Google, Uber, Amazon, Pinterest, Spotify, Netflix and many others.
Java is simple to use and shows no sign of declining popularity. For these reasons, it’s worth learning. The language is useful for building Android apps, but most importantly Java is so versatile that banks, retailers, insurance agencies, healthcare companies and the government use the language in some form, such as in Google’s Gmail.
QuickStart’s web development bootcamp explains the use of other popular programming languages through web development training.
Here is a Java cheat sheet, with common terms and common code you might see in a test for a job interview or a course:
Common Keywords
- abstract = Indicates parts of a class, method, or interface are given in the code.
- assert = Tests to see if a condition is true or not, based on the programmer’s assumption.
- boolean = Shows whether a value is true or false.
- break = Jumps out of a loop or switch.
- byte = Specifies that a value is an 8-bit whole number.
- case = Introduces one of a few possible paths of execution in a switch statement.
- catch = Finds exceptions created by try statements.
- char = Shows that a value is a character (a single letter, digit, punctuation symbol, etc.) stored in 16 bits of memory
- class = Introduces a blueprint for an object
- const = It’s not possible to use this word in a Java program, but it’s a common term. The word is meaningless but. Since it’s a keyword, you can’t create a variable named const.
- continue = Ends the current loop iteration and begins another iteration.
- default = Presents an execution path when there’s no possible match in a switch statement.
- do = Repeated statements.
- double = Wraps a value of the primitive type in an object.
- else = Introduces statements that are executed when the condition in an if statement isn’t true.
- enum = Defines a set of constants
- extends = Indicates that class is inherited
- final = Indicates a value can’t be changed, a class’s functionality can’t be extended or a method can’t be overridden.
- finally = Introduces the last statements in a try clause.
- float = Indicates that a value is a 32-bit number with one or more digits after the decimal point.
- for = Gets the computer to repeat statements repeatedly for a set amount of times.
- goto = This word can’t be used in a Java program, as it has no meaning. Because it’s a keyword, it’s not possible to create a variable named goto.
- if = Tests to see if a condition is true. If it’s true, certain statements are executed; otherwise, other statements are executed.
- implements = This is used to implement an interface.
- import = Allows you to abbreviate the names of classes defined in a package.
- instanceof = Tests to see whether an object comes from a certain class.
- Int = Indicates that a value is a 32-bit whole number.
- interface = Introduces an interface. An interface is like a class but an interface’s methods have no bodies.
- long = Indicates that a value is a 64-bit whole number.
- native = Enables the programmer to use code written in a language other than Java.
- new = Creates an object from an existing class.
- package = Puts the code into a package made of logically related definitions.
- private = Indicates that a variable or method can be used only within a certain class.
- protected = Indicates that a variable or method can be used in subclasses from another package.
- public = Indicates that a variable, class or method can be used by another Java code.
- return = Ends execution of a method and returns a value to the calling code.
- short = Indicates that a value is a 16-bit whole number.
- static = Indicates that a variable or method is a class method.
- Strictfp = Limits the computer’s ability to represent very large or small numbers when the computer does intermediate calculations on float and double values.
- super = This term refers to the parent class.
- switch = The computer follows one of many possible paths of execution.
- synchronized = Keeps two threads from interfering with one another.
- This = Refers to the object in which the word “this” appears.
- throw = Creates a new exception object and indicates that an undesirable situation has occurred.
- throws = Indicates that a method or constructor may pass the buck when an exception is thrown.
- transient = Indicates a variable’s value doesn’t require storing.
- try = Introduces statements that watch for whether everything will go right or not.
- void = Indicates that a method doesn’t return a value.
- volatile = Executes stringent rules on variable use by more than one thread at a time.
- while = Repeats statements that are true
Data Types
Primitive Data Types in Java
Data Type |
Default Value |
Size (in bytes) 1 byte = 8 bits |
boolean |
FALSE |
1 bit |
char |
“ “ (space) |
2 byte |
byte |
0 |
1 byte |
short |
0 |
2 byte |
int |
0 |
4 byte |
long |
0 |
8 byte |
float |
0.0f |
4 byte |
double |
0.0d |
8 byte |
Non-Primitive Data Types
- Data Type
- String
- Array
- Class
- Interface
Typical Java Statement
Statements in Java build programs. Every Java class has a body that’s made up of one or more statements. There are many different kinds of statements, such as the following:
The break Statement
break;
The continue Statement
continue;
The do Statement
do {statements...}while (expression);
The for statement
for (init; test; count) {statements...}
The enhanced for statement
for (type variable : array-or- collection) {statements...}
The if Statement
if (expression) {statements...}else {statements...}
The throw Statement
throw (exception)
The switch Statement
switch (expression){ case constant: statements; break; default: statements; break; }
The while Statement
while (expression) {statements...}
The try Statement
try {statements...}catch (exception-class e) {statements...}...finally {statements...}try {statements...}finally {statements...}
Types of Variables
- Static, Member (or instance), Local and Block are different kinds of variables.
Instance Variables
- Declared inside a class outside any method
- Each instance of the class has its own values
- Also known as member value, field or property
Local Variables
- Variables declared in a method
- Local variables can only be marked with final modifier
- If the name of a local variable is same as the instance variable name, it results in shadowing.
Member Variables
- Defined at class level, without keyword static.
Static Variable
- Defined at class level, using keyword static.
Member Variable and Static Variable
- Member Variables are accessed only through object references.
- Static Variables can be accessed through Class Name and Object Reference. It is not advocated you use object reference to refer to static variables.
Enroll in our Web Development Bootcamp program to get started.
Primitive Types:
Java Variables
Variables in Java refers to the location of the memory. You need variables to store any value for reference or computational reasons. It’s a container that holds the value while Java executes the program.
There are three types of variables in Java:
- Local Variables
- Instance Variables (or Global Variables)
- Static Variables
{public | private} [static] type name [= expression | value];
Java Methods
A method is a set of code that is grouped together to perform a particular operation. A method is completed in two steps:
- Method Initialization
- Method Invocation
A method can be invoked either by calling it by reference or by value.
{public | private} [static] {type | void} name(arg1, ..., argN ){statements}
Data Conversion
Data type conversion is the process of changing a value from one data type to another type. Data type conversion involves two types:
- Widening: The lower size datatype is converted into a higher size data type without information loss.
- Narrowing: The higher size datatype is converted into a lower size data type with any information loss.
// Widening (byte<short<int<long<float<double)
int i = 10; //int--> long
long l = i; //automatic type conversion
// Narrowing
double d = 10.02;
long l = (long)d; //explicit type casting
// Numeric values to String
String str = String.valueOf(value);
// String to Numeric values
int i = Integer.parseInt(str);
double d = Double.parseDouble(str);
User Input
Java provides three ways to receive input from the user:
- Using BufferReader class
- Using Scanner class
- Using the Console class
// Using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();// Using Scanner
Scanner in = new Scanner(System.in);
String s = in.nextLine();
int a = in.nextInt();// Using Console
String name = System.console().readLine();
Basic Java Program
A basic program in Java will consist of, at the minimum, the following components:
- Classes & Objects
- Methods
- Variables
public class Demo{
public static void main(String[] args)
{ System.out.println(Hello from QuickStart!);}
}
Compile a Java Program
You need to save your Java Program by the name of the class containing main() method along with .java extension.
className.java
Call the compiler using javac command.
javac className
Finally, execute the program using the below code:
java className
Flow of Control
Iterative Statements
Iterative statements are used when you have to repeat a set of statements until the condition for termination is not met, as seen below:
// for loop
for (condition) {expression}
// for each loop
for (int i: someArray) {}
// while loop
while (condition) {expression}
// do while loop
do {expression} while(condition)
Decisive Statements
Selection statements used when you need to choose between alternative actions during execution of the program.
//if statement
if (condition) {expression}
//if-else statement
if (condition) {expression} else {expression}
//switch statement
switch (var)
{ case 1: expression; break; default: expression; break; }
Generating a Fibonacci series.
for (i = 1; i <= n; ++i)
{System.out.print(t1 + + );
int sum = t1 + t2;
t1 = t2;
t2 = sum;}
Checking whether the given number is prime or not.
if (n < 2) { return false; }
for (int i=2; i <= n/i; i++)
{if (n%i == 0) return false;}
return true;
Creating a pyramid pattern.
k = 2*n - 2;
for(i=0; i<n; i++)
{ for(j=0; j<k; j++){System.out.print( );}
k = k - 1;
for(j=0; j<=i; j++ ){System.out.print(* );}
System.out.println(); }
Finding the factorial using recursion function.
int factorial(int n)
{
if (n == 0)
{return 1;}
else
{return(n * factorial(n-1));}
}
Start your 30-day free trial today
Java Arrays
Single Dimensional (1-D)
Single Dimensional or 1-D array is a type of linear array where elements are stored in a continuous row.
// Initializing
type[] varName= new type[size];
// Declaring
type[] varName= new type[]{values1, value2,...};
Multi-Dimensional (2-D)
Two Dimensional or 2-D array is an array of an array in which elements are stored in rows and columns.
// Initializing
datatype[][] varName = new dataType[row][col];
// Declaring
datatype[][] varName = {{value1, value2....},{value1, value2....}..};
Creating an array with random values.
double[] arr = new double[n];
for (int i=0; i<n; i++)
{a[i] = Math.random();}
Transposing a matrix.
for(i = 0; i < row; i++)
{ for(j = 0; j < column; j++)
{ System.out.print(array[i][j]+ ); }
System.out.println( );
}
Searching the max value in the array.
double max = 0;
for(int i=0; i<arr.length(); i++)
{ if(a[i] > max) max = a[i]; }
Multiplying two matrices.
for (i = 0; i < row1; i++)
{ for (j = 0; j < col2; j++)
{ for (k = 0; k < row2; k++)
{ sum = sum + first[i][k]*second[k][j]; }
multiply[i][j] = sum;
sum = 0;
}
}
Reversing an array.
for(int i=0; i<(arr.length())/2; i++)
{ double temp = a[i];
a[i] = a[n-1-i];
a[n-1-i] = temp;
}
Java Strings
Creating a String
A string in Java is an object that represents a sequence of char values. A string can be created in two ways:
- Using a literal
- Using a new keyword
String str1 = “Welcome”; // Using literal
String str2 = new String(”Edureka”); // Using new keyword
The java.lang.String class implements Serializable, Comparable, and CharSequence interfaces. Since the string object is immutable in nature Java provides two utility classes:
- StringBuffer:It is a mutable class that is thread-safe and synchronized.
- StringBuilder:It is a mutable class that is not thread-safe but is faster and used in a single-threaded environment.
String Methods
Some of the most important and frequently used string methods are found below:
str1==str2 //compares address;
String newStr = str1.equals(str2); //compares the values
String newStr = str1.equalsIgnoreCase() //compares the values ignoring the case
newStr = str1.length() //calculates length
newStr = str1.charAt(i) //extract i'th character
newStr = str1.toUpperCase() //returns string in ALL CAPS
newStr = str1.toLowerCase() //returns string in ALL LOWERvCASE
newStr = str1.replace(oldVal, newVal) //search and replace
newStr = str1.trim() //trims surrounding whitespace
newStr = str1.contains(value); //check for the values
newStr = str1.toCharArray(); // convert String to character type array
newStr = str1.IsEmpty(); //Check for empty String
newStr = str1.endsWith(); //Checks if string ends with the given suffix
String vs StringBuffer vs StringBuilder
- Immutability: String
- Thread Safety: String (immutable), StringBuffer
- Performance: StringBuilder (especially when many modifications are made)
String Constant Pool
- String literals are stored in a string constant pool. If the compiler finds a string literal, it checks if it exists in the pool. If it exists, it is reused.
- The following statement creates 1 string object (created on the pool) and 1 reference variable.
String str1 = value;
- However, if a new operator is used to create the string object, the new object is created on the heap. Here, a piece of code creates 2 objects.
//1. String Literal value - created in the String constant pool//2. String Object - created on the heapString str2 = new String(value);
String Method Examples
String class defines many methods to find information about the string content.
String str = abcdefghijk;
Get information from string:
The following methods help to get information from a String.
//char charAt(int paramInt)System.out.println(str.charAt(2)); //prints a char - cSystem.out.println(ABCDEFGH.length());//8System.out.println(abcdefghij.toString()); //abcdefghijSystem.out.println(ABC.equalsIgnoreCase(abc));//true //Get All characters from index paramInt//String substring(int paramInt)System.out.println(abcdefghij.substring(3)); //defghij //All characters from index 3 to 6System.out.println(abcdefghij.substring(3,7)); //defg String s1 = new String(HELLO); String s2 = new String(HELLO); System.out.println(s1 == s2); // falseSystem.out.println(s1.equals(s2)); // true
String Manipulation methods
The most important thing to remember is a String object can’t be modified. When any of these methods are called, they return a new String with the modified value. The original String remains unchanged.
//String concat(String paramString)System.out.println(str.concat(lmn));//abcdefghijklmn //String replace(char paramChar1, char paramChar2)System.out.println(012301230123.replace('0', '4'));//412341234123 //String replace(CharSequence paramCharSequence1, CharSequence paramCharSequence2)System.out.println(012301230123.replace(01, 45));//452345234523 System.out.println(ABCDEFGHIJ.toLowerCase()); //abcdefghij System.out.println(abcdefghij.toUpperCase()); //ABCDEFGHIJ //trim removes leading and trailings spacesSystem.out.println( abcd .trim()); //abcd
String Concatenation Operator
Three Rules of String Concatenation
- RULE1: Expressions are evaluated from left to right, except if there are parentheses.
- RULE2: number + number = number
- RULE3: number + String = String
System.out.println(5 + Test + 5); //5Test5System.out.println(5 + 5 + Test); //10TestSystem.out.println(5 + 5 + Test); //55TestSystem.out.println(5 + 5 + 25); //5525System.out.println(5 + 5 + 25); //1025System.out.println( + 5 + 5 + 25); //5525System.out.println(5 + (5 + 25)); //5525System.out.println(5 + 5 + 25); //35
Increment and Decrement Operators
Basics of Increment and Decrement Operators
Except for a minor difference ++i,i++ is similar to i = i+1 and --i,i-- is similar to i = i-1
++i is called pre-increment and i++ post increment
Increment Operators
The pre-increment statement returns value after increment. Post-increment statement returns value before increment.
int i = 25;int j = ++i;//i is incremented to 26, assigned to jSystem.out.println(i + + j);//26 26 i = 25;j = i++;//i value(25) is assigned to j, then incremented to 26System.out.println(i + + j);//26 25
Decrement Operators
Decrement Operators are similar to increment operators.
i = 25;j = --i;//i is decremented to 24, assigned to jSystem.out.println(i + + j);//24 24 i = 25;j = i--;//i value(25) is assigned to j, then decremented to 24System.out.println(i + + j);//24 25
Relational Operators
- Relational operators are used to compare operands. They always result in being true or false. Here is a list of relational operators: <, <=, >, >=, ==, and !=.
Relation Operators Examples
Here are examples of relational operators. Let's assume an int variable named number with a value of 7.
int number = 7;
greater than operator
System.out.println(number > 5);//trueSystem.out.println(number > 7);//false
greater than equal to operator
System.out.println(number >= 7);//true
less than operator
System.out.println(number < 9);//trueSystem.out.println(number < 7);//false
less than equal to operator
System.out.println(number <= 7);//true
is equal to operator
System.out.println(number == 7);//trueSystem.out.println(number == 9);//false
NOT equal to operator
System.out.println(number != 9);//trueSystem.out.println(number != 7);//false
single = is assignment operator and == is comparison. Below statement uses =.
System.out.println(number = 7);//7
== (equals) operator
Let's see how == equals operator works with primitives and reference variables.
Primitive Variables
- Equality for primitives only compares values
int a = 5;int b = 5;
Below statement compares if a and b have same value.
System.out.println(a == b);//true
Reference Variables
Integer aReference = new Integer(5);Integer bReference = new Integer(5);
For reference variables, == compares if they are referring to the same object.
System.out.println(aReference == bReference);//false bReference = aReference; //Now both are referring to same objectSystem.out.println(aReference == bReference);//true
Bitwise Operators
- Bitwise operators are |,&,^ and ~
int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 = 5 System.out.println(a&b = + (a & b)); // bitwise or // 0101 | 0111=0111 = 7 System.out.println(a|b = + (a | b)); // bitwise xor // 0101 ^ 0111=0010 = 2 System.out.println(a^b = + (a ^ b)); // bitwise and // ~0101=1010 // will give 2's complement of 1010 = -6 System.out.println(~a = + ~a); // can also be combined with // assignment operator to provide shorthand // assignment // a=a&b a &= b; System.out.println(a= + a); // a = 5
Logical Operators
- Logical operators: &&, ||, |, &, ! and ^.
Short Circuit and Operator - &&
- True when both operands are true.
System.out.println(true && true);//trueSystem.out.println(true && false);//falseSystem.out.println(false && true);//falseSystem.out.println(false && false);//false
Short Circuit or Operator - ||
True when at least one of operands are true.
System.out.println(true || true);//trueSystem.out.println(true || false);//trueSystem.out.println(false || true);//trueSystem.out.println(false || false);//false
Certification Tip : Logical Operators work with boolean values but not numbers.
//System.out.println(5 || 6);//COMPILER ERROR
Short Circuit Operators Are Lazy
- They stop execution the moment result is clear.
- For &&, if first expression is false, result is false.
- For ||, if first expression is true, the result is true.
- In above two situations, second expressions are not executed.
int i = 10;System.out.println(true || ++i==11);//trueSystem.out.println(false && ++i==11);//falseSystem.out.println(i);//i remains 10, as ++i expressions are not executed.
Operator & and |
- Logical Operators &, | are similar to &&, || except that they don't short circuit.
- They execute the second expression even if the result is decided.
Certification Tip : While & and | are very rarely used, it is important to understand them from a certification perspective.
int j = 10;System.out.println(true | ++j==11);//trueSystem.out.println(false & ++j==12);//falseSystem.out.println(j);//j becomes 12, as both ++j expressions are executed
Operator exclusive-OR (^)
- Result is true only if one of the operands is true.
System.out.println(true ^ false);//trueSystem.out.println(false ^ true);//trueSystem.out.println(true ^ true);//falseSystem.out.println(false ^ false);//false
Not Operator (!)
Result is the negation of the expression.
System.out.println(!false);//trueSystem.out.println(!true);//false
Arrays
- TODO: Why do we need arrays?
//Declaring an Arrayint[] marks; // Creating an arraymarks = new int[5]; // 5 is size of array int marks2[] = new int[5];//Declaring and creating an array in same line. System.out.println(marks2[0]);//New Arrays are always initialized with default values - 0 //Index of elements in an array runs from 0 to length - 1marks[0] = 25;marks[1] = 30;marks[2] = 50;marks[3] = 10;marks[4] = 5; System.out.println(marks[2]);//Printing a value from array //Printing a 1D Arrayint marks5[] = { 25, 30, 50, 10, 5 };System.out.println(marks5); //[I@6db3f829System.out.println( Arrays.toString(marks5));//[25, 30, 50, 10, 5] int length = marks.length;//Length of an array: Property length //Enhanced For Loopfor (int mark: marks) { System.out.println(mark);} //Fill array with a valueArrays.fill(marks, 100); //All array values will be 100 //String ArraysString[] daysOfWeek = { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
QuickStart’s Web Development Training Bootcamp
Everyone’s cheat sheet will look different, as some focus on certain things more than others. That’s why looking at a variety of sources will help you get a good summary of Java. Other cheat sheet sources include GitHub. If you are interested in learning all about web development—frontend, backend, and/or full-stack—then enroll in our web development training, which is a boot camp where you can earn a certification from a university to help you get hired right out of college or simply improve your resume.
Connect with our experts to learn more and start your journey to a successful career today!