0% found this document useful (1 vote)
471 views18 pages

Java Basics Cheat Sheet

The document provides an overview of basic Java concepts including: - Printing output and taking input - Primitive data types like int, float, boolean - Variables, arithmetic expressions, and type casting - Conditional and iterative statements like if-else and for loops - Arrays and how to access/change elements - Methods, overloading methods, and recursion - Strings and common string methods.

Uploaded by

Kaushal Mishra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
471 views18 pages

Java Basics Cheat Sheet

The document provides an overview of basic Java concepts including: - Printing output and taking input - Primitive data types like int, float, boolean - Variables, arithmetic expressions, and type casting - Conditional and iterative statements like if-else and for loops - Arrays and how to access/change elements - Methods, overloading methods, and recursion - Strings and common string methods.

Uploaded by

Kaushal Mishra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Primitive Type Variables
  • Basics
  • Comments
  • Arithmetic Expressions
  • Escape Sequences
  • Decision Control Statements
  • Type Casting
  • Iterative Statements
  • Arrays
  • Methods
  • Strings
  • Math Class
  • Object-Oriented Programming
  • File Operations
  • Exception Handling

Home - CodeWithHarry

Basics
Basic syntax and functions from the Java programming language.

Boilerplate

class HelloWorld{

public static void main(String args[]){

[Link]("Hello World");

Showing Output

It will print something to the output console.

[Link]([text])

Taking Input

It will take string input from the user

import [Link]; //import scanner class

// create an object of Scanner class

Scanner input = new Scanner([Link]);

// take input from the user

String varName = [Link]();

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 = 18;

1/18
Home - CodeWithHarry

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 number. Which means if we get past six decimal points, this number becomes less
precise and more of an estimate.

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 value in a single bit.

isEligible = true;

int

int holds a wide range of non-fractional number values.

var1 = 256;

short

If we want to save memory and byte is too small, we can use short.

short var2 = 786;

Comments
2/18
Home - CodeWithHarry

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
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;

Multiplication

3/18
Home - CodeWithHarry

It can be used to multiply add two numbers

int x = 10 * 3;

Division

It can be used to divide two numbers

int x = 10 / 3;

float x = (float)10 / (float)3;

Modulo Remainder

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

4/18
Home - CodeWithHarry

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
inside string literal.

Tab

It gives a tab space

\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


5/18
Home - CodeWithHarry

\"

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;

Narrowing Type Casting

It means converting a higher data type into a lower

double x = 165.48

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

6/18
Home - CodeWithHarry

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.

variable = (condition) ? expressionTrue : expressionFalse;

Switch Statements

It allows a variable to be tested for equality against a list of values (cases).

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.

7/18
Home - CodeWithHarry

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

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

do {

// body of loop

} while(textExpression)

Break statement

break keyword inside the loop is used to terminate the loop

break;

Continue statement

8/18
Home - CodeWithHarry

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

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

String[] var_name = {''Harry", "Rohan", "Aakash"};

[Link](var_name[index]);

Changing an element

Changing any element in an array

String[] var_name = {''Harry", "Rohan", "Aakash"};

var_name[2] = "Shubham";

Array length

It gives the length of the array

[Link](var_name.length);

9/18
Home - CodeWithHarry

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++) {

[Link](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.

Declaration

Declaration of a method

returnType methodName(parameters) {

//statements

Calling a method

Calling a method

methodName(arguments);
10/18
Home - CodeWithHarry

Method Overloading

Method overloading means having multiple methods with the same name, but different
parameters.

class Calculate

void sum (int x, int y)

[Link]("Sum is: "+(a+b)) ;

void sum (float x, float y)

[Link]("Sum is: "+(a+b));

Public static void main (String[] args)

Calculate calc = new Calculate();

[Link] (5,4); //sum(int x, int y) is method is called.

[Link] (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 calls itself is known as the Recursive function.

void recurse()

... .. ...

recurse();

... .. ...

Strings
It is a collection of characters surrounded by double quotes.

Creating String Variable

11/18
Home - CodeWithHarry

String var_name = "Hello World";

String Length

Returns the length of the string

String var_name = "Harry";

[Link]("The length of the string is: " + var_name.length());

String Methods toUpperCase()

Convert the string into uppercase

String var_name = "Harry";

[Link](var_name.toUpperCase());

toLowerCase()

Convert the string into lowercase

String var_name = ""Harry"";

[Link](var_name.toLowerCase());

indexOf()

Returns the index of specified character from the string

String var_name = "Harry";

[Link](var_name.indexOf("a"));

concat()

Used to concatenate two strings

String var1 = "Harry";

String var2 = "Bhai";

[Link]([Link](var2));

Math Class
12/18
Home - CodeWithHarry

Math class allows you to perform mathematical operations.

Methods max() method

It is used to find the greater number among the two

[Link](25, 45);

min() method

It is used to find the smaller number among the two

[Link](8, 7);

sqrt() method

It returns the square root of the supplied value

[Link](144);

random() method

It is used to generate random numbers

[Link](); //It will produce random number b/w 0.0 and 1.0

int random_num = (int)([Link]() * 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 any real-world entities.

object

An object is an instance of a Class.

className object = new className();

13/18
Home - CodeWithHarry

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

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.

public class Person {

private String name; // using private access modifier

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

[Link] = 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.

class Subclass-name extends Superclass-name

//methods and fields

14/18
Home - CodeWithHarry

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.

// A class with multiple methods with the same name

public class Adder {

// method 1

public void add(int a, int b) {

[Link](a + b);

// method 2

public void add(int a, int b, int c) {

[Link](a + b + c);

// method 3

public void add(String a, String b) {

[Link](a + " + " + b);

// My main class

class MyMainClass {

public static void main(String[] args) {

Adder adder = new Adder(); // create a Adder object

[Link](5, 4); // invoke method 1

[Link](5, 4, 3); // invoke method 2

[Link]("5", "4"); // invoke method 3

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

15/18
Home - CodeWithHarry

Checks whether the file is readable or not

[Link]()

createNewFile method

It creates an empty file

[Link]()

canWrite method

Checks whether the file is writable or not

[Link]()

exists method

Checks whether the file exists

[Link]()

delete method

It deletes a file

[Link]()

getName method

It returns the name of the file

[Link]()

getAbsolutePath method

It returns the absolute pathname of the file

[Link]()

16/18
Home - CodeWithHarry

length Method

It returns the size of the file in bytes

[Link]()

list Method

It returns an array of the files in the directory

[Link]()

mkdir method

It is used to create a new directory

[Link]()

close method

It is used to close the file

[Link]()

To write something in the file

import [Link]; // Import the FileWriter class

import [Link]; // Import the IOException class to handle errors

public class WriteToFile {

public static void main(String[] args) {

try {

FileWriter myWriter = new FileWriter("[Link]");

[Link]("Laal Phool Neela Phool, Harry Bhaiya Beautiful");

[Link]();

[Link]("Successfully wrote to the file.");

} catch (IOException e) {

[Link]("An error occurred.");

[Link]();

17/18
Home - CodeWithHarry
}
}

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

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

18/18

Common questions

Powered by AI

'For' and 'while' loops in Java are both used to execute a block of code repeatedly. The 'for' loop is usually used when the number of iterations is known ahead of time, featuring initialization, a condition, and an increment/decrement in a single line. The 'while' loop is employed when the number of iterations is not predetermined, and it runs as long as the condition remains true. 'For' loops are often viewed as more concise and are commonly used for iterating over arrays, whereas 'while' loops provide a more natural, flexible approach to looping when conditions need to be dynamically evaluated during execution .

Switch statements in Java simplify complex conditional logic that involves multiple potential values for a single variable by reducing cumbersome series of 'if-else' statements into more manageable code. According to the CodeWithHarry tutorial, instead of checking each condition with 'if-else', switch statements allow the programmer to test the variable against multiple predefined cases, simplifying readability and maintainability. Each case executes if it matches the variable value, with a default case to handle unmatched conditions, thus optimizing code control flow .

The 'float' data type in Java is a single-precision 32-bit IEEE 754 floating point, which means it is less precise and can represent approximately 6-7 decimal digits. On the other hand, 'double' is a double-precision 64-bit IEEE 754 floating point, offering a larger range and more precision, capable of representing approximately 15 decimal digits. Due to their precision differences, 'float' is commonly used when memory savings are more critical than precision, while 'double' is used when precision is essential .

Inheritance in object-oriented programming allows a new class to inherit properties and behaviors (methods) from an existing class, known as the superclass. In Java, the 'extends' keyword facilitates this relationship. By using inheritance, new code can be created by accessing already defined classes, promoting reuse and efficiency. It helps in maintaining a hierarchical class structure, where shared characteristics are placed in base classes, minimizing redundancy and fostering code reuse and manageability .

Encapsulation enhances security by restricting direct access to certain components of an object, allowing access only through public methods. This encapsulation of data within methods prevents unauthorized modifications or misuse. Moreover, it maintains code manageability by presenting a clear interface while hiding implementation complexities and allows for maintenance without affecting other parts of the program. Encapsulation encourages focused development on interface usage rather than the intricacies of inner working, thus improving a program's robustness and maintainability .

Method overloading in Java allows multiple methods to have the same name but differ in the number and/or types of parameters. It enhances code readability and functionality without changing the method name used in calls. For example, in the CodeWithHarry tutorial, the 'sum' method is overloaded with different parameter sets: one takes two integers, another takes two floats, and another prints a string concatenation, demonstrating how the same method name operates differently based on parameters .

A 'try-catch' block in Java is used to handle exceptions, which are runtime anomalies that may disrupt normal code flow. The 'try' block contains code that might throw an exception, while the 'catch' block contains code to handle these exceptions. This mechanism allows the program to continue smoothly in case of an error, instead of crashing, by taking appropriate actions to rectify or log the error. It provides more controlled error management and enhances a program’s reliability and stability .

Type casting in Java is the process of converting data from one type to another, which helps in situations where operations require data consistency. Widening type casting automatically converts smaller data types into larger ones, such as int to double, without data loss. Narrowing type casting, however, involves conversion from larger types to smaller ones (like double to int) and must be explicitly programmed, as it might lead to data loss. This differentiation helps in optimizing storage and calculations based on precision requirements .

Comments in Java, which can be single-line (//) or multi-line (/* ... */), significantly enhance the development process by improving code readability and maintaining clarity. They help developers and collaborators understand code functionality, intent, and logical steps, potentially reducing misunderstandings and errors during development. Moreover, comments provide a way to annotate improvements or modifications required in future development, thereby facilitating more efficient debugging and updates .

Constants are crucial in Java because they prevent constant values from being modified after their declaration, assisting in maintaining consistent values throughout the program execution. They are typically used for values known at compile-time which do not change. In Java, constants are declared using the 'final' keyword before the data type. For example, 'final float INTEREST_RATE = 0.04;' declares a constant float value for INTEREST_RATE that remains unchanged .

Home - CodeWithHarry
1/18
Basics
Basic syntax and functions from the Java programming language.
Boilerplate
class HelloWorld{
Home - CodeWithHarry
2/18
long
long is another primitive data type related to integers. long takes up 64 bits of memory.
view
Home - CodeWithHarry
3/18
A comment is the code that is not executed by the compiler, and the programmer uses it to keep 
tra
Home - CodeWithHarry
4/18
It can be used to multiply add two numbers
int x = 10 * 3;
Division
It can be used to divide two nu
Home - CodeWithHarry
5/18
var %= 10 // var = var % 10
Escape Sequences
It is a sequence of characters starting with a backsla
Home - CodeWithHarry
6/18
"
Type Casting
Type Casting is a process of converting one data type into another
Widening Type Ca
Home - CodeWithHarry
7/18
if else-if Statement
if (condition1) {
// Codes
}
else if(condition2) {
// Codes
}
else if (conditi
Home - CodeWithHarry
8/18
while Loop
It iterates the block of code as long as a specified condition is True
while (condition)
Home - CodeWithHarry
9/18
continue keyword skips the rest of the current iteration of the loop and returns to the starting 
p
Home - CodeWithHarry
10/18
Loop through an array
It allows us to iterate through each array element
String[] var_name = {''Ha

You might also like