Java Cheat Sheet for Freshers and Experienced Developers (2023) - IQCode

Introduction to Java Programming Language

Java is a widely used high-level programming language known for its robustness, object-oriented nature, enhanced security, and easy-to-learn features. These features are commonly referred to as Java buzzwords. Java can be classified both as a platform and a programming language. It was founded by James Gosling, who is recognized as the "Father of Java." Before it was named Java, it was originally called Oak. However, since Oak was already a registered business, Gosling and his team decided to change the language's name to Java instead. Java makes it easy for programmers to write, compile, and debug code, which is widely used in developing reusable code and modular programs.

Java is an object-oriented programming language that reduces dependencies for better code quality. A Java program is written once and can be executed anywhere (WORA). The code is first compiled into bytecode, which can be run on any Java Virtual Machine. Java has a syntax that is similar to that of C/C++.

Interestingly, Java is also the name of an Indonesian island, where the first coffee, Java coffee, was grown. It was while enjoying coffee near his office that James Gosling came up with the name for his new programming language.

If you're interested in learning Java, we offer a comprehensive course covering all the basics to advanced concepts.

1. Java Terminology: Code - Java programs are written in code. It is the set of instructions written in the Java programming language. Bytecode - It is the intermediate language used to execute programs on any platform that supports the Java Virtual Machine (JVM). JVM - Java Virtual Machine interprets compiled Java byte codes for an underlying platform. JRE - Java Runtime Environment is the environment required for running Java applications on systems. It comprises Java Virtual Machine (JVM), core classes, and supporting files. JDK - Java Development Kit is required to develop applications in Java. It consists of the JRE, Java compiler, Java debugger, and other development tools.


// These are the primitive datatypes in Java
int num = 10;
double decimal = 3.14;
float ftNum = 1.732f;
boolean flag = true;
char ch = 'a';

// These are the non-primitive datatypes in Java
String str = "Hello World";
Integer objNum = 20;
Double objDec = 3.14;
Boolean objFlag = true;

In Java, there are two categories of datatypes, primitive and non-primitive. The primitive datatypes are the most basic datatypes in Java and they include

int

,

double

,

float

,

boolean

, and

char

. The non-primitive datatypes are derived from the primitive datatypes and they include

String

,

Integer

,

Double

, and

Boolean

.

The variable names used in this code are self-explanatory and follow Java naming conventions.

Access Modifiers in Java

In Java, access modifiers are keywords that determine the accessibility of classes, methods, and variables. There are four types of access modifiers in Java - public, private, protected, and default.

- Public: A public member can be accessed from any class or package. - Private: A private member can only be accessed within the class that defines it. - Protected: A protected member can be accessed within the same class, subclasses, and classes in the same package. - Default: A default member can be accessed within the same package.

It is important to choose the appropriate access modifier for each member in order to control the level of access to the program's classes, methods, and variables.

Identifiers in Java

Java identifiers are names used for classes, interfaces, variables, and methods. Identifiers can be composed of letters, numbers, underscores, and dollar signs. The first character can only be a letter, underscore, or dollar sign. Identifiers cannot include spaces or special characters such as @, #, or %.

It is important to choose descriptive and meaningful names for identifiers to improve the readability and maintainability of the code. Camel case is a popular convention for naming variables and methods, where the first word is lowercase and subsequent words start with a capital letter. Class names usually start with an uppercase letter and use camel case, while interface names start with an uppercase letter and use a combination of uppercase and lowercase letters.

Here's an example of creating a variable with a meaningful identifier:

int numberOfStudents = 25;

In this case, the variable is named numberOfStudents, which clearly indicates what it represents.

Control Flow in Java

Java provides various control flow statements to handle the flow of execution of a program. These statements allow us to make decisions, to repeat blocks of code, and to break out of loops. The control flow statements in Java include if-else, switch, for, while, and do-while loops. Let's take a look at an example of each:

//if-else statement
int x = 10;
if(x > 5) {
  System.out.println("x is greater than 5");
} else {
  System.out.println("x is less than or equal to 5");
}

//switch statement
char grade = 'B';
switch(grade) {
  case 'A':
    System.out.println("Excellent!");
    break;
  case 'B':
  case 'C':
    System.out.println("Well done");
    break;
  case 'D':
    System.out.println("You passed");
    break;
  case 'F':
    System.out.println("Better try again");
    break;
  default:
    System.out.println("Invalid grade");
}

//for loop
for(int i = 0; i < 5; i++) {
  System.out.println("The value of i is: " + i);
}

//while loop
int j = 0;
while(j < 5) {
  System.out.println("The value of j is: " + j);
  j++;
}

//do-while loop
int k = 0;
do {
  System.out.println("The value of k is: " + k);
  k++;
} while(k < 5);

By using these control flow statements effectively, we can create programs that are more flexible and efficient, and that can handle a wide variety of use cases.

Java Polymorphism

Code:

java
public class Animal {
    public void makeSound() {
        System.out.println("Animal is making a sound");
    }
}

public class Cat extends Animal {
    public void makeSound() {
        System.out.println("Meow");
    }
}

public class Dog extends Animal {
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        Animal myCat = new Cat();
        Animal myDog = new Dog();

        myAnimal.makeSound();
        myCat.makeSound();
        myDog.makeSound();
    }
}

The code above demonstrates the use of polymorphism in Java. The Animal class is the parent class, while the Cat and Dog classes are the child classes that inherit from the Animal class. Each class has its own implementation of the makeSound() method.

In the Main class, we create new instances of the Animal, Cat, and Dog classes. We then call the makeSound() method on each object, which results in different sounds being outputted to the console depending on the object type. This is the power of polymorphism – different objects can be treated as if they are of the same type, allowing for more modular and flexible code.

Abstract Classes and Interfaces

Code:


//Defining an abstract class
abstract class Vehicle {
  //Defining an abstract method
  public abstract void drive();
  
  //Defining a regular method
  public void stop() {
    System.out.println("Vehicle has stopped.");
  }
}

//Defining an interface
interface MusicPlayer {
  //Defining a method without a body
  void playSong();
}

//Implementing both an abstract class and an interface
class Car extends Vehicle implements MusicPlayer {
  //Implementing the abstract method from Vehicle class
  public void drive() {
    System.out.println("Car is being driven.");
  }

  //Implementing the method from MusicPlayer interface
  public void playSong() {
    System.out.println("Playing music in the car.");
  }
}

public class Main {
  public static void main(String[] args) {
    Car myCar = new Car();
    myCar.drive();
    myCar.playSong();
    myCar.stop();
  }
}

This code demonstrates the use of abstract classes and interfaces in Java. An abstract class is defined using the `abstract` keyword and can contain both abstract and regular methods. Abstract methods are declared without a body and must be implemented by any class that extends the abstract class.

An interface is defined using the `interface` keyword and can only contain abstract methods. Any class that implements an interface must provide a body for all methods declared in the interface.

In the code above, the abstract class `Vehicle` defines an abstract method `drive()` and a regular method `stop()`. The interface `MusicPlayer` declares an abstract method `playSong()`. The `Car` class extends `Vehicle` and implements `MusicPlayer`, thus implementing both the abstract method from `Vehicle` and the abstract method from `MusicPlayer`. Finally, in the `Main` class, an instance of `Car` is created and the defined methods are called.

Java Exception Handling

Code:

java
try {
    // code that may cause an exception
} catch (Exception e) {
    // code to handle the exception
} finally {
    // code that will always run regardless of whether an exception was caught or not
}

Explanation:

Java Exception Handling is a mechanism that allows you to handle potentially risky code. The structure of the code starts with the "try" block, which contains the potentially risky code to be attempted. If an exception is thrown, the "catch" block(s) will identify the exception(s) and handle them as needed. The "finally" block contains code that will always run regardless of whether an exception was caught or not.

It is important to properly handle exceptions in your code to ensure the program does not crash unexpectedly.

Java Multithreading

In Java, multithreading is a way of executing multiple threads simultaneously within a single process. Each thread is a lightweight sub-process that can run concurrently with other threads. This allows for greater efficiency and improved application performance.

There are two main ways to create a thread in Java: 1. Implement the Runnable interface and override the run() method. 2. Extend the Thread class and override the run() method.

Here's an example of creating a new thread using the Runnable interface:

class MyRunnable implements Runnable { public void run() { // code to be executed in this thread } }

public class Main { public static void main(String[] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); // start the thread } }

In this example, we create a new MyRunnable object that implements the Runnable interface. We then create a new Thread object and pass in the MyRunnable object as an argument to the constructor. Finally, we call the start() method on the Thread object to start the thread.

Multithreading can be used in a variety of applications, such as web servers and GUI applications, to improve performance and responsiveness. However, it's important to be aware of potential issues such as race conditions and deadlock when working with multiple threads.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.