Introduction to Java

Java is a high-level, object-oriented programming language developed by Sun Microsystem which is now owned by Oracle Corporation.

Features of Java
Simple: Easy to learn with a clear and clean syntax.
Object-Oriented: Everything is Java is an object. It promotes code reusability.
Platform-independent: Write Once, Run Anywhere (WORA). Java code runs on any device with a Java Virtual Machine (JVM).
Secure: Built-in security features like bytecode verification and exception handling.
Robust: Strong memory management and error handling.
Multithreaded: It Supports multithreading for better performance and parallel processing.
High Performance: It is not as fast as C/C++, Java’s performance is good due to JIT compiler.

Complete Tutorial For Beginners

Object-Oriented Programming

Object-Oriented Programming (OOP) in Java is a programming paradigm c

Data Types and Variables

A variable is a name given to a memory location that stores a value. It’s like a container that holds data which can be changed during program execution.

There are mainly two type of data types:
1.Primitive Data Types: these data types are built-in.
byte: It takes 1byte. Example: byte a = 10;
short: It takes 2bytes. Example: short b = 2000;
int: It takes 4bytes. Example: int c = 50000;
long: It takes 8bytes. Example: long d = 100000L;
float: It takes 4bytes. Example: float e = 5.75f;
double: It takes 8bytes. Example: double f = 19.99;
char: It takes 2bytes. Example: char g = ‘A’;
boolean: It takes 1bit. Example: boolean h = true;

2.Non-Primitive Data Types: It is also called reference types.
String: It is used to store strings. Example: String name = “Java”;
Arrays: It is used to store collection of multiple values with a single name. Example: int[] numbers = {1, 2, 3};
Objects: It is created using classes like Scanner, Student, etc.

Operators

Operators are special symbols in java that perform operations on variables and values.

Arithmetic Operators: These are used for basic math operations. Example: +, -, *, /, %
Assignment Operators: It is used to assign values to variables. Example: =
Relational Operators: These operators are used to compare values. They returns true or false. Example: ==, !=, >, <, >=, <=.
Logical Operators: These operators are used to combine multiple conditions. Example: &&, ||, !.
Unary Operators: These operators work with only one operand. Example: +, -, ++, –, !
Bitwise Operators: These operators are used for binary-level operations. Example: &, ^, ~, <<, >>.

Control Statement and Loops

These statements are used for making decisions or repeating certain parts of the code.

Java
//Executes code if the condition is true.
if (age > 18) {
    System.out.println("Adult");
}
Java
//Chooses between two blocks of code.
if (age >= 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}
Java
//Checks multiple conditions.
if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else {
    System.out.println("Grade C");
}
Java
//switch Statement: Used when you have multiple exact values to check.
int day = 2;
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    default: System.out.println("Other day");
}

Loops

Java
//for Loop – Known number of repetitions
for (int i = 1; i <= 5; i++) {
    System.out.println("i = " + i);
}
Java
//while Loop – Repeats while the condition is true
int i = 1;
while (i <= 5) {
    System.out.println("i = " + i);
    i++;
}
Java
//do-while Loop – Runs at least once, then checks condition
int i = 1;
do {
    System.out.println("i = " + i);
    i++;
} while (i <= 5);
Java
//break: Exits a loop or switch immediately.
for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    System.out.println(i);
}
Java
//continue: Skips the current iteration and jumps to the next one.
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}

Arrays

Arrays are used to store multiple values of the same type in a single variable. In java arrays are objects and are stored in heap. We can use Arrays class from java.util for common operations.

Java
//Declaration
int[] numbers;
int numbers[];

//Initialization
numbers = new int[5];

//Declaration + Initilization
int[] numbers = new int[5];

//Initialization with values
int[] numbers = {10, 20, 30, 40, 50};
Java
// Accessing Elements
System.out.println(numbers[0]); //prints the first element
numbers[1] = 100; //sets second elelment to 100
Java
// Length of Array
System.out.println(numbers.length);

Types of Arrays
Single-Dimensional Array: int[] arr = new int[10];
Multi-Dimensional Array: int[][] matrix = new int[3][3];

Java
int[][] matrix = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};
System.out.println(matrix[1][2]); //Outputs 6

Access Modifiers

Access modifiers are used to set the access level of classes, methods, constructors, and variables. They control which parts of your code can access others.

1. public: The member is accessible from everywhere from any class in any package.
2. protected: The member is accessible within the same package and also in subclasses (even if they are in different packages).
3. default: If no access modifier is specified, the member is accessible only within the same package.
4. private: The member is accessible only within the same class.

String

String is a sequence of characters, It is a class in java and is a part of the java.lang package.
In java strings are immutable means, once created the contents of a string object cannot be changed. Any operation that seems to modify it actually creates a new string.

Java
//Declaration and Initialization
String s1 = "Hello";         // String literal
String s2 = new String("Hi"); // Using constructor

//Common String Methods
String str = "Java Programming";

str.length();                 // Returns the length
str.charAt(0);                // Returns 'J'
str.substring(5);             // Returns "Programming"
str.substring(0, 4);          // Returns "Java"
str.toLowerCase();            // Returns "java programming"
str.toUpperCase();            // Returns "JAVA PROGRAMMING"
str.contains("Java");         // Returns true
str.equals("Java");           // Checks exact match
str.equalsIgnoreCase("java");// Checks match ignoring case
str.replace("Java", "C++");   // Returns "C++ Programming"

//String Comparison
String a = "hello";
String b = "hello";
String c = new String("hello");

a == b;       // true (both refer to same object in string pool)
a == c;       // false (c is a new object)
a.equals(c);  // true (values are the same)

//String Concatenation
String a = "Hello";
String b = "World";
String result = a + " " + b;  // "Hello World"

Exception Handling

It is a mechanism that allows developers to handle runtime errors, so the normal flow of the application can be maintained.

An exception is an unwanted or unexpected event that occurs during the execution of a program, disrupting its normal flow. Example: Dividing by zero, File not found, Accessing an invalid array index.
Types of Exceptions
Checked Exception: Checked exceptions are handled compile-time. Example: IOException, SQLException, FileNotFoundException, etc.
Unchecked Exceptions: Unchecked exceptions are handled runtime. Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

try: Block of code to be tested for errors.
catch: Block to handle the exception
finally: Block that always executes.
throw: Used to throw an exception manually.
throws: Declares exceptions in method signature.

Java
public class Example {
    public static void main(String[] args) {
        try {
            int a = 5 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
        catch (Exception e) {
            System.out.println("General exception caught.");
        } 
        finally {
            System.out.println("Always runs.");
        }
    }
}

Java Collections

Java Collections is a framework that provides architectures, interfaces, and classes to store and manipulate groups of objects. It is a part of the java.util package.

Collection: Root interface for all collection classes
List: Ordered collection, allows duplicates. Example, ArrayList, LinkedList.
Set: Unordered collection, no duplicates allowed. Example, HashSet, LinkedHashSet, TreeSet.
Queue: It is used for holding elements before processing. Example, LinkedList, PriorityQueue.
Deque: It is double-ended queue. Example, ArrayDeque.
Map: It stores key-value pairs. Example, HashMap, TreeMap, LinkedHashMap.

Will update soon…..

Scroll to Top