Java Programming Cheatsheet

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.

Basic syntax and functions from the Java programming language.

Boilerplate

class HelloWorld{ 
public static void main(String args[]){ 
System.out.println("Hello World"); 
} 
}

Showing Output

It will print something to the output console.

System.out.println(); or

System.out.print(); or

System.out.printf();

Taking Input

It will take string input from the user

import java.util.Scanner; //import scanner class

// create an object of Scanner class
Scanner input = new Scanner(System.in);

// take input from the user
String varName = input.nextLine();

Primitive Type Variables

The eight primitives defined in Java are int, byte, short, long, float, double, boolean, and char those aren’t considered objects and represent raw values.

byte

byte is a primitive data type it only takes up 8 bits of memory.

age = 16;

long

The long data type is a 64-bit two’s complement integer.

viewsCount = 6_124_476N;

float

The Java float keyword is a primitive data type. It is a single-precision 32-bit IEEE 754 floating point.

price = 300INR;

char

The char data type is a single 16-bit Unicode character.

letter = 'S';

boolean

It is used to store only two possible values, either true or false.

isEligible = true;

isEligible = false;

int

The int data type is a 32-bit signed two’s complement integer.

var1 = 128;

Short

The short data type is a 16-bit signed two’s complement integer

short var2 = 512;

Comments

A comment is the code that is not executed by the compiler, and the programmer uses it to keep track of the code.

Single line comment

// It's a single line comment

Multi-line comment

/* It's a 
multi-line
comment
*/

Constants

A value which is fixed and does not change during the execution of a program is called constants in java.

final float INTEREST_RATE = 0.17;

Arithmetic Expressions

These are the collection of literals and arithmetic operators.

Addition

It can be used to add two numbers

int x = 12 + 5;  

Subtraction

It can be used to subtract two numbers

int x = 12 - 5;

Multiplication

It can be used to multiply add two numbers

int x = 12 * 5;

Division

It can be used to divide two numbers

int x = 12 / 5;
float x = (float)12 / (float)5;

Modulo Remainder

It returns the remainder of the two numbers after division

int x = 12 % 4;

Augmented Operators

Addition assignment

var += 20 // var = var + 20

Subtraction assignment

var -= 20 // var = var - 20

Multiplication assignment

var *= 20 // var = var * 20

Division assignment

var /= 20 // var = var / 20

Modulus assignment

var %= 20 // var = var % 20

Escape Sequences

Escape sequences are used to signal an alternative interpretation of a series of characters.

Tab

Inserts a tab in the text at this point.

\t

Backslash

It adds a backslash

\\

Single quote

It adds a single quotation mark

\'

Question mark

It adds a question mark

\?

Carriage return

Inserts a carriage return in the text at this point.

\r

Double quote

It adds a double quotation mark

\"

Type Casting

Type Casting is a process of converting one data type into another

Widening Type Casting

This type of casting takes place when two data types are automatically converted

// int x = 55;
double var_name = x;

Narrowing Type Casting

Converting a higher datatype to a lower datatype 

double x = 169.69
int var_name = (int)x;

Decision Control Statements

Conditional statements are used to perform operations based on some condition.

if Statement

if (condition) {
// block of code to be executed if the condition is true
}

if-else Statement

if (condition) {
// If condition is True then this block will get executed
} else {
// If condition is False then this block will get executed
}

if else-if Statement

if (condition1) {
// Codes
}
else if(condition2) {
// Codes
}
else if (condition3) {
// Codes
}
else {
// Codes
}

Ternary Operator

A ternary operator evaluates the test condition and executes a block of code based on the result of the condition

variable = (condition) ? expressionTrue : expressionFalse;

Switch Statements

The switch statement or switch case in java is a multi-way branch statement

switch(expression) {
case a:
// code block
break;
case b:
// code block
break;
default:
// code block
}

Iterative Statements

The java programming language provides a set of iterative statements that are used to execute a statement or a block of statements repeatedly as long as the given condition is true.

while Loop

It iterates the block of code as long as a specified condition is True

while (condition) {
// code block
}

for Loop

for loop is used to run a block of code several times

for (initialization; termination; increment) {
statement(s)
}

for-each Loop

for(dataType item : array) {
...
}

do-while Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true

do {
// body of loop
} while(textExpression)

Break statement

break keyword inside the loop is used to terminate the loop

break;

Continue statement

continue keyword skips the rest of the current iteration of the loop and returns to the starting point of the loop

continue;

Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Declaring an array

Declaration of an array

String[] var_name;

Defining an array

Defining an array

String[] var_name = {''Saransh", "Saurav", "Sonia"};

Accessing an array

Accessing the elements of an array

String[] var_name = {"Richa", "Rohan", "Rohit"};
System.out.println(var_name[index]);

Changing an element

Changing any element in an array

String[] var_name = {"Neha", "Nupur", "Naman"};
var_name[2] = "Nil";

Array length

It gives the length of the array

System.out.println(var_name.length);

Loop through an array

It allows us to iterate through each array element

String[] var_name = {"Raja", "Rohan", "Aakash"};
for (int i = 0; i < var_name.length; i++) {
System.out.println(var_name[i]);
}

Multi-dimensional Arrays

Arrays can be 1-D, 2-D or multi-dimensional.

// Creating a 2x3 array (two rows, three columns) 
int[2][3] matrix = new int[2][3]; 
matrix[0][0] = 10; 
// Shortcut 
int[2][3] matrix = { 
{ 1, 2, 3 }, 
{ 4, 5, 6 } 
};

Methods

method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. I

Declaration

Declaration of a method

returnType methodName(parameters) {
//statements
}

Calling a method

Calling a method

methodName(arguments);

Method Overloading

In Java, method overriding occurs when a subclass (child class) has the same method as the parent class.

class Calculate
{
void sum (int x, int y)
{
System.out.println("Sum is: "+(a+b)) ;
}
void sum (float x, float y)
{
System.out.println("Sum is: "+(a+b));
}
Public static void main (String[] args)
{
Calculate calc = new Calculate();
calc.sum (5,4); //sum(int x, int y) is method is called.
calc.sum (1.2f, 5.6f); //sum(float x, float y) is called.
}
}

Recursion

Recursion in java is a process in which a method calls itself continuously.

void recurse()
{
... .. ...
recurse();
... .. ...
}

Strings

It is a collection of characters surrounded by double quotes.

Creating String Variable

String var_name = "Hello World";

String Length

Returns the length of the string

String var_name = "Harry";
System.out.println("The length of the string is: " + var_name.length());

String Methods toUpperCase()

Convert the string into uppercase

String var_name = "Harry";
System.out.println(var_name.toUpperCase());

toLowerCase()

Convert the string into lowercase

String var_name = ""Harry"";
System.out.println(var_name.toLowerCase());

indexOf()

Returns the index of specified character from the string

String var_name = "Harry";
System.out.println(var_name.indexOf("a"));

concat()

Used to concatenate two strings

String var1 = "Harry";
String var2 = "Bhai";
System.out.println(var1.concat(var2));

File Operations

File handling refers to reading or writing data from files. Java provides some functions that allow us to manipulate data in the files.

canRead method

Checks whether the file is readable or not

file.canRead()

createNewFile method

It creates an empty file

file.createNewFile()

canWrite method

Checks whether the file is writable or not

file.canWrite()

exists method

Checks whether the file exists

file.exists()

delete method

It deletes a file

file.delete()

getName method

It returns the name of the file

file.getName()

getAbsolutePath method

It returns the absolute pathname of the file

file.getAbsolutePath()

length Method

It returns the size of the file in bytes

file.length()

list Method

It returns an array of the files in the directory

file.list()

Exception Handling

Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

try-catch block

try statement allow you to define a block of code to be tested for errors. catch block is used to handle the exception.

try {
// Statements
}
catch(Exception e) {
// Statements
}

finally block

finally code is executed whether an exception is handled or not.

try {
//Statements
}
catch (ExceptionType1 e1) { 
// catch block
}
finally {
// finally block always executes
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saransh Saurav

Saransh Saurav

Articles: 67

Leave a Reply

Your email address will not be published. Required fields are marked *