Java Cheatsheet _ CodeWithHarry
Java Cheatsheet _ CodeWithHarry
Java Cheatsheet
Haris Ali Khan
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.
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Taking Input
It will take string input from the user
java.
import java .util
util.
.Scanner;
class HelloWorld
{
public static void main(String args[])
{
Scannner sc=new Scanner(System.in);
String name=sc.nextLine();
System.out.println(name);
}
}
java.
import java .util
util.
.Scanner;
class HelloWorld
{
public static void main(String args[])
{
Scannner sc=new Scanner(System.in);
int x=sc.nextInt();
System.out.println(x);
https://www.codewithharry.com/blogpost/java-cheatsheet/ 1/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
}
}
java.
import java .util
util.
.Scanner
Scanner;
;
class HelloWorld
{
main(
public static void main (String args
args[
[])
{
sc=
Scannner sc =new Scanner
Scanner((System
System.
.in
in)
);
x=
int x=sc
sc..nextFloat
nextFloat(();
System.
System.out
out.
.println
println(
(x);
}
}
java.
import java .util
util.
.Scanner
Scanner;;
class HelloWorld
{
public static void main(
main(String args
args[
[])
{
Scannner scsc==new Scanner
Scanner((System
System.
.in
in)
);
double xx=
=sc
sc..nextDouble
nextDouble(
();
System.
System .out
out..println
println(
(x);
}
}
byte
byte is a primitive data type it only takes up 8 bits of memory.
class HelloWorld
{
main(
public static void main(String args
args[
[])
{
age=
byte age =18
18;;
System.
System.out
out.
.println
println(
(age
age)
);
}
}
long
long is another primitive data type related to integers. long takes up 64 bits of memory.
class HelloWorld
{
public static void main
main(
(String args
args[
[])
{
var=
long var =900.0
900.0;;
System.
System.out
out.
.println
println(
(age
age)
);
}
}
float
https://www.codewithharry.com/blogpost/java-cheatsheet/ 2/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
We represent basic fractional numbers in Java using the float type. This is a single-precision decimal number. Which
means if we get past six decimal points, this number becomes less precise and more of an estimate.
class HelloWorld
{
public static void main(String args[])
{
float price=100.05;
System.out.println(price);
}
}
char
Char is a 16-bit integer representing a Unicode-encoded character.
class HelloWorld
{
public static void main(String args[])
{
char letter='A';
System.out.println(letter);
}
}
int
int holds a wide range of non-fractional number values.
class HelloWorld
{
public static void main(String args[])
{
int var1=256;
System.out.println(var1);
}
}
short
If we want to save memory and byte is too small, we can use short.
class HelloWorld
{
public static void main(String args[])
{
short var2=5666;
System.out.println(var2);
}
}
Comments
A comment is the code that is not executed by the compiler, and the programmer uses it to keep track of the code.
Multi-line comment
https://www.codewithharry.com/blogpost/java-cheatsheet/ 3/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
/* It's a
multi-line
comment
*/
Constants
Constants are like a variable, except that their value never changes during program execution.
3.14;
final double PI = 3.14;
main(
public static void main (String
String[
[] args
args)) {
System.
System.out
out.
.println
println(
("Value of PI: " + PIPI)
);
}
}
Arithmetic Expressions
These are the collection of literals and arithmetic operators.
Addition
It can be used to add two numbers
Subtraction
It can be used to subtract two numbers
Multiplication
https://www.codewithharry.com/blogpost/java-cheatsheet/ 4/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
It can be used to multiply add two numbers
Division
It can be used to divide two numbers
Modulo Remainder
It returns the remainder of the two numbers after division
Augmented Operators
Addition assignment
Subtraction assignment
https://www.codewithharry.com/blogpost/java-cheatsheet/ 5/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
}
}
Multiplication assignment
Division assignment
Modulus assignment
Escape Sequences
It is a sequence of characters starting with a backslash, and it doesn't represent itself when used inside string literal.
Tab
It gives a tab space
Backslash
It adds a backslash
https://www.codewithharry.com/blogpost/java-cheatsheet/ 6/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
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.
Double quote
It adds a double quotation mark
Type Casting
Type Casting is a process of converting one data type into another
https://www.codewithharry.com/blogpost/java-cheatsheet/ 7/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
class HelloWorld
{
public static void main(String args[])
{
int x = 45;
double var_name = x;
System.out.println(var_name);
}
class HelloWorld
{
public static void main(String args[])
{
double x = 40005;
int var_name = x;
System.out.println(var_name);
}
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
}
https://www.codewithharry.com/blogpost/java-cheatsheet/ 8/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
else {
// Codes
}
Ternary Operator
It is shorthand of an if-else statement.
Syntax
Example
Switch Statements
It allows a variable to be tested for equality against a list of values (cases).
class SwitchExample
{
public static void main(String args[])
{
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
https://www.codewithharry.com/blogpost/java-cheatsheet/ 9/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
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
for Loop
for loop is used to run a block of code several times
class HelloWorld
{
public static void main(String args[])
{
int i;
for(i=1;i<100;i++)
{
System.out.println(i);
}
}
for-each Loop
do-while Loop
It is an exit controlled loop. It is very similar to the while loop with one difference, i.e., the body of the do-while loop is
executed at least once even if the condition is False
https://www.codewithharry.com/blogpost/java-cheatsheet/ 10/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
{
System.out.println(i);
i++;
}while(i<=100);
}
}
Break statement
break keyword inside the loop is used to terminate the loop
class HelloWorld
{
public static void main(String args[])
{
int i;
for(i=1;i<100;i++)
{
System.out.println(i);
if(i==50)
break;
}
}
Continue statement
continue keyword skips the rest of the current iteration of the loop and returns to the starting point of the loop
class HelloWorld
{
public static void main(String args[])
{
int i;
for(i=1;i<100;i++)
{
System.out.println(i);
if(i==50)
continue;
}
}
Arrays
Arrays are used to store multiple values in a single variable
Declaring an array
Declaration of an array
Defining an array
https://www.codewithharry.com/blogpost/java-cheatsheet/ 11/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
Defining an array
Accessing an array
Accessing the elements of an array
Changing an element
Changing any element in an array
Array length
It gives the length of the array
https://www.codewithharry.com/blogpost/java-cheatsheet/ 12/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
}
}
Multi-dimensional Arrays
Arrays can be 1-D, 2-D or multi-dimensional.
Methods
Methods are used to divide an extensive program into smaller pieces. It can be called multiple times to provide
reusability to the program.
Declaration
Declaration of a method
methodName(
returnType methodName(parameters
parameters)
) {
//statements
}
Calling a method
Calling a method
methodName(
methodName(arguments
arguments)
);
Example
findEvenOdd(
public static void findEvenOdd(int num
num)
)
{
//method body
if(
if(num
num%
%2==
==00)
System.
System.out
out.
.println
println(
(num
num+
+" is even")
even");
else
System.
System.out
out.
.println
println(
(num
num+
+" is odd")
odd");
}
import java.
java.util
util..Scanner
Scanner;;
public class EvenOdd
{
args[
public static void main (String args[])
https://www.codewithharry.com/blogpost/java-cheatsheet/ 13/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
{
//creating Scanner class object
scan=
Scanner scan=new Scanner
Scanner(
(System
System.
.in
in)
);
System.
System.out
out.
.print
print(
("Enter the number: ")
");
//reading value from the user
num=
int num =scan
scan..nextInt
nextInt(
();
//method calling
findEvenOdd(
findEvenOdd (num
num));
}
Method Overloading
Method overloading means having multiple methods with the same name, but different parameters.
class Calculate
{
void sum (int x x,
, int yy)
)
{
System.
System.out
out.
.println
println(
("Sum is: "+
"+(a+b)) ;
}
x,
void sum (float x, float y
y)
)
{
System.
System.out
out.
.println
println(
("Sum is: ""+
+(a+b));
}
public static void main (String
String[
[] args
args)
)
{
Calculate(
Calculate calc = new Calculate ();
calc.
calc.sum (5,4); //sum(int x, int y) is method is called.
calc.
calc.sum (1.2f
1.2f,
, 5.6f
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 calls itself is known
as the Recursive function.
recurse(
void recurse()
{
recurse(
recurse();
}
Strings
It is a collection of characters surrounded by double quotes.
String Length
Returns the length of the string
https://www.codewithharry.com/blogpost/java-cheatsheet/ 14/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
}
}
toLowerCase()
Convert the string into lowercase
indexOf()
Returns the index of specified character from the string
concat()
Used to concatenate two strings
Math Class
Math class allows you to perform mathematical operations.
https://www.codewithharry.com/blogpost/java-cheatsheet/ 15/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
It is used to find the greater number among the two
min() method
It is used to find the smaller number among the two
sqrt() method
It returns the square root of the supplied value
random() method
It is used to generate random numbers
Math.
Math.random
random((); //It will produce random number b/w 0.0 and 1.0
https://www.codewithharry.com/blogpost/java-cheatsheet/ 16/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
Object-Oriented Programming
It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world
entities.
class
A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.
class ClassName {
// Fields
// Methods
// Constructors
// Blocks
}
object of class
An object is an instance of a Class.
Encapsulation
Encapsulation is a mechanism of wrapping the data and code acting on the data together as a 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.
// Getter
public String getName(
getName()
{
name;
return name ;
}
// Setter
public void setName(
setName(String newName
newName)
)
{
this.
this .name = newName
newName;
;
}
}
Inheritance
Inheritance can be defined as the process where one class acquires the properties of another. With the use of
inheritance the information is made manageable in a hierarchical order.
https://www.codewithharry.com/blogpost/java-cheatsheet/ 17/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
Subclass-
class Subclass-name extends Superclass
Superclass-
-name
{
//methods and fields
}
Example
class Employee
{
float salary=
salary=40000;
40000;
}
class Programmer extends Employee
{
int bonus=
bonus=10000;
10000;
public static void main(
main(String args[
args[])
{
Programmer p=
p=new Programmer(
Programmer();
System.
System out println("Programmer salary is:"+
. out.
. println( is:"+p.salary)
salary);
System.
. out.
. println(
System out println ( "Bonus of Programmer is:"+
is:" p.bonus)
+ bonus);
}
}
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs
when a parent class reference is used to refer to a child class object.
// 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
dd add
dd("5" "4"); // invoke
i k method
th d 3
https://www.codewithharry.com/blogpost/java-cheatsheet/ 18/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
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.
Assume that we have created the file “D:\\Example.txt”
canRead method
Checks whether the file is readable or not
java.
import java .io
io.
.*;
createNewFile method
It creates an empty file
java.
import java .io
io.
.*;
try {
https://www.codewithharry.com/blogpost/java-cheatsheet/ 19/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
System.
System.err
err.
.println
println(
(e);
}
}
}
canWrite method
Checks whether the file is writable or not
java.
import java .io
io.
.*;
exists method
Checks whether the file exists
java.
import java .io
io.
.*;
// Main class
public class FileOperations {
main(
public static void main(String args
args[[])
{
File(
File f = new File("D:\\Example.txt"
"D:\\Example.txt"));
delete method
It deletes a file
java.
import java .io
io.
.*;
https://www.codewithharry.com/blogpost/java-cheatsheet/ 20/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
if (file
file.
.delete
delete(()) {
System.
System .out
out.
.println
println(
("File deleted successfully")
successfully");
}
else {
System.
System.out
out.
.println
println(
("Failed to delete the file")
file");
}
}
}
getName method
It returns the name of the file
import java.io.*;
getAbsolutePath method
It returns the absolute pathname of the file
import java.io.*;
https://www.codewithharry.com/blogpost/java-cheatsheet/ 21/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
}
}
length Method
It returns the size of the file in bytes
import java.io.*;
list Method
It returns an array of the files in the directory
import java.io.*;
System.out.println("Files are:");
mkdir method
It is used to create a new directory
import java.io.*;
https://www.codewithharry.com/blogpost/java-cheatsheet/ 22/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
public static void main(String args[])
{
// create an abstract pathname (File object)
File f = new File("D:\\program");
close method
It is used to close the file
import java.io.File;
import java.io.FileInputStream;
try {
FileInputStream input= new FileInputStream(file);
int character;
// read character by character by default
// read() function return int between
// 0 and 255.
input.close();
System.out.println("File is Closed");
System.out.println(
"Now we will again try to read");
while ((character = input.read()) != -1) {
System.out.print((char)character);
}
}
catch
t h (Exception
E ti e) {
https://www.codewithharry.com/blogpost/java-cheatsheet/ 23/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
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
An exception is an unusual condition that results in an interruption in the flow of the program.
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
}
Example
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
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
}
https://www.codewithharry.com/blogpost/java-cheatsheet/ 24/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
Example
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
Post Comment
Comments (28)
prince1509patel_gm 2024-05-28
REPLY
aryan754289_gm 2024-05-10
download problem
REPLY
dipenvaja841_gm 2024-05-08
REPLY
jatinnama100_gm 2024-04-30
REPLY
samesahu19_gm 2024-04-29
REPLY
https://www.codewithharry.com/blogpost/java-cheatsheet/ 25/28
5/29/24, 4:18 PM Java Cheatsheet | CodeWithHarry
shwetayadav530 2024-04-29
REPLY
raviprakash8808546773_gm 2024-04-27
thakursiddharthsingh007_gm 2024-04-23
download error
REPLY
abhijeeetkushwaha_gm 2024-04-23
download problem
REPLY
abhijeeetkushwaha_gm 2024-04-23
Salute #CodeWithHarry
REPLY
modasirkhan958_gm 2024-03-20
pradeepyad089_gm 2024-02-10
jfv,dk,dl,vdlvld
REPLY
parassainipatakmajra123_gm 2023-12-29
bhaiya code mai galti hai Get output from user wale section mai
Scanner ki spelling mai tripple "n" hai.
REPLY
karpit757_gm 2023-12-28
REPLY
balajirathod9445_gm 2023-12-11
public class Harry { public static void main(String[] args) { while (true) {
System.out.println("Thank you"); } } }
REPLY
madhavsharma963420_gm 2023-11-06