Basics

Basic Boilerplate Code - Hello World Program

public class test{
 
    public static void main(String[] a){
        System.out.println("Hello World");
    }
}
 

Comments

Comments are used to make code more readable or to explain java code. Comments are ignored while executing the code.

Single Line Comment

Single Line comments starts with double forward slashes(//). Syntax for Single Line Comment:

//This is comment and will be ignored by java while executing.
System.out.println("HelloWorld");

Multi-Line Comments

Multi-line comments starts with /* and ends with */. Any code between these two will be ignored.

/*
This block will be ignored
The code below will print hello world.
Example of multi-line comment
*/
System.out.println("HelloWorld");

User Input in Java

To take user input, first we will import Scanner class. Learn more about Scanner class here

 
public class test{
    public static void main(String[] a){
 
        //Creating an object of scanner class.
        Scanner input = new Scanner(System.in);
 
        //Taking Integer Input from user
        int testVar = input.nextInt();
    }
}

Data Types

Primitive Data Type

Data TypeExampleSize
Bytebyte a = 100;1 bytes
Shortshort a = 500;2 bytes
Integerint a = 5;4 bytes
Longlong a =1241351866L;8 bytes
Floatfloat a = 15.87;4 bytes
Doubledouble a =2156.4674;8 bytes
Booleanbool isValid = true;1 bit
Characterchar letter = “J”;2 bytes

Java Operator

Operator are used to perform mathematical operations on variables and values.

Types of Operators

  • Arithmetic Operators
  • Logical Operators
  • Relational Operators
  • Bitwise Operators

Arithmetic Operators

OperatorNameAboutExample
+AdditionAdds the variablesa + b
-SubtractionSubtracts the variablesa - b
*MultiplicationMultiply the variablesa * b
/DivisionDivides the variablesa / b
%Modulusprints the remainder of divisiona % b
++IncrementIncrement the values by 1a++
DecrementDecrement the values by 1a—

Logical Operators

OperatorNameAboutExample
&&Logical ANDIf any one of the condition is false, then result becomes false.A && B (If A is true and B is false then result is FALSE)
||Logical ORIf any one of the condition is true then result becomes trueA || B (If A is true and B is false then result is TRUE)
!Logical NOTIt is used to reverse the logical state of operand. If condition is FALSE then NOT operator will make it TRUE!A (Here If A is TRUE the !A(NOT A) becomes FALSE)

Relational Operators

OperatorNameAboutExample
==Equals toCheck two variables if they are equal or nota == b
<Less thanChecks if left variable is less than or not of right variablea < b
>Greater thanChecks if left variable is greater than or not of right variablea > b
Less than or equal toCheck if left variable is less than or equal to right variablea b
>=Greater than or equal toChecks if left variable is greater than or equal to right variablea>=b

Bitwise Operator

In progress

Conditional Statements

If Statements

if statements are used to specify block of code to be executed if condition is true

if(condition){
    //block of code
}
 
//EXAMPLE:
int a = 5;
int b = 2;
if(a > b){
  System.out.println("A is greater");
}

Else Statement

else block is executed if the if block is false

if(condition){
  //code
}
else{
  //executed this block if above "if" block is false
}

Else if Statements

else if is used to specify multiple if condition.

if(condition){
  //code 1
}
else if(condition2){
  // execute this block if above "if" is false.
}
else if(condition3){
  // execute this block if above "else if" block is false.
}
else{
  // execute this if all above block is false.
}

Switch Statement

switch(condition){
  case A:
    // code
    break;
 
  case B:
    //code
    break;
 
  case C:
    //code
    break;
 
  default:
    //code
}

Loops

While Loop

while(condition){
  //code
}

Example Code:

//print 1 to 10
int i=1;
while(i<=10){
  System.out.println(i);
  i++;
}

For Loop

for(initialization; condition; increment/decrement){
  //code
}
 
//print 1 to 10
 
for(int i=1; i<=10; i++){
  System.out.println(i);
}

Do While Loop

do{
  //loop body or code
}
while(condition);
 
 
//Example Code:
int i=1;
do{
  System.out.println(i);
  i++;
}
while(i<=10);

Break/Continue Statements

break statement is used to jump out of the loop.

for(int i=1; i<=10;i++){
  //break loop if value of i becomes 5
  if(i == 5){
    break;
  }
  System.out.print(i + " ");
}
 
//OUTPUT:
// 1 2 3 4

continue statement is used skip the one iteration in the loop.

for(int i=1; i<=10; i++){
  if(i==5){
      continue;
  }
  System.out.print(i+" ");
}
 
// OUTPUT:
// 1 2 3 4 6 7 8 9 10
// Here 5 is skipped

Arrays

Arrays are used to store multiple values of same data type in single variable. Array Index starts from 0.

Declaring Array

int[] id; //declaring array
id = new int[5]; //allotting memory to array
 
//Another Way to declare array
int[] id = new int[5];

Defining Array

int[] id = {1,2,3,4,5};

Access an Array Element

String[] arr = {'ABC','XYZ', 'PQR'};
System.out.println(arr[1]);
 
//Changing Array Element
arr[2] = "RST";
//"PQR" will be changed to "RST"

Array Length

System.out.println(arr.length);

2D Array

//Creating 2x2 Matrix Array
int[2][2] matrix = new int[2][2];
//the two brackets( [2][2] ) represents no. of rows and columns
// Here array of 2 row and 2 col are declared.
 
//defining array
int[2][2] matrix = {
// COL 1  COL 2
  {12,    54},   // ROW 1
  {67,    23}    // ROW 2
};

Methods (Functions)

Declaring Method

//SYNTAX
returnType methodName(parameters){
  //code
}
 
//EXAMPLE
int printNum(int a){
  return a;
}
 
//CALLING METHOD
//SYNTAX : methodName(arguments);
// EXAMPLE:
    printNum(5);
//     ↑     ↑
//  Method   Arguments
//  Name

Method Overloading

Two or more methods can have same name but different parameters, such methods are called “overloaded methods”.

//Method 1 (0 Arguments)
 
static void greet(){
  System.out.println("Good Morning");
}
 
//Method 2 (1 Arguments)
static void greet(String name){
  System.out.println("Good Morning " + name);
}
 
//Calling Both Methods
greet();                //OUTPUT: Good Morning
greet("Carl Johnson")   //OUTPUT: Good Morning Carl Johnson

Recursion

Recursion is the technique of making a function call itself.

//Factorial of Number in Recursion
static int factorial(int n){
  if(n == 0){
    return 1;
  }
  return n * factorial(n-1);
//                ↑
//          This is recursive function call.
}