Java Cheat Sheet: Things You Should Be Knowing

Java Cheat Sheet: Things You Should Be Knowing

Introduction

Java is an object-oriented programming language developed by James Gosling under Sun Microsystems and released in 1995. It is one of the most versatile programming languages present on the fact that Java code is platform-independent due to its property of converting compiled code into byte code.

This byte code is platform-independent and can be readily reused, moved, and scaled. There are multiple domains of use of Java. Some of the most popular applications that we use in our daily lives are built on Java.

It is supported by billions of devices at this moment and paves a way to develop highly reliable, scalable, production-ready applications with utmost ease.

Applications in Java Cheat Sheet

  • Mobile Applications
  • Desktop Applications
  • Web-based apps
  • Cloud-based apps
  • Distributed systems
  • Big data
  • Gaming applications
  • Enterprise-level apps

Some of the most popular applications that are based on Java are – Wikipedia Search, Hadoop (for big data), Minecraft (most popular game of 2009), Twitter, Square, Eclipse IDE, Intellij, Gmail.

The best features of Java language: Compiled and interpreted with platform-independent byte code, scalable and highly portable with reliable performance, supports multithreading, and Object-oriented.

Let’s get into the very basics of the Java programming language.

Data Typessizerange
int32-2,147,483,648 to 2,147,483,647
float323.4e-0.38 to 3.4e+0.38
byte8-128 to 127
long64-9,223,372,036,854,775,808 to9,223,372,036,854,775,807
char16Complete Unicode Character Set
booleanTrue and False
short16-32,768 to 32,767

Data Structures for Java Cheat Sheet

Arrays

These are contiguous memory allocation data structures that store elements linearly. Arrays are generally stored in stack memory although the new keyword can be used to store them in the heap. The basic syntax is given as:

int[] array = new int[10]; // stores 10 elements of integer type in the array

Objects and Classes

As Java is an Object-Oriented programming language it is more based on data. Java treats data as an object or entity which is defined by the structure of a class. A class is a block that encapsulates data members, methods and helps to realize an object.

The basic class declaration can be given as:

public static class Preparation{
        int months_left;
        String[] chapters;
        public int getMonths_left() {
            return months_left;
        }
        public void setMonths_left(int months_left) {
            this.months_left = months_left;
        }
        public String[] getChapters() {
            return chapters;
        }
        public void setChapters(String[] chapters) {
            this.chapters = chapters;
        }
    }

Methods

These are functions defined as class members and are responsible for performing some tasks like one of the most used methods is getters and setters used to get the value of the private members whereas setters are used to set the values of the private members. The basic definition can be seen in the above example too.

public int getMonths_left() {
            return months_left;
        }

Variables 

These are elements that store data in memory locations. There can be the following types of variables supported in Java.

Local VariablesGlobal VariablesStatic Variables
These are defined and declared inside a block of method or classThese variables are defined outside the class and are default associated to 0 valueThese are declared using the static keyword and are always global.
It can be accessed by methods and objects within the same class only or within the same method depending on the block where it is definedGlobal variables can be accessed from anywhere in the program but from the same package.Static variables have a single copy of memory throughout the program that is shared among all objects of the class.

Conditional Statements

These are the statements that are used to perform some task according to the conditions that are applied to the methods. There are 3 types of conditional statements present in Java:

If-elseSwitchLoop
Checks the condition in ‘if’ and then moves to ‘else’ block if the previous condition is falseThis is used to switch the control to other cases of logic, like if logic A is not true then moves to the next logic.Loops are used to repeatedly perform some task. There can be multiple types of loops like for loop, while loop, do-while loop.
Syntax:If(condition is true){//perform if block}else{//perform else block}Syntax:Int condition = 0;Switch(condtion){Case 0: //when condtion = 0;break;Case 1: //when condition = 1;break;Case 2: //when condition = 2;break;default}Syntax:For(int I =0; condtion for I; i++//change i){//block to perform}
While(condition is true){//perform the task and change the condtion}
Do{//perform task and change condtion until condition in while is false}while(condtion)

Object-Oriented Programming Concept

Every OOP language contains the main four features of OOPs i.e., Polymorphism, Abstraction, Inheritance, Encapsulation. These form the basics of any OOP language.

Polymorphism

 It is defined as the property by which the same entity can be used in different forms. The methods can be used for different tasks. Polymorphism is achieved by the concept of method overloading and method overriding.

  • Method Overloading: When the same method in a class is defined with different parameters or return types but the same name then the method is termed as an overloaded method.
    • Example: void int study(int hours){return hours}
    • void String study(String subject){return subject}
  • Method Overriding: In method overriding, the subclass of a superclass inherits methods from the superclass and redefines this method, which is known as method overriding. Example:
public class MainCN {
    public static class Preparation{
        int months_left = 0; 
        public int getMonths_left() {
            System.out.println("this preparation class");
             return months_left;
        }      
    }
    public static class CodingNinja extends Preparation{
        int months = 5;
        public int getMonths_left(){
            System.out.println("this is CodingNinja class");
            return months;
        }
    }
    public static void main(String[] args) {
        CodingNinja obj = new CodingNinja();
        obj.getMonths_left(); //this is CodingNinja class

        Preparation obj1 = new Preparation();
        obj1.getMonths_left(); //this preparation class

        Preparation obj2 = new CodingNinja();
        obj2.getMonths_left(); //this is CodingNinja class
    }
}

Output: 
this is CodingNinja class
this preparation class
this is CodingNinja class

Inheritance

This is the property of any class to inherit methods and functions from the superclass(another class from which it is deriving). There can be multiple forms of inheritance like:

  • Single level Inheritance: There is only one child class to one parent class.
  • Multilevel Inheritance: It goes on the hierarchical concept of inheriting. 
  • Multiple Inheritance: When there are multiple parents of a single child then it is called multiple inheritances. In java, this is supported by Interface. 

Example: 

public class MainCN {
    public static class Preparation{
        int months_left = 0; 
        public int getMonths_left(){
            return 1;
        };
    }
    public static class CodingNinja extends Preparation{  //single level inheritance
        int months = 5;
        public int getMonths_left(){
            System.out.println("this is CodingNinja class");
            return months; //this method is inherited from the parent class
        }
    }
    public static void main(String[] args) {
        CodingNinja obj = new CodingNinja();
        obj.getMonths_left(); //this is CodingNinja method which defines 
    }
}

Abstraction

 The concept of showing only the important information rather than the minute complicated details is known as abstraction. In Java abstraction is achieved by using Abstract classes.

Abstract Class: These are the classes that are generally shared among its subclass but the definitions of methods inside these classes are not necessary. Each of the subclasses can now implement the methods of the superclass. The abstract class may have some methods defined also. In such cases, the defined methods can be overridden.

Example: 

public class MainCN {
    public abstract static class Preparation{
        int months_left = 0; 
        public abstract int getMonths_left();
    }
    public static class CodingNinja extends Preparation{
        int months = 5;
        public int getMonths_left(){
            System.out.println("this is CodingNinja class");
            return months;
        }
    }
    public static void main(String[] args) {
        CodingNinja obj = new CodingNinja();
        obj.getMonths_left(); //this is CodingNinja method which defines 
                                // the abstract method of Preparation
    }
}

Output:
this is CodingNinja class

Interfaces

 An interface is a class that is fully abstracted which means all the methods in the Interface class are not defined. These methods can be inherited by various subclasses and hence multiple inheritances can also be supported. Variables inside Interfaces are public, final, static, although the classes inheriting interface methods can also have their methods.

Example:

public class MainCN {
    interface Preparation{
        public int getMonths_left();
    }
    public static class CodingNinja implements Preparation{
        int months = 5;
        public int getMonths_left(){
            System.out.println("this is CodingNinja class");
            return months;
        }
    }
    public static void main(String[] args) {
        CodingNinja obj = new CodingNinja();
        obj.getMonths_left(); //this is CodingNinja method which defines 
    }
}

Encapsulation

It refers to the concept of wrapping up the data members and methods into a class and that can be accessed using the instances of the class being created as required. The whole concept of classes and objects revolves around this encapsulation and it provides better security too.

Example:

Public static class main(String[] args){
	Int datamember;
	//objects can also be declared here
}

String Classes in Java

Strings in Java are treated as non-primitive data types that store a sequence of characters. In java, there are two main classes to handle strings – String Buffer, String Builder.

String BufferString Builder
This is synchronisedString Builder is not synchronised
Less efficient than String BuilderMore efficient
Multithreading is supportedThread-safe but slower

Exception Handling in Java

Java provides a wide range of techniques to handle errors and abnormality. It has exception handling classes that throw an error whenever encountered and also provides the message for the error. It also supports the use of a try-catch block which catches the most fault-prone block of code and can simply move over it by moving to the catch block. It also uses the Finally keyword to handle exceptions and this statement is always executed no matter if the error is caught or not. 

Example:

Try{ do something faulty}
Catch{display error and move over}
Finally{always executed }

Java Collection Framework

Java has this really useful support of advanced data structures through the Collections framework which has interfaces of the most useful data structures and these can be implemented using proper classes. These include ArrayList, HashMaps, Set, Queue, sorted map, etc.

In hashmap, there can be three main types of implementations:

HashMapTreeMapLinkedHashMap
Stores in random orderStores the values in sorted orderStored in order of their insertion
Insertion, lookup in O(1)Insertion, lookup in O(logn)Insertion, lookup in O(1)

Frequently Asked Questions

What is a cheat sheet in Java?

This cheat sheet in java provides a roadmap and a brief intro to every important topic in Java.

What are the Java commands?

Java commands are the very basic commands used to know about the version, components of the java installed in a particular machine like java –version.

Provide a Java summary?

Java is a widely used language that provides support for various domains of technology. Most of the legacy code of popular applications is written in Java as it is highly scalable and reliable.

What is useful Java?

Java is useful in various applications like mobile application development, web development, server development, desktop applications, etc.

Does Windows 10 need Java?

Java is platform-independent due to its compiled code of byte code which can be executed in any machine with the help of Java Virtual Machine.

Key Takeaways

Java is a powerful general-purpose object-oriented programming language used to develop mobile applications, web applications, big data processing, embedded applications, and is supported by billions of devices worldwide.

Due to its platform-independent nature, Java is preferred for enterprise-level application development, server-side development, etc. If you are someone who is on the journey of learning this amazing language then keep this cheat sheet handy for easy and fast reference.

Hope this Java cheat sheet helps you to get a reference of the important concepts in the Java programming language.

By Aniruddha Guin

Exit mobile version