0% found this document useful (0 votes)
1 views7 pages

Java Basics

This document serves as a concise reference guide to core Java concepts, covering topics such as the Java language, JVM, data types, operators, control flow, object-oriented programming, exception handling, strings, and the collections framework. It explains key components like JDK, JRE, and JVM, and provides examples of Java syntax and programming principles. The guide concludes by encouraging further exploration of advanced Java topics.
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)
1 views7 pages

Java Basics

This document serves as a concise reference guide to core Java concepts, covering topics such as the Java language, JVM, data types, operators, control flow, object-oriented programming, exception handling, strings, and the collections framework. It explains key components like JDK, JRE, and JVM, and provides examples of Java syntax and programming principles. The guide concludes by encouraging further exploration of advanced Java topics.
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 Basics

A concise reference guide to core Java concepts

1. Introduction to Java & the JVM/JDK/JRE


2. Variables and Data Types
3. Operators
4. Control Flow Statements
5. Arrays
6. Object-Oriented Programming
7. Exception Handling
8. Strings
9. Collections Framework (Overview)
1. Introduction to Java
Java is a statically-typed, object-oriented, platform-independent programming language. Code is compiled to
bytecode (.class files) which runs on the Java Virtual Machine (JVM), making Java “write once, run
anywhere.”

JDK vs JRE vs JVM

Component Purpose

JVM Executes bytecode; provides memory management (heap, garbage collection)

JRE JVM + core libraries; needed to run Java applications

JDK JRE + compiler (javac) + dev tools; needed to build Java applications

A Minimal Java Program


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Every standalone Java program needs a class containing a main method — the entry point the JVM invokes
when the program starts.

2. Variables and Data Types


Java is statically typed: every variable's type is declared and checked at compile time.

Primitive Types
Type Size Example

byte 8-bit byte b = 10;

short 16-bit short s = 200;

int 32-bit int x = 42;

long 64-bit long l = 42L;

float 32-bit float f = 3.14f;

double 64-bit double d = 3.14159;

char 16-bit char c = 'A';

boolean 1-bit boolean flag = true;


Non-primitive (reference) types include String, arrays, classes, and interfaces — these store a reference to
an object on the heap rather than the value itself.

Type Inference with var (Java 10+)


var count = 10; // inferred as int
var name = "Sai"; // inferred as String

3. Operators
● Arithmetic: + - * / % (modulo)

● Relational: == != > < >= <=

● Logical: && || !

● Assignment: = += -= *= /= %=

● Increment/Decrement: ++ --

● Bitwise: & | ^ ~ << >> >>>

● Ternary: condition ? valueIfTrue : valueIfFalse

int a = 10, b = 3;
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1
String result = (a > b) ? "a is bigger" : "b is bigger";

4. Control Flow Statements


Conditional Statements
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else {
grade = "C";
}

switch (day) {
case MONDAY, FRIDAY -> [Link]("Busy day");
case SATURDAY, SUNDAY -> [Link]("Weekend");
default -> [Link]("Midweek");
}

Loops
for (int i = 0; i < 5; i++) {
[Link](i);
}

for (String name : names) { // enhanced for-loop


[Link](name);
}

int i = 0;
while (i < 5) {
[Link](i);
i++;
}

int j = 0;
do {
[Link](j);
j++;
} while (j < 5);

break exits a loop entirely; continue skips to the next iteration.

5. Arrays
Arrays are fixed-size, ordered collections of elements of the same type, indexed from 0.

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


String[] names = new String[3];
names[0] = "Alice";

int[][] matrix = new int[3][3]; // 2D array

for (int n : numbers) {


[Link](n);
}

[Link]([Link]); // 5

6. Object-Oriented Programming
Java is built around four core OOP principles: encapsulation, inheritance, polymorphism, and abstraction.

Classes and Objects


public class Employee {
private String name;
private double salary;

public Employee(String name, double salary) {


[Link] = name;
[Link] = salary;
}

public double getSalary() {


return salary;
}
}

Employee emp = new Employee("Sai", 90000);

Encapsulation
Bundling data (fields) and behavior (methods) together, and restricting direct access to internal state using
access modifiers (private, protected, public, package-private), typically exposing controlled access via
getters/setters.

Inheritance
public class Manager extends Employee {
private int teamSize;

public Manager(String name, double salary, int teamSize) {


super(name, salary);
[Link] = teamSize;
}
}

A subclass inherits fields and methods from its superclass using extends. Java supports single inheritance
for classes (one direct superclass) but multiple inheritance via interfaces.

Polymorphism
Employee e = new Manager("Priya", 120000, 5); // upcasting
[Link](); // runtime resolves to the correct method (dynamic dispatch)

// Method overloading (compile-time polymorphism)


int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }

Abstraction
abstract class Shape {
abstract double area();
}

interface Drawable {
void draw();
}

class Circle extends Shape implements Drawable {


double radius;
Circle(double radius) { [Link] = radius; }

double area() { return [Link] * radius * radius; }


public void draw() { [Link]("Drawing circle"); }
}
An abstract class can have both implemented and unimplemented methods and cannot be instantiated
directly. An interface defines a contract that implementing classes must fulfill; since Java 8, interfaces can
also have default and static methods.

7. Exception Handling
Exceptions represent abnormal conditions during execution. Java distinguishes checked exceptions (must
be declared or caught, e.g. IOException) from unchecked exceptions (RuntimeException and its
subclasses, e.g. NullPointerException).

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
} finally {
[Link]("Always runs");
}

// try-with-resources: auto-closes resources implementing AutoCloseable


try (BufferedReader reader = new BufferedReader(new FileReader("[Link]"))) {
String line = [Link]();
} catch (IOException e) {
[Link]();
}

// Custom exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

8. Strings
Strings in Java are immutable — every modification creates a new String object. Literal strings are stored in
a special memory area called the String pool for reuse.

String a = "hello";
String b = "hello";
[Link](a == b); // true (same pool reference)

String c = new String("hello");


[Link](a == c); // false (different object)
[Link]([Link](c)); // true (same content)

// StringBuilder for mutable, efficient string building


StringBuilder sb = new StringBuilder();
[Link]("Hello").append(", ").append("World!");
String result = [Link]();
9. Collections Framework (Overview)
Interface Common Implementations Notes

List ArrayList, LinkedList Ordered, allows duplicates

Set HashSet, TreeSet, LinkedHashSet No duplicates

Map HashMap, TreeMap, LinkedHashMap Key-value pairs

Queue ArrayDeque, PriorityQueue FIFO / priority ordering

List<String> names = new ArrayList<>();


[Link]("Sai");

Map<String, Integer> ages = new HashMap<>();


[Link]("Sai", 38);
[Link]((k, v) -> [Link](k + " is " + v));

End of guide — a solid foundation for exploring more advanced Java topics like generics, streams,
concurrency, and the module system.

You might also like