Java Cheatsheet

Java Development Kit - Compilter + Java Runtime Environment + Library of classes

How Java code gets executed?

  1. Java code (.java) enters Java compiler.

  2. Java compiler compiles it down to Java Bytecode (.class) [a cross platform format]

  3. When we run Java code, JVM gets loaded into memory.

  4. Bytecode -> JVM -> Native code for the OS.

Architecture of Java Applications - Methods β†’ Combine related methods in Classes β†’ Combine related classes in Packages

Every Java Program should have at least one class that contains the main function, i.e. the main class.

Access Modifier

In Java, all classes and methods should have an access modifier which determines if other classes and methods of the program can access them. Example - Access_Modifier class/returnType ClassName/FunctionName

  • Default Integer type in Java is int, to represent a long append a L to the value. Example - long countViews = 8202984L

  • Default Floating point type is double, to represent a float append a F to the value. Example - float price = 10.99F

  • Strings are immutable.

Types of Variables : Primitive and Reference Primitive : byte β†’ 1 β†’ [-128,127] , short β†’ 2 β†’ [-32k, 32k] , int β†’ 4 β†’ [-2B, 2B] , long β†’ 8 , float β†’ 4 , double β†’ 8 , char β†’ 2 , boolean β†’ 1

public static void main (String args[])

  1. Public - Access Modifier. Main method must be public so that JVM can access it from outside the class as it is not present in the current class.

  2. Static - Any static member can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions:

    1. They can only directly call other static methods.

    2. They can only directly access static data.

    3. They cannot refer to this or super in any way.

  3. Void - The main function in Java has to be void. C and C++ programs which can return int from main are processes of the Operating System. The int value returned is the exit code. Parent process of any child process keeps waiting for the exit status of the child. And after receiving the exit status of the child, cleans up the child process from the process table and frees the resources allocated to it. Which is why it becomes mandatory for C and C++ programs(which are processes of OS) to pass its exit status from main explicitly or implicitly.

  4. However, The java program runs as β€˜main thread’ in JVM. The Java program is not even a process of Operating System directly. There is no direct interaction between Java program and Operating System. There is no direct allocation of resources to Java programs directly, or the Java program does not occupy any place in the process table. Whom should it return exit status to, then. Which is why the main method of Java is designed not to return int or exit status. But JVM is a process of an operating system, and JVM can be terminated with certain exit status. With help of java.lang.Runtime.exit(int status) or System.exit(int status)

  5. Main - It is the identifier that the JVM looks for as the starting point of the Java program. It’s not a keyword.

  6. String args[] - Stores Java CLI Arguments. You can use anything in place of args[]

System is a class in java.lang package

Out is a variable static member of the System class

println() is a method of java.io.PrintStream

Scanner is a class in java.util package

Encapsulation - A technique of wrapping the data and the code. Variables of a class are always hidden from other classes. They can only be accessed using the methods (getters and setters) of the current class.

Abstraction - The abstract keyword is a non-access modifier, used for classes and methods.

Inheritance - Provides Reusability. Deriving a new class from the earlier existing class. New class inherits features from old class.

Polymorphism - Provides a way for an entity to behave in several forms.

If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.

Static Keyword - Static methods in Java are resolved at compile time. Since method overloading is a part of Runtime Polymorphism, so static methods can’t be overridden. Abstract Methods can’t be static. Static Methods cannot use super or this keyword.

Why is the Java main method static?

It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then calls the main method that will lead to the problem of extra memory allocation.

Overriding - Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent Classes. Method Overriding is one of the ways by which Java can achieve Runtime Polymorphism. The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in the subclass. Doing so, will generate compile-time error. private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of the parent class.

Method OverloadingMethod Overriding

Static Binding

Child class Method will override the Parent Class Method - Dynamic Binding

EXCEPTION

Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.

BUILT IN EXCEPTION

  1. ArithmeticException - It is thrown when an exceptional condition has occurred in an arithmetic operation.

  2. ArrayIndexOutOfBoundsException - It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

  3. ClassNotFoundException - This Exception is raised when we try to access a class whose definition is not found.

  4. FileNotFoundException - This Exception is raised when a file is not accessible or does not open.

  5. IOException - It is thrown when an input-output operation failed or interrupted.

  6. InterruptedException - It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.

  7. NoSuchFieldException - It is thrown when a class does not contain the field (or variable) specified.

  8. NoSuchMethodException - It is thrown when accessing a method which is not found.

  9. NullPointerException - This exception is raised when referring to the members of a null object. Null represents nothing.

  10. NumberFormatException - This exception is raised when a method could not convert a string into a numeric format.

  11. RuntimeException - This represents any exception which occurs during runtime.

  12. StringIndexOutOfBoundsException - It is thrown by String class methods to indicate that an index is either negative than the size of the string

PACKAGES

Packages are Java’s way of grouping a number of related classes or interfaces into a single unit. Six foundation Java packages are - java.lang (Contains classes for primitive types, strings, packages

Last updated