java is a high- level, class-based, object-oriented programming language. Which developed by Sun Microsystems in 1995. It follows the principle: "Write Once, Run Anywhere".
Java was originally designed by James Gosling at Sun Microsystems. Originally called Oak, it was renamed Java in 1995. Sun Microsystem was acquired by Oracle in 2010.
| Year | Event |
| 1991 | Project Oak started by James Gosling at Sun Microsystems |
| 1995 | Java 1.0 released, renamed from Oak to Java |
| 1996 | JDK 1.0 officially released |
| 2004 | Java 5 (Tiger) - Generics, Annotations, Enums |
| 2010 | Oracle acquires Sun Microsystems |
| 2014 | Java 8 - Lambda expressions, Stream API |
| 2017 | Java 9 - Module System |
| 2021 | Java 17 LTS, Java 21 LTS and beyond |
| Feature | Description |
| Simple | Easy syntax, remove complex features like pointers. |
| Object- oriented | Everything is an object, supports encapsulation, inheritance, polymorphism, abstraction |
| Platform Independent | Complied to bytecode, runs on any OS with JVM |
| Secure | No explicit pointer, bytecode verification, security manager |
| Robust | Strong memory management, exception handeling, type checking |
| Multithreaded | Built-in support for concurrent programming |
| High Performance |
JIT compiler optimizes bytecode at runtime |
| Distributed |
Built-in networking support (RMI, CORBA) |
| Dynamic |
Classes loaded at runtime; supports reflection |
| Architecture Neutral |
Bytecode not tied to any hardware architecture |
Understanding the Java ecosystem is fundamental:
JVM (Java Virtual Machine)
Java Virtual Machine (JVM) is a virtual machine that executes Java bytecode. It enables Java programs to run on different operating systems without modification.
Work of JVM
Features :
JRE (Java Runtime Environment)
The JRE provides the environment required to run Java applications. It contains the JVM and supporting libraries
Work of JRE:
Components of JRE:
Features:
JDK (Java Development Kit)
The JDK is a complete package for Java development. It contains JRE along with development tools.
Work of JDK:
Important JDK Tools:
jar – Archive Tooljava – Program Launcherjdb – Debuggerjavac – Java Compilerjavadoc – Documentation GeneratoFeatures:
Java Program Structure
Every Java program must follow a specific structure:
| // File: HelloWorld.java import java.util.Scanner; // 2. Import statements (optional) public class HelloWorld { // 3. Class declaration (must match filename // Instance variable String message; // 4. Main method - entry point of every Java program public static void main(String[] args) { // 5. Statements System.out.println("Hello, World!"); } } |
Explain:
public : Access modifier - visible to all
class HelloWorld : Class name must match the file name exactly
public static void main : Entry point - JVM calls this method to start the program
String[ ] args : Command - line arguments passed to the program
System.out.println() : Prints text to console with a newkine at the end
Note: - The class name Must match the filename. - Java is case-sensitive ('main' and 'Main' are different) |
Comments are non-executable statements used to explain the code. The Java compiler ignores comments entirely. They improve code readability and documentation.
Single-Line Comment
Syntax: // comment text
| // This is a single-line comment int age = 20; // age of the student // You can also use it to temporarily disable code. System.out.println("This line is disabled"); |
Syntax: /* comment */
Used to generate API documentation using the javadoc tool. Placed before classes, methods, and fields
| /* * This class represents a Student. * * @author YourName * @version 1.0 */ public class Student { /* * Calculates the grade of a student. * * @param marks marks obtained (0-100) * @return grade as a character (A/B/C/F) */ public char getGrade(int marks) { if (marks >= 90) return 'A'; else if (marks >= 75) return 'B'; else if (marks >= 60) return 'C'; else return 'F'; } } |
Syntax: /** comment */
Used to generate API documentation using the javadoc tool. Placed before classes, methods, and fields
| /** * This class represents a Student. * * @author YourName * @version 1.0 */ public class Student { /** * Calculates the grade of a student. * * @param marks marks obtained (0-100) * @return grade as a character (A/B/C/F) */ public char getGrade(int marks) { if (marks >= 90) return 'A'; else if (marks >= 75) return 'B'; else if (marks >= 60) return 'C'; else return 'F'; } } |
A variable is a named memory location used to store data.
1. Local Variable
Declared inside a method, constructor, or block.
public void display(){ int x = 10; System.out.println(x); } |
2. Instance Variable
Declared inside a class but outside methods, without static.
class Student { String name; // instance variable } |
3. Static (Class) Variable
Declared with the static keyword.
class Student { static String school = "ABC School"; } |
| Note: Java does not have true global variables like some languages. A public static variable is often used when global-like access is needed. |
| Variable Naming Rules |
|
Data types specify the type and size of data that can be stored in a variable. Java is a statically-typed language — every variable must have a declared type
Java has two categories of data types:
Primitive Data Types
| Type | Size | Default | Example |
| byte | 1 byte | 0 | byte b = 100; |
| short | 2 bytes | 0 | short x = 500; |
| int | 4 bytes | 0 | int x = 100000; |
| long | 8 bytes | 0L | long l = 100L; |
| float | 4 bytes | 0.0f | float f = 3.14f; |
| double | 9 bytes | 0.0d | double d = 3.14; |
| char | 2 bytes | \u000 | char c = 'A'; |
| boolean | 1 bit | false | boolean b = true; |
Example of each Primitive Type:
public class PrimitiveDemo { public static void main(String[] args) { //byte smallest integer type byte b = 127; // range: -128 to 127 System.out.println("byte: " + b); //short larger than byte short s = 32767; // range: -32768 to 32767 System.out.println("short: " + s); //int most commonly used integer type int i = 2147483647; // range: -2147483648 to System.out.println("int: " + i); //long largest integer type long l = 9223372036854775807L; // range: -9223372036854775808 to 9223372036854775807 System.out.println("long: " + l); //float single-precision floating point float f = 3.14f; // range: approximately ±1.4E-45 to ±3.4E38 System.out.println("float: " + f); //double double-precision floating point double d = 3.141592653589793; // range: approximately ±4.9E-324 to ±1.7E308 System.out.println("double: " + d); //char single 16-bit Unicode character char c = 'A'; // range: '\u0000' (0) to '\uffff' (65535) System.out.println("char: " + c); //boolean true or false boolean bool = true; System.out.println("boolean: " + bool); } } |
| Note Common Mistake: float needs 'f' suffix (3.14f), long needs 'L' suffix (100L). Without suffix, 3.14 is treated as double. Memory Tip: byte(1) < short(2) < int(4) < long(8) — doubles in size each time! |
Non-Primitive Data Types
| String String is an immutable sequence of characters. It is an object of the java.lang.String class. |
public class PrimitiveDemo { public static void main(String[] args) { //example of string data type String name = "John Doe"; String greeting = "Hello, " + name + "!"; System.out.println(greeting); //Useful string methods String s = "Biswas Parajuli"; System.out.println("Length of the string: " + s.length()); //output => 16 System.out.println("Uppercase: " + s.toUpperCase()); //output => BISWAS PARAJULI System.out.println("Lowercase: " + s.toLowerCase()); //output => biswas parajuli System.out.println("Substring (0, 6): " + s.substring(0, 6)); //output => Biswas System.out.println("Index of 'Parajuli': " + s.indexOf("Parajuli")); //output => 7 System.out.println("Replace 'a' with 'o': " + s.replace('a', 'o')); //output => Biswas Porajuli System.out.println("Trimmed string: '" + s.trim() + "'"); //output => 'Biswas Parajuli' System.out.println("Character at index 0: " + s.charAt(0)); //output => B System.out.println("Does the string contain 'Parajuli'? " + s.contains("Parajuli")); //output => true } } |
| Key Fact: Strings are immutable — once created, their value cannot change. Operations create new String objects |
| Arrays |
public class PrimitiveDemo { public static void main(String[] args) { //example of array int[] myArray = new int[5]; myArray[0] = 10; // create with new keyword int[] myArray2 = new int[5]; myArray2[0] = 20; myArray2[1] = 30; // accessing elements of the array System.out.println("First element of myArray: " + myArray[0]); System.out.println("First element of myArray2: " + myArray2[0]); System.out.println("Second element of myArray2: " + myArray2[1]); //2d array int[][] my2DArray = new int[3][4]; my2DArray[0][0] = 1; System.out.println("Element at [0][0]: " + my2DArray[0][0]); } } |
| Important: Array index starts at 0. Last element index = length - 1. Accessing out-of-range index throws ArrayIndexOutOfBoundsException. |
A constant is a variable whose value cannot be changed once assigned. In Java, constants are declared using the final keyword
Syntax:
| final dataType constant_name = value;
|
Example:
public class PrimitiveDemo { //example of constant static final double PI = 3.14159; static final int MAX_SIZE = 100; static final String GREETING = "Hello, World!"; public static void main(String[] args) { final int MAX_SIZE = 50; // This will cause a compile-time error System.out.println("The value of PI is: " + PI); System.out.println("The maximum size is: " + MAX_SIZE); System.out.println(GREETING); } } |
| Usage Of Final | Description |
| final variable | Value cannot be reassigned after initialization |
| final method | cannot be overridden in a subclass |
| final class | Cannot be extended |
| 💡 Best Practice : Use 'static final' for class-level constants so they're shared and accessible without creating object 💡 Important : A final variable must be initialized either at declaration or in the constructor — but only once! |
An operator performs an operation on operands. Java provides a rich set of operators.
Used to perform mathematical calculations
| Operator | Name | Example | Result |
| + | Addition | 10 + 3 | 13 |
| - | Subtraction | 10 - 3 | 7 |
| * | Multiplication | 10 * 3 | 30 |
| / | Division | 10 / 3 | 3 (integer division) |
| % | Modulus | 10 % 3 | 1 (remaining) |
Example:
public class ArithmeticDemo { public static void main(String[] args) { //arithmetic operators int a = 10; int b = 5; //addition System.out.println("a + b = " + (a + b)); //output: a + b = 15 //subtraction System.out.println("a - b = " + (a - b)); //output: a - b = 5 //multiplication System.out.println("a * b = " + (a * b)); //output: a * b = 50 //division System.out.println("a / b = " + (a / b)); //output: a / b = 2 //modulus System.out.println("a % b = " + (a % b)); //output: a % b = 0 } } |
| 💡 Tricky: 10 / 3 = 3 (not 3.33) for int. Use 10.0/3 or cast to get decimal result 💡 Use case: Modulus (%) is very useful: to check even/odd (n%2==0), to get last digit (n%10), etc. |
Used to compare two values. Always returns a boolean (true or false)
| Operators | Name | Example | Result |
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 3 | true |
| > | Greater than | 5 > 3 | true |
| < | Less than | 5 < 3 | false |
| >= | Greater than or equal to | 5 >= 5 | true |
| <= | Less than or equal to | 3 <= 5 | true |
Example:
public class RelationalDemo { public static void main(String[] args) { //relational operators int a = 10; int b = 5; //greater than System.out.println("a > b = " + (a > b)); //output: a > b = true //less than System.out.println("a < b = " + (a < b)); //output: a < b = false //equal to System.out.println("a == b = " + (a == b)); //output: a == b = false //not equal to System.out.println("a != b = " + (a != b)); //output: a != b = true //greater than or equal to System.out.println("a >= b = " + (a >= b)); //output: a >= b = true //less than or equal to System.out.println("a <= b = " + (a <= b)); //output: a <= b = false } } |
| Common Mistake : Don't use == to compare Strings. Use .equals() method: str1.equals(str2). == compares references, not content. |
Used to combine multiple boolean conditions
| Operator | Name | Description | Example |
| && | Logical AND | true only if BOTH condition are true | (5>3) && (10>7) |
| | | | Logical OR | true if AT LEAST ONE condition is true | (5>3) | | (10<7) |
| ! | Logical NOT | REVERSES the boolean value | ! (5>3) |
Example:
public class LogicalDemo { public static void main(String[] args) { //logical operators int a = 10; int b = 5; System.out.println("a > b: " + (a > b)); // true System.out.println("a < b: " + (a < b)); // false System.out.println("a == b: " + (a == b)); // false System.out.println("a != b: " + (a != b)); // true } } |
| 💡 Short-circuit Evaluation: && stops at first false; || stops at first true. This is called short-circuit evaluation and can improve performance. |
Used to assign values to variables
x = 10
| Operator | Equivalent to | Example | Result |
| = | a = value | a = 10 | a = 10 |
| += | a = a + b | a += 5 | a = 15 |
| -= | a = a - b | a -= 5 | a = 5 |
| *= | a = a * b | a *= 2 | a = 20 |
| /= | a = a / b | a /= 4 | a = 2 |
| %= | a = a % b | a %= 3 | a = 1 |
Example
public class AssignmentDemo { public static void main(String[ ] args) { //assignment operator int x = 10; System.out.println("Value of x: " + x); //output will be: Value of x: 10 //addition assignment operator x += 5; // equivalent to x = x + 5 System.out.println("After addition assignment (x += 5): " + x); //output will be: After addition assignment (x += 5): 15 //subtraction assignment operator x -= 3; // equivalent to x = x - 3 System.out.println("After subtraction assignment (x -= 3): " + x); //output will be: After subtraction assignment (x -= 3): 12 //multiplication assignment operator x *= 2; // equivalent to x = x * 2 System.out.println("After multiplication assignment (x *= 2): " + x); //output will be: After multiplication assignment (x *= 2): 24 //division assignment operator x /= 4; // equivalent to x = x / 4 System.out.println("After division assignment (x /= 4): " + x); //output will be: After division assignment (x /= 4): 6 //modulus assignment operator x %= 3; // equivalent to x = x % 3 System.out.println("After modulus assignment (x %= 3): " + x); //output will be: After modulus assignment (x %= 3): 0 } } |
| 💡 Tip: Compound assignment operators are shorthand and also more readable. Prefer a += 5 over a = a + 5.
|
Work on a single operand
| Operator | Name | Example | Description |
| + | Unary plus | +a | Represent positive value |
| - | Unary minus | -a | Negates the value |
| ++ | Pre-increment | ++a | Increment first, then use value |
| ++ | Post-increment | a++ | Use value first, then increments |
| -- | Pre-decrement | --a | Decrements first, then uses value |
| -- | Post-decrement | a-- | Uses value first, then decrements |
Example:
public class UnaryOperators { public static void main(String[] args) { // Unary Operators int a = 10; System.out.println("Value of a: " + a); //output will be: Value of a: 10 // Unary minus operator int b = -a; System.out.println("Value of b: " + b); //output will be: Value of b: -10 // Unary plus operator int c = +a; System.out.println("Value of c: " + c); //output will be: Value of c: 10 // pre- Increment operator int d = ++a; System.out.println("Value of d: " + d); //output will be: Value of d: 11 // post- Increment operator int f = a++; System.out.println("Value of f: " + f); //output will be: Value of f: 11 // pre-Decrement operator int e = --a; System.out.println("Value of e: " + e); //output will be: Value of e: 11 // post-Decrement operator int g = a--; System.out.println("Value of g: " + g); //output will be: Value of g: 11 } } |
| 💡
Memory Trick: Pre(++a): Change then carry Post(a++): Carry then Change 💡 Important: Avoid using ++/-- inside complex expression like a = a++ + ++a; because this can confusing. |
Operate directly on binary (bit-level) representation of numbers.
| Operators | Name | Description | Example (a=5 , b=3) |
| & | Bitwise AND | 1 only if both bits are 1 |
5 & 3 = 1 |
| | | Bitwise OR | 1 if at least one bit is 1 | 5 | 3 = 7 |
| ^ | Bitwise XOR | 1 if bits are different | 5 ^ 3 = 6 |
| ~ | Bitwise NOT | Inverts all bits | ~5 = - 6 |
| << | Left Shift | Sheft bits left | 5 << 1 = 10 |
| >> | Right Shift |
Shift bits right |
5 >> 1 = 2 |
| >>> |
Unsigned Right Shift |
Shift right, fill with 0 |
5 >>> 1 = 2 |
Example:
public class Bitwise { public static void main(String[] args) { //bitwise operators int a = 5; // 0101 in binary int b = 3; // 0011 in binary System.out.println("a & b: " + (a & b)); // 0001 in binary, which is 1 System.out.println("a | b: " + (a | b)); // 0111 in binary, which is 7 System.out.println("a ^ b: " + (a ^ b)); // 0110 in binary, which is 6 System.out.println("~a: " + (~a)); // 1010 in binary System.out.println("a << 1: " + (a << 1)); // 1010 in binary, which is 10 System.out.println("a >> 1: " + (a >> 1)); // 0010 in binary, which is 2 System.out.println("a >>> 1: " + (a >>> 1)); // 0010 in binary, which is 2 } } |
| 💡 Practical Use: Left shift << is a fast way to multiply by powers of 2: a << 3 = a * 8 💡 Practical Use: Bitwise AND with 1 checks if a number is odd: if (n & 1) → odd |
The ternary operator is a compact if-else written in one line. It takes three operands.
Syntax:
| result = (condition) ? valueIfTrue : valueIfFalse;
|
Example:
import java.util.Scanner; public class TernaryOperators { public static void main(String[] args) { //ternary operator is a shortcut for if-else statement //syntax: condition ? expression1 : expression2 Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); String result = (number % 2 == 0) ? "Even" : "Odd"; System.out.println("The number is " + result); scanner.close(); } } |
| 💡 Best Practice: Use ternary for simple single-line conditions. For complex logic with multiple statements, use if-else for readability. |
PDF बनाउँदैछ…