Home - CodeWithHarry Home - CodeWithHarry
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
[Link]("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.
[Link]([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 [Link]; //import scanner class its value in a single bit.
// create an object of Scanner class isEligible = true;
Scanner input = new Scanner([Link]);
// take input from the user int
String varName = [Link]();
int holds a wide range of non-fractional number values.
Primitive Type Variables var1 = 256;
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
// It's a single line comment Division
It can be used to divide two numbers
Multi-line comment
int x = 10 / 3;
float x = (float)10 / (float)3;
/* It's a
multi-line
comment Modulo Remainder
*/
It returns the remainder of the two numbers after division
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
var += 10 // var = var + 10
Arithmetic Expressions
These are the collection of literals and arithmetic operators. Subtraction assignment
Addition
var -= 10 // var = var - 10
It can be used to add two numbers
Multiplication assignment
int x = 10 + 3;
var *= 10 // var = var * 10
Subtraction
It can be used to subtract two numbers
Division assignment
int x = 10 - 3; var /= 10 // var = var / 10
Multiplication Modulus assignment
3/18 4/18
Home - CodeWithHarry Home - CodeWithHarry
var %= 10 // var = var % 10 \"
Escape Sequences Type Casting
It is a sequence of characters starting with a backslash, and it doesn't represent itself when used Type Casting is a process of converting one data type into another
inside string literal.
Widening Type Casting
Tab
It means converting a lower data type into a higher
It gives a tab space
// int x = 45;
\t double var_name = x;
Backslash Narrowing Type Casting
It adds a backslash It means converting a higher data type into a lower
\\ double x = 165.48
int var_name = (int)x;
Single quote
It adds a single quotation mark
Decision Control Statements
\'
Conditional statements are used to perform operations based on some condition.
Question mark if Statement
It adds a question mark
if (condition) {
// block of code to be executed if the condition is true
\?
}
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 }
It adds a double quotation mark
5/18 6/18
Home - CodeWithHarry Home - CodeWithHarry
if else-if Statement while Loop
It iterates the block of code as long as a specified condition is True
if (condition1) {
// Codes
while (condition) {
}
// code block
else if(condition2) {
}
// Codes
}
else if (condition3) { for Loop
// Codes
} for loop is used to run a block of code several times
else {
// Codes for (initialization; termination; increment) {
} statement(s)
}
Ternary Operator
for-each Loop
It is shorthand of an if-else statement.
for(dataType item : array) {
variable = (condition) ? expressionTrue : expressionFalse;
...
}
Switch Statements
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 [Link](var_name[i]);
}
Arrays are used to store multiple values in a single variable
Declaring an array Multi-dimensional Arrays
Declaration of an array Arrays can be 1-D, 2-D or multi-dimensional.
String[] var_name; // Creating a 2x3 array (two rows, three columns)
int[2][3] matrix = new int[2][3];
matrix[0][0] = 10;
Defining an array
// Shortcut
int[2][3] matrix = {
Defining an array
{ 1, 2, 3 },
{ 4, 5, 6 }
String[] var_name = {''Harry", "Rohan", "Aakash"};
};
Accessing an array
Accessing the elements of an array
Methods
String[] var_name = {''Harry", "Rohan", "Aakash"}; Methods are used to divide an extensive program into smaller pieces. It can be called multiple
[Link](var_name[index]); times to provide reusability to the program.
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"; }
Array length Calling a method
It gives the length of the array Calling a method
[Link](var_name.length); methodName(arguments);
9/18 10/18
Home - CodeWithHarry Home - CodeWithHarry
String var_name = "Hello World";
Method Overloading
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) [Link]("The length of the string is: " + var_name.length());
{
[Link]("Sum is: "+(a+b)) ;
}
String Methods toUpperCase()
void sum (float x, float y)
Convert the string into uppercase
{
[Link]("Sum is: "+(a+b));
String var_name = "Harry";
}
[Link](var_name.toUpperCase());
Public static void main (String[] args)
{
Calculate calc = new Calculate(); toLowerCase()
[Link] (5,4); //sum(int x, int y) is method is called.
[Link] (1.2f, 5.6f); //sum(float x, float y) is called. Convert the string into lowercase
}
} String var_name = ""Harry"";
[Link](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
void recurse() String var_name = "Harry";
{ [Link](var_name.indexOf("a"));
... .. ...
recurse();
... .. ... concat()
}
Used to concatenate two strings
Strings String var1 = "Harry";
String var2 = "Bhai";
It is a collection of characters surrounded by double quotes. [Link]([Link](var2));
Creating String Variable
Math Class
11/18 12/18
Home - CodeWithHarry Home - CodeWithHarry
Math class allows you to perform mathematical operations. class
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 {
[Link](25, 45); // Fields
// Methods
// Constructors
min() method
// Blocks
It is used to find the smaller number among the two }
[Link](8, 7); Encapsulation
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
public class Person {
[Link](144);
private String name; // using private access modifier
random() method // Getter
public String getName() {
It is used to generate random numbers return name;
}
[Link](); //It will produce random number b/w 0.0 and 1.0
// Setter
public void setName(String newName) {
int random_num = (int)([Link]() * 101); //Random num b/w 0 and 100 [Link] = newName;
}
}
Object-Oriented Programming Inheritance
It is a programming approach that primarily focuses on using objects and classes. The objects Inheritance can be defined as the process where one class acquires the properties of another.
can be any real-world entities. With the use of inheritance the information is made manageable in a hierarchical order.
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 Checks whether the file is readable or not
Polymorphism is the ability of an object to take on many forms. The most common use of
[Link]()
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) { [Link]()
[Link](a + b);
}
canWrite method
// method 2 Checks whether the file is writable or not
public void add(int a, int b, int c) {
[Link](a + b + c);
[Link]()
}
// method 3 exists method
public void add(String a, String b) {
[Link](a + " + " + b); Checks whether the file exists
}
} [Link]()
// 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
[Link](5, 4); // invoke method 1
[Link]()
[Link](5, 4, 3); // invoke method 2
[Link]("5", "4"); // invoke method 3
} getName method
}
It returns the name of the file
[Link]()
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
[Link]()
15/18 16/18
Home - CodeWithHarry Home - CodeWithHarry
}
length Method }
It returns the size of the file in bytes
[Link]()
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.
[Link]()
try {
mkdir method // Statements
}
It is used to create a new directory catch(Exception e) {
// Statements
[Link]() }
close method finally block
It is used to close the file finally code is executed whether an exception is handled or not.
[Link]() try {
//Statements
}
To write something in the file
catch (ExceptionType1 e1) {
// catch block
import [Link]; // Import the FileWriter class }
import [Link]; // 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("[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 18/18