0% found this document useful (0 votes)
17 views9 pages

Java Data Types and Basics Cheat Sheet

The document discusses various basic concepts in Java programming including primitive data types, variables, arithmetic expressions, escape sequences, type casting, and decision control statements like if statements. It provides examples and explanations of concepts like int, float, char, boolean, constants, addition, subtraction, multiplication, division, escape sequences, widening and narrowing type casting.

Uploaded by

Ravi Kumar
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 (0 votes)
17 views9 pages

Java Data Types and Basics Cheat Sheet

The document discusses various basic concepts in Java programming including primitive data types, variables, arithmetic expressions, escape sequences, type casting, and decision control statements like if statements. It provides examples and explanations of concepts like int, float, char, boolean, constants, addition, subtraction, multiplication, division, escape sequences, widening and narrowing type casting.

Uploaded by

Ravi Kumar
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

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

Common questions

Powered by AI

Primitive data types in Java are simple data types that store values directly in memory, unlike objects which store references to values. Examples include 'int', 'byte', 'short', 'long', 'float', 'double', 'boolean', and 'char'. For instance, 'int age = 18;' directly stores the integer 18. Primitives do not have methods or additional functionalities associated with them, whereas objects can have multiple methods to manipulate the data they encapsulate .

Encapsulation in Java is crucial as it protects the internal state of an object from unauthorized external access and misuse. It involves bundling the data (variables) and methods that operate on the data into a single unit or class, and restricting direct access to some of an object's components. This can be seen in the 'Person' class example, where the 'name' variable is private and can only be accessed or modified through public getter and setter methods. Encapsulation enhances code maintainability and relieves programmers from the complexity by hiding the internal object details .

Recursion in Java is a technique where a method calls itself to solve a smaller instance of the same problem, breaking down complex tasks into simpler sub-tasks. A classic example is calculating the factorial of a number. However, recursion can lead to risks such as stack overflow if the base case is not properly defined, resulting in infinite recursive calls. Additionally, recursive solutions may be less efficient and harder to debug than iterative solutions due to increased memory overhead and call stack usage .

Arrays in Java store multiple values of the same type in a single variable, providing a structured way to manage data collections with predefined size. Loops, such as 'for' loops, are used extensively to manipulate arrays. For instance, one can iterate through an array using 'for(int i = 0; i < array.length; i++) { System.out.println(array[i]); }' to access elements by index. Multi-dimensional arrays extend this by allowing arrays of arrays, facilitating handling complex data structures like matrices .

Widening type casting, also known as implicit casting, involves converting a smaller integer type to a larger one without data loss, such as converting an 'int' to a 'double'. For example, 'int x = 45; double var_name = x;' automatically converts the integer to a double . Narrowing type casting, or explicit casting, converts a larger data type to a smaller one, which can involve data loss, such as converting a 'double' to an 'int'. This requires casting explicitly, as in 'double x = 165.48; int var_name = (int)x;', where the decimal portion is lost .

Escape sequences in Java play a crucial role in managing special characters within string literals, which could otherwise disrupt the code. Starting with a backslash '\', escape sequences represent characters that can't be included directly in strings, like tabs ('\t'), backslashes ('\\'), single quotes ('\''), and new lines ('\n'). These sequences allow Java programmers to format text fields, manage output, and handle special character input with precision, thereby enhancing readability and correctness of both strings and formatted outputs .

Java supports several types of loops designed for different scenarios: - 'while' loop: Executes a block of code as long as a specified condition is true. It is suitable for cases where the number of iterations is not known beforehand. - 'for' loop: Used to run a block of code a specific number of times. Best used when the number of iterations is fixed in advance. - 'do-while' loop: Executes the block of code at least once before checking the condition. Suitable when the code block needs to run at least once regardless of the condition. - 'for-each' loop: Iterates over elements of an array or collection, ideal for simple iteration over the array elements .

Conditional statements in Java control the flow of execution based on specified conditions. The 'if' statement executes a block of code if its condition evaluates to true; otherwise, it is skipped. The 'if-else' statement extends this by providing an alternative block if the condition is false. For example, 'if(condition) { ... } else { ... }' executes one of the two blocks based on the boolean result of 'condition'. The 'switch' statement checks a variable against a list of values (cases) and executes corresponding blocks, ideal for cleaner code when dealing with many discrete values. For instance, 'switch(expression) { case a: ... break; ... default: ... }' selects a case or defaults if no matches occur .

File handling in Java is significant as it allows applications to read from and write to files on a storage device, enabling data persistence beyond program execution. Common operations include checking readability ('file.canRead()'), writability ('file.canWrite()'), creating files ('file.createNewFile()'), and deleting files ('file.delete()'). Methods like 'getName()' and 'getAbsolutePath()' retrieve file information, while 'mkdir()' creates directories. These operations provide controlled interaction with the file system, essential for logging, data storage, and processing tasks .

Method overloading in Java occurs when multiple methods have the same name but differ in parameters (type, number, or both). This allows for different implementations based on the different inputs, enabling more flexible and readable code. For example, in the class 'Calculate', the method 'sum' is overloaded to handle both 'int' and 'float' types: 'void sum(int x, int y)' and 'void sum(float x, float y)'. When invoked with integers, the first method runs, and with floats, the second .

You might also like