Java Cheatsheet
Java Cheatsheet
long
Basics
long is another primitive data type related to integers. long takes up 64 bits of memory.
Basic syntax and functions from the Java programming language.
viewsCount = 3_123_456L;
Boilerplate
float
class HelloWorld{
public static void main(String args[]){ We represent basic fractional numbers in Java using the float type. This is a single-precision
System.out.println("Hello World"); decimal number. Which means if we get past six decimal points, this number becomes less
} precise and more of an estimate.
}
price = 100INR;
Showing Output
char
It will print something to the output console.
Char is a 16-bit integer representing a Unicode-encoded character.
System.out.println([text])
letter = 'A';
Taking Input
boolean
It will take string input from the user
The simplest primitive data type is boolean. It can contain only two values: true or false. It stores
import java.util.Scanner; //import scanner class its value in a single bit.
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.
short
If we want to save memory and byte is too small, we can use short.
byte
byte is a primitive data type it only takes up 8 bits of memory. short var2 = 786;
age = 18;
Comments
1/18 2/18
Home - CodeWithHarry Home - CodeWithHarry
A comment is the code that is not executed by the compiler, and the programmer uses it to keep It can be used to multiply add two numbers
track of the code.
int x = 10 * 3;
Single line comment
Constants int x = 10 % 3;
Constants are like a variable, except that their value never changes during program execution.
Augmented Operators
final float INTEREST_RATE = 0.04;
Addition assignment
Addition
var -= 10 // var = var - 10
3/18 4/18
Home - CodeWithHarry Home - CodeWithHarry
// int x = 45;
\t double var_name = x;
\\ double x = 165.48
int var_name = (int)x;
Single quote
Carriage return
if-else Statement
Inserts a carriage return in the text at this point.
if (condition) {
\r // If condition is True then this block will get executed
} else {
// If condition is False then this block will get executed
Double quote }
Ternary Operator
for-each Loop
It is shorthand of an if-else statement.
It allows a variable to be tested for equality against a list of values (cases). do-while Loop
It is an exit controlled loop. It is very similar to the while loop with one difference, i.e., the body
switch(expression) { of the do-while loop is executed at least once even if the condition is False
case a:
// code block
do {
break;
// body of loop
case b:
} while(textExpression)
// code block
break;
default: Break statement
// code block
} break keyword inside the loop is used to terminate the loop
break;
Iterative Statements
Iterative statements facilitate programmers to execute any block of code lines repeatedly and Continue statement
can be controlled as per conditions added by the coder.
7/18 8/18
Home - CodeWithHarry Home - CodeWithHarry
continue keyword skips the rest of the current iteration of the loop and returns to the starting Loop through an array
point of the loop
It allows us to iterate through each array element
continue;
String[] var_name = {''Harry", "Rohan", "Aakash"};
for (int i = 0; i < var_name.length; i++) {
Arrays System.out.println(var_name[i]);
}
Arrays are used to store multiple values in a single variable
Accessing an array
Declaration
Changing an element
Declaration of a method
Changing any element in an array
returnType methodName(parameters) {
String[] var_name = {''Harry", "Rohan", "Aakash"}; //statements
var_name[2] = "Shubham"; }
System.out.println(var_name.length); methodName(arguments);
9/18 10/18
Home - CodeWithHarry Home - CodeWithHarry
Method overloading means having multiple methods with the same name, but different String Length
parameters.
Returns the length of the string
class Calculate
{ String var_name = "Harry";
void sum (int x, int y) System.out.println("The length of the string is: " + var_name.length());
{
System.out.println("Sum is: "+(a+b)) ;
}
String Methods toUpperCase()
void sum (float x, float y)
Convert the string into uppercase
{
System.out.println("Sum is: "+(a+b));
String var_name = "Harry";
}
System.out.println(var_name.toUpperCase());
Public static void main (String[] args)
{
Calculate calc = new Calculate(); toLowerCase()
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. Convert the string into lowercase
}
} String var_name = ""Harry"";
System.out.println(var_name.toLowerCase());
Recursion
indexOf()
Recursion is when a function calls a copy of itself to work on a minor problem. And the function
that calls itself is known as the Recursive function. Returns the index of specified character from the string
Methods max() method A class can be defined as a template/blueprint that describes the behavior/state that the object
of its type support.
It is used to find the greater number among the two
class ClassName {
Math.max(25, 45); // Fields
// Methods
// Constructors
min() method
// Blocks
It is used to find the smaller number among the two }
Encapsulation is a mechanism of wrapping the data and code acting on the data together as a
sqrt() method single unit. In encapsulation, the variables of a class will be hidden from other classes and can be
accessed only through the methods of their current class.
It returns the square root of the supplied value
object
class Subclass-name extends Superclass-name
An object is an instance of a Class. {
//methods and fields
className object = new className(); }
13/18 14/18
Home - CodeWithHarry Home - CodeWithHarry
Polymorphism is the ability of an object to take on many forms. The most common use of
file.canRead()
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
createNewFile method
// A class with multiple methods with the same name
It creates an empty file
public class Adder {
// method 1
public void add(int a, int b) { file.createNewFile()
System.out.println(a + b);
}
canWrite method
// My main class
delete method
class MyMainClass {
public static void main(String[] args) { It deletes a file
Adder adder = new Adder(); // create a Adder object
adder.add(5, 4); // invoke method 1
file.delete()
adder.add(5, 4, 3); // invoke method 2
adder.add("5", "4"); // invoke method 3
} getName method
}
It returns the name of the file
file.getName()
File Operations
getAbsolutePath method
File handling refers to reading or writing data from files. Java provides some functions that allow
us to manipulate data in the files. It returns the absolute pathname of the file
canRead method
file.getAbsolutePath()
15/18 16/18
Home - CodeWithHarry Home - CodeWithHarry
}
length Method }
file.length()
Exception Handling
An exception is an unusual condition that results in an interruption in the flow of the program.
list Method
try-catch block
It returns an array of the files in the directory
try statement allow you to define a block of code to be tested for errors. catch block is used to
handle the exception.
file.list()
try {
mkdir method // Statements
}
It is used to create a new directory catch(Exception e) {
// Statements
file.mkdir() }
It is used to close the file finally code is executed whether an exception is handled or not.
file.close() try {
//Statements
}
To write something in the file
catch (ExceptionType1 e1) {
// catch block
import java.io.FileWriter; // Import the FileWriter class }
import java.io.IOException; // Import the IOException class to handle errors finally {
// finally block always executes
public class WriteToFile { }
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Laal Phool Neela Phool, Harry Bhaiya Beautiful");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
17/18 18/18