Java Cheatsheet
Basics
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([text])
Taking Input
It will take string input from the user
import Scanner; //import scanner class
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
age = 18;
long
long is another primitive data type related to integers. long takes up 64 bits of memory.
viewsCount = 3_123_456L;
float
We represent basic fractional numbers in Java using the float type. This is a single-precision decimal
Which means if we get past six decimal points, this number becomes less precise and more of an esti
price = 100INR;
char
Char is a 16-bit integer representing a Unicode-encoded character.
letter = 'A';
boolean
The simplest primitive data type is boolean. It can contain only two values: true or false. It stores its va
single bit.
isEligible = true;
int
int holds a wide range of non-fractional number values.
2 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
// It's a single line comment
Multi-line comment
/* It's a
multi-line
comment
*/
Constants
Constants are like a variable, except that their value never changes during program execution.
final float INTEREST_RATE = 0.04;
Arithmetic Expressions
These are the collection of literals and arithmetic operators.
Addition
It can be used to add two numbers
int x = 10 + 3;
Subtraction
It can be used to subtract two numbers
int x = 10 - 3;
3 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
It returns the remainder of the two numbers after division
int x = 10 % 3;
Augmented Operators
Addition assignment
var += 10 // var = var + 10
Subtraction assignment
var -= 10 // var = var - 10
Multiplication assignment
var *= 10 // var = var * 10
Division assignment
var /= 10 // var = var / 10
Modulus assignment
var %= 10 // var = var % 10
Escape Sequences
It is a sequence of characters starting with a backslash, and it doesn't represent itself when used insid
literal.
4 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
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
It means converting a lower data type into a higher
// int x = 45;
double var_name = x;
5 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
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
It is shorthand of an if-else statement.
6 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
switch(expression) {
case a:
// code block
break;
case b:
// code block
break;
default:
// code block
}
Iterative Statements
Iterative statements facilitate programmers to execute any block of code lines repeatedly and can be
controlled as per conditions added by the coder.
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)
}
7 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
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 th
continue;
Arrays
Arrays are used to store multiple values in a single variable
Declaring an array
Declaration of an array
String[] var_name;
Defining an array
Defining an array
String[] var_name = {''Harry", "Rohan", "Aakash"};
Accessing an array
Accessing the elements of an array
8 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
Loop through an array
It allows us to iterate through each array element
String[] var_name = {''Harry", "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
Methods are used to divide an extensive program into smaller pieces. It can be called multiple times to
provide reusability to the program.
9 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
Method Overloading
Method overloading means having multiple methods with the same name, but different parameters.
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 is when a function calls a copy of itself to work on a minor problem. And the function that ca
is known as the Recursive function.
void recurse()
{
... .. ...
recurse();
... .. ...
}
10 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
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));
Math Class
Math class allows you to perform mathematical operations.
11 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
Math.sqrt(144);
random() method
It is used to generate random numbers
Math.random(); //It will produce random number b/w 0.0 and 1.0
int random_num = (int)(Math.random() * 101); //Random num b/w 0 and 100
Object-Oriented Programming
It is a programming approach that primarily focuses on using objects and classes. The objects can be
real-world entities.
object
An object is an instance of a Class.
className object = new className();
class
A class can be defined as a template/blueprint that describes the behavior/state that the object of its ty
12 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
public class Person {
private String name; // using private access modifier
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Inheritance
Inheritance can be defined as the process where one class acquires the properties of another. With th
inheritance the information is made manageable in a hierarchical order.
class Subclass-name extends Superclass-name
{
//methods and fields
}
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphis
OOP occurs when a parent class reference is used to refer to a child class object.
13 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
// A class with multiple methods with the same name
public class Adder {
// method 1
public void add(int a, int b) {
System.out.println(a + b);
}
// method 2
public void add(int a, int b, int c) {
System.out.println(a + b + c);
}
// method 3
public void add(String a, String b) {
System.out.println(a + " + " + b);
}
}
// My main class
class MyMainClass {
public static void main(String[] args) {
Adder adder = new Adder(); // create a Adder object
adder.add(5, 4); // invoke method 1
adder.add(5, 4, 3); // invoke method 2
adder.add("5", "4"); // invoke method 3
}
}
14 of 17 23-07-2021, 08:40
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
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
15 of 17 23-07-2021, 08:40
mkdir method
It is used to create a new directory
file.mkdir()
close method
It is used to close the file
file.close()
To write something in the file
import FileWriter; // Import the FileWriter class
import IOException; // Import the IOException class to handle errors
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();
}
}
}
Exception Handling
Java Cheatsheet - CodeWithHarry https://www.codewithharry.com/blogpost/java-cheatsheet
finally code is executed whether an exception is handled or not.
try {
//Statements
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
You need to be logged in to post a comment!
Comments
No comments to display. Be the first person to post a comment!
17 of 17 23-07-2021, 08:40