0% found this document useful (0 votes)
16 views8 pages

Java Method Basics Cheat Sheet

This Java cheatsheet provides a concise overview of Java programming basics, including syntax for classes, methods, data types, and control flow structures. It covers input/output operations, operators, comments, arrays, and string manipulation, along with examples for each concept. Additionally, it highlights important features like method overloading, recursion, and the Math class functionalities.

Uploaded by

TECHNICAL ARPIT
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)
16 views8 pages

Java Method Basics Cheat Sheet

This Java cheatsheet provides a concise overview of Java programming basics, including syntax for classes, methods, data types, and control flow structures. It covers input/output operations, operators, comments, arrays, and string manipulation, along with examples for each concept. Additionally, it highlights important features like method overloading, recursion, and the Math class functionalities.

Uploaded by

TECHNICAL ARPIT
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

Java Cheatsheet

Basics

Boilerplate

class HelloWorld {
public static void main(String[] args) {

[Link]("Hello World");
}

• public → Access modifier (needed for JVM to call main ).


• static → Allows JVM to call without creating an object.
• void → Method returns nothing.
• String[] args → Command-line arguments.

Showing Output

[Link]("Hello"); // prints without newline


[Link](" World"); // prints with newline
[Link]("Age: %d", 20); // formatted output

Taking Input (Scanner)

import [Link];

class InputExample {
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String name = [Link](); // String

int age = [Link](); // int


float f = [Link](); // float
double d = [Link](); // double
boolean b = [Link](); // boolean
char c = [Link]().charAt(0); // char (first char of input)

[Link]("Name: " + name);


}
}

Primitive Types

Eight primitives: byte , short , int , long , float , double , boolean , char .

• byte (8-bit, -128 to 127)


• short (16-bit, -32,768 to 32,767)
• int (32-bit, default for integers)
• long (64-bit, append L for literals)
• float (32-bit, append f )
• double (64-bit, default for decimals)
• boolean ( true or false )
• char (16-bit Unicode)

Comments

// Single line

/* Multi-line */
/** Javadoc comment */
Constants

final double PI = 3.14159;


static final int MAX = 100;

Arithmetic Operators

+ - * / % ++ --

• Division between integers truncates result.


• % gives remainder.

Assignment Operators

=, +=, -=, *=, /=, %=

Comparison Operators

==, !=, >, <, >=, <=

Logical Operators

&& (AND), || (OR), ! (NOT)


Escape Sequences

• \n → newline
• \t → tab
• \\ → backslash
• \' → single quote
• \" → double quote
• \r → carriage return
• \b → backspace

( \? is not valid in Java; use "?" literally.)

Type Casting

Widening (automatic)

int x = 45;
double y = x; // OK

Narrowing (manual)

double d = 45.9;
int n = (int) d; // truncates decimal
Control Flow

if / else if / else

if (x > 0) { ... }

else if (x == 0) { ... }
else { ... }

Ternary

String result = (x > 0) ? "Positive" : "Negative";

switch (Java 7+ supports Strings)

switch(day) {

case 1: [Link]("Mon"); break;

...

default: [Link]("Invalid");
}

Loops

while

while (i < 5) {
i++;

}
do-while

do {
i++;
} while (i < 5);

for

for (int i = 0; i < 5; i++) { ... }

for-each

for (int n : arr) { ... }

break / continue
• break → exits loop
• continue → skips iteration

Arrays

int[] nums = new int[5];


String[] names = {"Harry", "Rohan"};
[Link]([Link]);

Multi-dimensional

int[][] matrix = {
{1, 2, 3},

{4, 5, 6}
};
[Link](matrix[1][2]); // 6
Methods

static int add(int a, int b) {


return a + b;
}

public static void main(String[] args) {


[Link](add(5, 10));

Method Overloading

void sum(int a, int b) { ... }

void sum(double a, double b) { ... }

Recursion

int fact(int n) {
if (n == 0) return 1;

return n * fact(n - 1);

Strings

Strings are objects of [Link] .

String s = "Hello";

int len = [Link]();


[Link]();
[Link]();
[Link]("l");
[Link]("He");
[Link]("Hello");

[Link]("hello");

[Link](0, 3); // "Hel"


[Link]("H", "J");

Math Class

[Link](5, 10);
[Link](5, 10);

[Link](16);
[Link](2, 3);

[Link](-10);

[Link](); // [0.0, 1.0)

Common questions

Powered by AI

Widening type casting in Java is an automatic conversion that converts a smaller primitive type to a larger primitive type, which does not result in data loss. For example, assigning an 'int' value to a 'double' variable is widening: 'int x = 45; double y = x;' . In contrast, narrowing type casting is a manual conversion where a larger primitive type is converted to a smaller primitive type, which may result in data loss. For example, casting a 'double' to an 'int': 'double d = 45.9; int n = (int) d;', this truncates the decimal part .

The 'continue' command in Java is utilized within loops to skip the current iteration and move directly to the next iteration. This is particularly useful when you want to ignore certain conditions in a loop without completely exiting the loop. For example, in a loop where certain values should not be processed, 'continue' can be used to skip further operations for those values and continue with the next iteration of the loop. This allows for efficient conditional evaluation while keeping the loop running .

The main difference between 'while' and 'do-while' loops in Java is when the condition is evaluated. In a 'while' loop, the condition is evaluated before the loop body is executed, meaning the loop body might not run at all if the condition is false initially. Conversely, a 'do-while' loop evaluates the condition after the loop body is executed, guaranteeing that the loop body runs at least once. 'Do-while' is preferable when you need the loop to execute at least once regardless of the condition's initial state .

Starting from Java 7, the 'switch' statement can be used with Strings, enabling more expressive control flows based on string values. This feature increases the flexibility and readability of code that needs to perform different actions based on string content. For example, 'switch(day)' can be used with cases as strings like 'case "Monday":', making it more intuitive than using multiple 'if-else' conditions. This reduces code complexity in scenarios where distinct string values determine the execution path, improving code maintainability and readability .

Using the 'Scanner' class in Java allows for flexible input handling from various sources like input streams. However, issues could arise related to input buffer handling and token parsing. For example, when switching between reading different data types, the Scanner might not consume the newline character correctly, which could lead to unexpected behavior or errors. It is important to handle these scenarios by potentially using 'sc.nextLine()' to clear the buffer after reading numeric input or when changing input types to avoid such discrepancies .

Java provides various string manipulation functions through the java.lang.String class, which allow for modifying and extracting substrings. Methods like 'substring()' allow parts of a string to be extracted, e.g., 's.substring(0, 3)' would extract "Hel" from "Hello". Functions such as 'replace()' can be used to alter string content, e.g., 's.replace("H", "J")' transforms "Hello" to "Jello". These methods provide flexibility in handling strings for detailed text processing tasks .

Escape sequences in Java are used to perform specific character formatting tasks in strings and output operations. They allow control over the display of special characters and formatting without disrupting the flow or causing syntax errors. Examples include '\n' for a newline, '\t' for a tab, '\\' for a backslash, '\"' for a double quote, and '\r' for a carriage return. These are crucial for correct and readable formatting in console output .

Method overloading in Java allows multiple methods to have the same name with different parameters (different type or number of parameters). This enhances code readability and usability, allowing programmers to use the same logic with different input sets. For instance, having two 'sum' methods, one taking integers and another taking doubles, allows you to handle summation seamlessly regardless of the data type input: 'void sum(int a, int b)' and 'void sum(double a, double b)'. This approach avoids creating different function names for similar operations and improves code maintenance .

The 'static' keyword in the context of the 'main' method allows the Java Virtual Machine (JVM) to invoke the method without creating an instance of the class. This is necessary because the 'main' method serves as the entry point of a Java application, and it must be accessible to the JVM directly. If the 'main' method were not static, the JVM would need to instantiate the class before it could call the method, complicating the process of application startup .

Recursion in Java involves a method calling itself to solve a problem. It is characterized by a base case that stops the recursion and a recursive case that reduces the problem size. For example, calculating the factorial of a number can be implemented recursively: 'int fact(int n) { if (n == 0) return 1; return n * fact(n - 1); }'. This method will keep calling itself with decreasing values of 'n' until 'n' reaches 0, at which point it returns 1 and allows the recursive calls to resolve .

You might also like