Basic Syntax
public class Main {
public static void main(String[] args) {
//code goes here
}
}
System.out.println
System.out.println("Hello World");
scanner
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.close();
System.out.println("Hello, " + name);
System.out.println("Your age is: " + age);
}
}
Comments
//this is a single lined comment.
/*this is a
multi-lined comment*/
Java Constants
public class Declaration {
final double PI = 3.14;
public static void main(String[] args) {
System.out.println("Value of PI: " + PI);
}
}
Escape Sequences
//escape sequences
\n //adds a new line
\t //adds four spaces
\b //backspace
\a //beep sound
\f //form feed
\r //carriage return
\\ //adds backslash
\' //adds single quote
\? //adds question mark
\0 //null character
Variables
int sum = 10;
Data Types
int sum = 10; //stores integer
float average = 90.33; //stores numbers with decimal
double percentage = 80.3452; //stores numbers with decimal but precision is double as compared to float
char letter = 'A'; //stores single character
bool isTrue = true; //stores true or false
string intro = "My name is Sajeel"; //stores sequence of characters
void myFunc();//it represent the absence of data type. Mostly used with functions
Type Casting
//type casting
int x = 45;
double var_name = x;
System.out.println(var_name);
String and its methods
//declaring string
char fname[] = "John";
char lname[] = "Doe";
//concatenating strings
String name = fname + lname; // Using the + operator
// or
String name = fname.concat(lname); // Using the concat method
//finding length of string
String myString = "Hello, World!";
int length = myString.length();
System.out.println("Length: " + length);
//accessing characters of string
String myString = "Hello, World!";
char firstChar = myString.charAt(0);
System.out.println(firstChar);
//Changing characters
String myString = "Hello, World!";
myString = myString.replace('H', 'A'); // Replace 'H' with 'A'
System.out.println(myString);
//taking string input ignoring spaces
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String myString = scanner.next();
System.out.println("You entered: " + myString);
scanner.close();
}
}
Operators
Arithmetic Operators
+ //addition
- //subtraction
* //multiplication
/ //division
% //modulus
++ //increment
-- //decrement
Assignment Operators
= //assign value
+= //add and assign
-= //subtract and assign
/= //divide and assign
*= //multiply and assign
%= //taking modulus and assign
Comparison Operators
== //checks equality
!= //checks unequality
> //checks greater than
>= //checks greater than or equal to
< //check less than
<= //checks less than or equal to
Logical Operators
&& //returns true if all are expressions true
|| //returns true if only one expression is true
! //returns true if false and vice versa
Bitwise Operators
& //bitwise AND
| //bitwise OR
~ //bitwise NOT
>> //shift right
<< //shift left
Conditional statements
//if statement
if(condition){
//code
}
//if-else statement
if(condition){
//code
}
else{
//code
}
//else-if statement
if(condition){
//code
}
else if(condition){
//code
}
else{
//code
}
//goto statement
int main(){
//code
label:
// code
goto label;
// code
}
//Ternary Operator
variable = condition ? ifTrue : ifFalse;
Switch Statements
switch(expression){
case const-exp:
//code
break;
case const-exp:
//code
break;
.
.
.
default:
//code
break;
}
Loops
//for Loop:
for( initialization ; condition ; change-variable-value ){
//code
}
//for each loop
for (int i : arrayName) {
System.out.println(i);
}
//while Loop:
initialize variable
while(condition){
//code
//change-variable-value
}
//do-while Loop:
initialize variable
do{
//code
//change-variable-value
}while(condition);
Continue And Break Statements
//break statement
for( initialization ; condition ; change-variable-value ){
if(condition){
break; //moves out of the loop when condition is true
}
}
//continue statement
for( initialization ; condition ; change-variable-value ){
if(condition){
continue; //skip the iteration when condition is true
}
}
Arrays
// Initializing arrays
int[] arrayName = {data1, data2, ...};
// Printing array
for (int i = 0; i < arrayName.length; i++) {
System.out.printf("%d%n", arrayName[i]);
}
// Taking input in array
for (int i = 0; i < arrayName.length; i++) {
System.out.printf("Enter data at %d index: ", i + 1);
Scanner scanner = new Scanner(System.in);
arrayName[i] = scanner.nextInt();
}
// Changing array elements at specified index
int[] myArray = {1, 2, 3};
myArray[0] = 5; // Now the array has 5 at the first index
Methods
public class HelloWorld {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(5, 3);
System.out.println("Sum: " + sum);
}
}
Method Overloading
public class MathOperations {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two double values
public double add(double a, double b) {
return a + b;
}
// Method to concatenate two strings
public String add(String str1, String str2) {
return str1 + str2;
}
public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of two integers: " + math.add(5, 7));
System.out.println("Sum of three integers: " + math.add(2, 4, 6));
System.out.println("Sum of two doubles: " + math.add(3.5, 2.5));
System.out.println("Concatenated strings: " + math.add("Hello, ", "World!"));
}
}
Built-in Functions
import java.util.Scanner; // Import the Scanner class for input
import java.util.Date; // Import the Date class for date/time
public class Main {
public static void main(String[] args) {
// Input and Output functions
System.out.printf("%s", "Hello, World"); // Formatted output
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine(); // Formatted input
char character = scanner.next().charAt(0); // Character input
System.out.print(character); // Character output
String str = "Hello, World";
System.out.println(str); // Printing strings
// String functions
String str1 = "Hello";
String str2 = "World";
int length = str1.length(); // Length of a string
boolean equal = str1.equals(str2); // String comparison
boolean equalIgnoreCase = str1.equalsIgnoreCase(str2); // Case-insensitive comparison
boolean startsWith = str1.startsWith("Hel"); // Starts with
boolean endsWith = str2.endsWith("rld"); // Ends with
String concatenated = str1.concat(str2); // String concatenation
String substring = str1.substring(1, 4); // Substring
String replaced = str1.replace('l', 'z'); // Replace
String upper = str1.toUpperCase(); // Uppercase
String lower = str2.toLowerCase(); // Lowercase
String reversed = new StringBuilder(str1).reverse().toString(); // Reverse
// Math functions
double x = 4.5;
double y = 2.0;
double power = Math.pow(x, y); // Exponentiation
double sqrt = Math.sqrt(x); // Square root
double floorValue = Math.floor(x); // Floor
double ceilValue = Math.ceil(x); // Ceiling
long rounded = Math.round(x); // Round
double remainder = Math.IEEEremainder(x, y); // Remainder
double cosine = Math.cos(x); // Cosine
double sine = Math.sin(x); // Sine
double tangent = Math.tan(x); // Tangent
double logarithm = Math.log(x); // Natural logarithm
double logarithm10 = Math.log10(x); // Base-10 logarithm
// Date and time functions
Date startTime = new Date(); // Get the current time
// Perform some task or wait
Date endTime = new Date();
long difference = endTime.getTime() - startTime.getTime();
double differenceInSeconds = difference / 1000.0;
System.out.printf("Time elapsed: %.2f seconds\n", differenceInSeconds);
}
}
Exceptions
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handling code
} finally {
// Cleanup code
}
Class
class ClassName {
// code goes here
}
Object
className object = new className();
Encapsulation
public class Vehicle
{
private int price; // using private access modifier
// Getter
public int getPrice()
{
return price;
}
// Setter
public void setPrice(int price)
{
this.price = price;
}
}
Inheritance
class Child extends Parent {
//class implementation
}
Polymorphism
// A class with multiple methods with the same name
public class Adder
{
// method 1
public void add(int a, int b)
{
System.out.println(a + b);
}
// 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);
}
}
// Main class
class Main
{
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.add("5", "4"); // invoke method 3
}
}
File Handling
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileHandling {
public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
System.out.println(data);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}