Java is among the best programming languages. It is a powerful and flexible programming language that has a wide range of applications.
Here, with this Java cheat sheet, we aim to deliver a comprehensive Java reference. Since this Java cheat sheet is going to be a long article covering a wide array of Java topics, it's good to have a table of contents. This will make it simpler to look for a specific Java topic rather than going back and forth the entire Java cheat sheet.
Java Characteristics
Let's start the Java cheat sheet with the important points about Java:
- Java is an object-oriented programming language .
- It is the most powerful and widely used programming language.
- Since it is open-source, everyone can use Java for free.
- Cross-platform availability.
- Its byte code is platform-independent.
- Garbage collected language.
- Supports multithreading.
- It is a statically typed language, which ensures fast performance.
Data Types in Java
Java has 2 data types:
- Primitive and
- Non-primitive.
Primitive Data Type
These are the data types that can not be divided further. These are also known as atomic data types.
Primitive Data Types | Size | Default Value |
int | 4 bytes | 0 |
char | 2 bytes | " " <SPACE> |
boolean | 1 bit | False |
float | 4 bytes | 0.0f |
double | 8 bytes | 0.0d |
long | 8 bytes | 0 |
short | 2 bytes | 0 |
Non-primitive Data Type
Non-primitive data types can be divided further into 4 data types:
- Array
- String
- Class
- Interface
Type Casting
Type casting is a method in Java by which the data type of one variable gets converted into another data type. There are 2 types of typecasting:
- Implicit typecasting : In implicit typecasting, the Java Compiler itself changes the data type of a variable without any user intervention.
- Explicit Typecasting : In explicit typecasting, the user is responsible for changing the data type of a variable from one to another using reserved words.
Operators in Java
There are many standard operators present in Java. The following table enumerates the various operators and their types:
Category | Operators |
Arithmetic Operators |
|
Relational Operators |
|
Logical Operators |
|
Assignment Operators |
|
Increment Operator |
|
Decrement Operator |
|
Conditional Operator |
|
Bitwise Operators |
|
Dot Operator (To call class method and attributes.) |
|
Best IDEs for Java
There are many IDEs and text editors to code in Java. Here are the 2 most popular IDEs for Java development:
- Eclipse
- IntelliJ IDEA Community Edition
Variables in Java
A variable or identifier is the name given to an object, which is stored at a particular address. With the variable, we can access that object or its value very easily. In Java, there are 3 types of variables:
- Local Variable
- Global Variable
- Static Variable
Important information regarding the 3 types of variables is summed up in the following table:
Types | Description |
Local Variables |
|
Global Variables |
|
Static Variable |
|
Example:
class Variables
{
int g = 20; // Global variable
static int s = 10; //static variable
void method()
{
int l = 100; //local variable
}
}
Keywords
There are many words in Java, which are reserved, and we can not use these as variables or identifiers. As such, they are also known as reserved words. Some keywords in Java are:
|
Java Methods
We use methods in Java to add functionality to a program . Also, methods increase the reusability of code. Methods are the functions defined inside a class. There are some notations we should take care of while we write a method in Java:
- Return Type of the method (void, int, float).
- Name of the method (method name, like a variable).
- Arguments (paraments we pass in the method).
- return (a return statement, which returns a single value when we call the function. A return statement cannot have a void return type).
Syntax example:
return_type name (arguments)
{
//body of the method
//return value () // except void return_type
}
Con
ditional Statements in Java
Conditional Statements | Description |
if-else | It contains two blocks; if block and else block. The if statement works on a Boolean value. If the Boolean value is true, the if block will execute, otherwise the else block will execute. |
switch | It consists of different cases and the case that matches the switch parameter value gets to execute. |
Example (if-else):
class IFELSE
{
public static void main(String args[])
{
int num = 70;
if(num > 75)
{
System.out.println("Number is greater than 75");
}
else
{
System.out.println("Number is less than 75");
}
}
}
Example (switch):
class Switch_Case
{
public static void main(String args[])
{
int day = 0;
switch(day)
{
case 0 :
System.out.println("sunday");
break;
case 1 :
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Wednesday");
break;
case 5 :
System.out.println("Thursday");
break;
case 6 :
System.out.println("Friday");
break;
case 7 :
System.out.println("Saturday");
break;
}
}
}
Loops in Java
These are often used to execute the same block of statements again and again, up to a finite time. In Java, we have 3 types of loop:
Loops | Description |
for | We use for loop when we are certain to a specific number of times we want to iterate over a block of code. |
while | The while loop executes the same statement of code again and again until the condition is true. |
do-while | It is similar to while loop, but even if the condition is false, the while loop iterates over its block of code once. |
Example (loops): For Loop:
class For_LOOP
{
public static void main (String args[])
{
for(int i=0;i<=10;i++)
System.out.println(i);
}
While Loop:
class While_LOOP
{
public static void main (String args[])
{
int i = 1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Do While Loop:
class Do_While_Loop
{
public static void main (String args[])
{
int i = 1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}
Java OOPs
Java is an object-oriented programming language because it supports the basic properties of object-oriented programming, such as polymorphism, class, objects, inheritance, and abstraction. With the help of object-oriented concept, we can increase the efficiency of programming and software development.
Properties of Object-Oriented Programming:
- Class and Objects
- Data Abstraction and Encapsulation
- Inheritance
- Polymorphism
Class and Object
A class is a structure that provides a blueprint of functionality. Also, it is a collection of methods and attributes where methods are the user-defined functions and attributes are the variables associated with that class. It comes into existence when its object gets created. With the help of the object, we can access the class properties, which include class attributes and methods.
Data Abstraction and Encapsulation
With data encapsulation, we can wrap a collection of data into a single entity. For example, with a class, we wrap many methods and attributes. Data abstraction allows the user to deal with the object with no knowledge of class and its methods.
Inheritance
Inheritance is one of the major concepts of object-oriented programming. With inheritance, we can inherit the properties and methods from one class to another. Some important points about inheritance are:
- A derived class can not inherit the private members of the base class.
- A constructor can not be inherited.
Types of Inheritance
- Single Inheritance : In single inheritance, there is only one base and one derived class. Minimum 2 classes are required for single inheritance.
- Multilevel Inheritance : In multilevel inheritance, the derived class itself is a base class for another class. Multilevel inheritance requires at least 3 classes.
- Multiple Inheritance : In multiple inheritance, the child or derived class can have 2 or more than 2 base or parent classes. Java does not have standard support for multiple inheritance. Nonetheless, to achieve this, we use Java interfaces.
- Hierarchical Inheritance : When 2 or more child classes inherit properties from the same base or parent class then it is called hierarchical inheritance.
Code example:
class A
{
void a_method() {
System.out.println(" From Class A");
}
}
class B extends A {
void b_method() {
System.out.println("From Class B" );
}
}
class Inheritance {
public static void main(String args[]) {
A a = new A();
B b = new B();
a.a_method();
b.b_method();
}
}
Polymorphism
Polymorphism deals with the same operator performing different tasks. To achieve polymorphism in Java, we do method overloading and method overriding.
Method Overriding
When the child class has the same method name, with the same data types of argument as the parent class, it is called method overriding. Here the child class overrides the method of the parent class.
Example:
class Base
{
void method()
{
System.out.printf("Method of Base");
System.out.println();
}
}
class Derived extends Base
{
void method()
{
System.out.printf("Method of Derived");
}
public static void main (String args[])
{
Derived obj = new Derived();
obj.method();
}
}
Method Overloading
When a class has two or more methods with the same name but different parameters, it is method overloading.
Example:
class Overloading
{
public void over(int i)
{
System.out.println(i);
}
public void over(int i, int num)
{
System.out.println(i +num);
}
}
class Main_Class
{
public static void main(String args[])
{
Overloading obj = new Overloading();
obj.over(200);
obj.over(200,10);
}
}
Abstract Class
To define an abstract class, we use the abstract keyword before the class name. The abstract class can not be inherited by any class.
Example:
abstract class Bus{
abstract void buy();
}
class Tata extends Bus{
void buy()
{
System.out.println("Go For it");
}
static void main(String args[]){
Bus obj = new Tata ();
obj.buy();
}
}
Interface
An interface in Java helps to implement the concept of abstraction. In an interface class, we only have abstract methods and no method body. With interfaces, we can also achieve multiple inheritance in Java.
Example:
interface Sun{
void rays();
}
class Mercury implements Sun{
public void rays(){System.out.println("Mercury");}
}
class Earth implements Sun{
public void rays(){System.out.println("Earth");}
}
class Sunlight{
public static void main(String args[]){
Sun e =new Earth();
e.rays();
}}
Java Constructor
- A constructor is a special method of a class, which is automatically called when we initialize the class object.
- The constructor shares the same name as that of its class.
- It does not have any return type.
- The constructor can’t be static, abstract or final.
- A constructor can have parameters.
Example:
class Cons {
Cons() // Constructor of Box
{
System.out.println("Constructor");
}
}
class BoxVol {
public static void main(String args[])
{
Cons mybox1 = new Cons(); // initializing object and calling constructor
}
}
Arrays
An array is a collection of similar data types, which stores all items in a contiguous memory location. We can store primitive data types in an array. The array supports indexing and that’s how we can randomly access any item of the array. Java supports two types of array:
- One-dimensional array
- 2-dimensional array
Example:
int [] numbers = {3,44,12,53,6,87};
int [][] m1 = { {1,5,7}, {2,4,6}};
int [][] m2 = {{1,2,1},{4,4,3}};
Strings in Java
A string is a sequential collection of characters inside “ ” double-quotes. It is an array of char data type. By default, the last element of a string is ‘\0’ (Null). Strings are immutable, which means once a string is declared we cannot modify its elements. To define a string, we use the String keyword.
Syntax to define a String:
<String_Type> <string_variable> = “<sequence_of_string>”;
OR
<String_Type> <string_variable> = new String (“<sequence_of_string>”);
Example:
String str = " TechGeekBuzz "
Or
String str = new String("TechGeekbuzz");
Java String Standard Methods
There are many standard methods associated with the Java strings. These are summed up as follows:
Method | Description |
toLowerCase() | Converts a string to lowercase. |
toUpperCase() | Converts a string to uppercase. |
replace(‘x’, ‘y’) | Replaces the value of ‘x’ with ‘y.’ |
trim() | Removes the end and beginning whitespaces. |
equals() | Checks whether two strings are equal or not. Returns a Boolean value. |
equalsIgnoreCase() | Checks whether two strings are equal or not and ignores the case. Returns a Boolean value. |
length() | Returns the total number of characters in a string. |
CharAt(n) | Returns the nth character value. |
compareTo() | Compares 2 strings. |
concat() | Joins 2 strings. |
substring(n) | Returns the part of the string from the nth index. |
substring(n,m) | Returns a sequence of strings between n to m. |
toString() | Helps to provide a string representation. |
indexOf(‘x’) | Returns the index value of the “x” character. |
indexOf(‘x’,n) | Returns the index value of x after the nth index. |
ValueOf (Variable) | Converts the parameter value to the string value. |
StringBuffer
It is an extension of the string data type, which provides more functionality, and it creates a CharSequence, which is better than string for some cases. The CharSequence generated by StringBuffer is growable and writable.
Example:
StringBuffer s = new StringBuffer("TechGeekBuzz");
StringBuilder
StringBuilder creates a mutable string.
StringBuilder str = new StringBuilder();
str.append("TGB");
A program to compare two strings in Java:
public class TechGeekBuzz {
public static int Compare_String(String str1, String str2)
{
int len1 = str1.length();
int len2 = str2.length();
int lenmin = Math.min(len1, len2);
for (int i = 0; i < lenmin; i++) {
int str1_ch = (int)str1.charAt(i);
int str2_ch = (int)str2.charAt(i);
if (str1_ch != str2_ch) {
return str1_ch - str2_ch;
}
}
if (len1 != len2) {
return len1 - len2;
}
else {
return 0;
}
}
public static void main(String args[])
{
String string1 = new String("TechGeekBuzz");
String string2 = new String("Tech");
System.out.println( Compare_String(string1, string2));
}
}
Multithreading in Java
In Java, we have multithreading. It allows our different methods to work concurrently so as to optimize the CPU utilization. As threads are the small processes inside a process, with multithreading, we can concurrently execute each thread for better performance.
Thread Life Cycle
New Thread ---> Runnable Thread ---> Running Thread -----> Block Thread --> Dead State
Exception Handling in Java
Exceptions are abnormal errors that often occur at run time due to some irregular input or conditions. These are the bugs that affect the efficiency and the working of the complete program. So, to tackle exceptions, we have some reserved keywords in Java that can catch and raise errors. Here are some Common Exception (Runtime Errors) you will see in Java:
Exceptions | Description |
ArithmeticException | Errors because of an arithmetic expression. |
ZeroDivisionException | Dividing a value with 0. |
ArrayIndexOutOfBoundException | No such index number. |
ArrayStoreException | When trying to insert a different data type in an array. |
FileNotFoundException | Accessing a file that does not exist. |
IOException | Input or output error. |
NullPointerException | Referencing a null object. |
NumberFormatException | When typecasting does not work. |
OutOfMemoryException | No memory for the variable. |
StringIndexOutOfBoundException | When there is no index for a particular string. |
try…..catch Statement in Java
Try and catch work similar to the if else statement. We use to try and catch statements to handle the exception. The try block contains the code that could contain some exception, and the catch block contains the code that will execute if an exception occurs in the try block. There is another keyword “ throw ” that we use to raise an error and terminate the complete program.
Example:
class Exception_Handaling
{
public static void main(String args[])
{
try
{
int x = 10/0;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
}
Finally Statement
With try and catch we can also use the finally statement. The main thing about the finally statement is that no matter what happens, whether the try and catch execute or not, the code inside the finally block will execute.
Example:
try
{
//try block
}
catch(<Exception>)
{
}
finally
{
//finally block
}
Throw
The throw is a special keyword in Java, which is used to raise an exception in the program. With the throw keyword, we can raise our own exceptions.
Files in Java
Though we have data structures to save data, there is one big problem with them. They are temporary and once the program is completely executed all the data is destroyed. So, to save the data, we use file handling.
In Java, we can create text files in which we can store the data. The text files that we have created can be read too, whenever we want. Once we have created a file, we can perform various operations on it which include, write on the file, read from the file, and delete the file.
Java File Streams
Stream determines the flow of data. When we deal with the file, the stream decides the path and pattern to follow for performing appropriate operations. In Java, we have 2 streams:
- Input Stream: With an input stream, we can read data from a file.
- Output Stream: The output stream accepts data from the user and writes it into the file.
File Reading and Writing Process
import java.io.File --> Create or Open File --> Read or Write in to file --> Close the file
Example:
// Create a file
File Obj = new File("file.txt");
// Write in the file
import java.io.FileWriter;
FileWriter write_file = new FileWriter("file.txt");
write_file.write(“ ”) // write in the file
write_file.close() //close file
//Read from a File:
File read_file = new File("File.txt");
System.out.println(read_file.nextLine());
read_file.close();
Memory Management in Java
Whenever we write the program, all of its functions and variables require some memory to execute. As such, the compiler provides 2 memory types to the different methods and variables. Java has a garbage collector that automatically allocates and deallocates memory.
Some important points about memory management in Java are:
- The Java compiler stores the program properties into either a heap or stack.
- The local variables and methods are stored in the stack memory.
- The instances are stored in the heap memory.
Conclusion
That sums up the Java cheat sheet. We have tried to comprehensively cover all the important Java concepts in this Java cheat sheet so that you get a complete Java reference.
Happy coding!
P.S. - Is something wrong or missing in this Java cheat sheet? Let us know in the comments so that we can mend it ASAP.
People are also reading:
- What is Java? Know more about Java
- Features of Java
- Core Java Interview Questions and Answers
- Java Frameworks for Web Development
- Download CSS Cheat Sheet
- Top 10 Java IDE
- What is Java Interface?
- Top Java Blogs, Newsletter & Websites
- Bootstrap Cheat Sheet
Leave a Comment on this Post