[Go to site: main page, start]

0% found this document useful (0 votes)
3 views23 pages

Java Programming Notes

This document provides comprehensive notes on Java programming, covering topics such as the basics of Java, variables, data types, control statements, arrays, methods, object-oriented programming principles, and access modifiers. It includes syntax, examples, and diagrams for quick revision and exam preparation. The content is structured to facilitate understanding of key concepts and practical applications in Java.

Uploaded by

itsharishpatil01
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)
3 views23 pages

Java Programming Notes

This document provides comprehensive notes on Java programming, covering topics such as the basics of Java, variables, data types, control statements, arrays, methods, object-oriented programming principles, and access modifiers. It includes syntax, examples, and diagrams for quick revision and exam preparation. The content is structured to facilitate understanding of key concepts and practical applications in Java.

Uploaded by

itsharishpatil01
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 PROGRAMMING

Complete Notes

Simple one-line explanations • Syntax • Examples • Diagrams

Prepared for quick revision and exam preparation


Java Programming Notes Quick Revision Guide

1. Introduction to Java

1.1 What is Java?


Java is a high-level, object-oriented programming language that is platform-independent because of the JVM.
• Write Once, Run Anywhere (WORA) — code compiles to bytecode that runs on any device with a JVM.
• Developed by Sun Microsystems (1995), now owned by Oracle.
• Used for web apps, Android apps, enterprise software, and more.

1.2 JDK, JRE and JVM


JDK is used to develop Java programs, JRE is used to run them, and JVM actually executes the bytecode.

JDK (Java Development Kit)

JRE (Java Runtime Environment)

JVM (Java Virtual Machine)

Runs the .class bytecode

JDK = JRE + Compiler/Tools | JRE = JVM + Libraries

1.3 First Java Program


Every Java application starts execution from the main() method inside a class.
Syntax:

class ClassName {
public static void main(String[] args) {
// code
}
}

Example:

public class HelloWorld {


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

1.4 Compiling and Running


Java source code (.java) is compiled into bytecode (.class) and then run by the JVM.
Syntax:

javac [Link] // compiles to [Link]


java FileName // runs the program

Page 2
Java Programming Notes Quick Revision Guide

2. Variables, Data Types & Operators

2.1 Variables
A variable is a named memory location used to store data that can change during program execution.
Syntax:

dataType variableName = value;

Example:

int age = 20;


String name = "Harish";

2.2 Data Types


Java has two categories of data types: primitive (basic values) and non-primitive (objects/references).
• byte (1 byte), short (2 bytes), int (4 bytes), long (8 bytes) — whole numbers.
• float (4 bytes), double (8 bytes) — decimal numbers.
• char (2 bytes) — a single character, boolean — true/false.
• Non-primitive: String, Array, Class, Interface (store references, not raw values).
Example:

int x = 10;
double price = 99.99;
char grade = 'A';
boolean isPassed = true;

2.3 Type Casting


Type casting means converting one data type into another, either automatically (widening) or manually
(narrowing).
Syntax:

// Widening (automatic)
double d = intValue;

// Narrowing (manual)
int i = (int) doubleValue;

Example:

int a = 10;
double b = a; // widening
double c = 9.7;
int d = (int) c; // narrowing, d = 9

Page 3
Java Programming Notes Quick Revision Guide

2.4 Operators
Operators are symbols used to perform operations on variables and values.
• Arithmetic: + - * / %
• Relational: == != > < >= <=
• Logical: && || !
• Assignment: = += -= *= /=
• Increment/Decrement: ++ --
Example:

int a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
[Link](a > b); // true

Page 4
Java Programming Notes Quick Revision Guide

3. Control Statements & Loops

3.1 if / else if / else


The if-else statement executes a block of code only when a given condition is true or false.
Syntax:

if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}

Example:

int marks = 75;


if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 60) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}

3.2 switch Statement


The switch statement selects one of many code blocks to execute based on the value of a variable.
Syntax:

switch (expression) {
case value1:
// code
break;
default:
// code
}

Example:

int day = 2;
switch (day) {
case 1: [Link]("Mon"); break;
case 2: [Link]("Tue"); break;
default: [Link]("Other");
}

Page 5
Java Programming Notes Quick Revision Guide

3.3 for Loop


The for loop repeats a block of code a fixed number of times using a counter variable.
Syntax:

for (initialization; condition; update) {


// code
}

Example:

for (int i = 1; i <= 5; i++) {


[Link](i);
}

3.4 while Loop


The while loop repeats a block of code as long as the given condition remains true.
Syntax:

while (condition) {
// code
}

Example:

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

3.5 do-while Loop


The do-while loop executes the code block once before checking the condition, so it always runs at least once.
Syntax:

do {
// code
} while (condition);

Example:

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

3.6 break & continue


break exits a loop completely, while continue skips the current iteration and moves to the next one.
Example:

for (int i = 1; i <= 5; i++) {


if (i == 3) continue; // skips 3
if (i == 5) break; // stops at 5
[Link](i);
}

Page 6
Java Programming Notes Quick Revision Guide

4. Arrays & Strings

4.1 Arrays
An array is a fixed-size container that stores multiple values of the same data type in contiguous memory.
Syntax:

dataType[] arrayName = new dataType[size];


dataType[] arrayName = {value1, value2, ...};

Example:

int[] marks = {90, 85, 78};


[Link](marks[0]); // 90
[Link]([Link]); // 3

4.2 2D Arrays
A 2D array is an array of arrays, used to store data in rows and columns like a table.
Syntax:

dataType[][] name = new dataType[rows][cols];

Example:

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


[Link](grid[1][0]); // 3

4.3 Strings
A String is a sequence of characters, and in Java it is an immutable object (cannot be changed once created).
Syntax:

String s = "text";
String s2 = new String("text");

Example:

String name = "Java";


[Link]([Link]()); // 4
[Link]([Link]()); // JAVA
[Link]([Link](0)); // J

4.4 Common String Methods


Java's String class provides built-in methods to search, compare, and modify text easily.
• length() — returns number of characters.
• substring(start, end) — extracts part of a string.
• equals() — compares two strings for equal content.
• concat() or + — joins two strings together.
• trim() — removes leading and trailing spaces.
Example:

String a = "Hello";
String b = "World";
[Link]([Link](" " + b)); // Hello World
[Link]([Link]("Hello")); // true

Page 7
Java Programming Notes Quick Revision Guide

4.5 StringBuilder
StringBuilder is a mutable sequence of characters, used when a String needs to be modified frequently for
better performance.
Syntax:

StringBuilder sb = new StringBuilder();


[Link]("text");

Example:

StringBuilder sb = new StringBuilder("Java");


[Link](" Rocks");
[Link](sb); // Java Rocks

Page 8
Java Programming Notes Quick Revision Guide

5. Methods

5.1 Defining a Method


A method is a named block of reusable code that performs a specific task and can be called multiple times.
Syntax:

returnType methodName(parameters) {
// code
return value;
}

Example:

int add(int a, int b) {


return a + b;
}

// calling it
int result = add(5, 3); // 8

5.2 Method Parameters & Return Types


Parameters let a method receive input values, and the return type defines what kind of value it sends back.
Example:

void greet(String name) { // no return value


[Link]("Hi " + name);
}
double square(double n) { // returns a double
return n * n;
}

5.3 Method Overloading


Method overloading means having multiple methods with the same name but different parameter lists in the
same class.
Example:

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


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

5.4 Static vs Instance Methods


A static method belongs to the class itself, while an instance method belongs to an object of the class.
Example:

class MathUtil {
static int square(int n) { return n * n; } // called as [Link](5)
}

Page 9
Java Programming Notes Quick Revision Guide

6. OOP Basics: Class, Object & Constructor

6.1 Class
A class is a blueprint or template that defines the properties (fields) and behaviors (methods) of an object.
Syntax:

class ClassName {
// fields
// methods
}

Example:

class Student {
String name;
int age;

void display() {
[Link](name + " - " + age);
}
}

6.2 Object
An object is a real instance of a class created in memory using the 'new' keyword.
Syntax:

ClassName obj = new ClassName();

Example:

Student s1 = new Student();


[Link] = "Harish";
[Link] = 20;
[Link](); // Harish - 20

Page 10
Java Programming Notes Quick Revision Guide

6.3 Constructor
A constructor is a special method used to initialize an object, automatically called when the object is created.
• Has the same name as the class and no return type.
• Default constructor — auto-provided if none is written.
• Parameterized constructor — accepts arguments to set initial values.
Syntax:

class ClassName {
ClassName(parameters) {
// initialization
}
}

Example:

class Student {
String name;
Student(String n) { // parameterized constructor
name = n;
}
}
Student s1 = new Student("Harish");

6.4 this Keyword


The 'this' keyword refers to the current object and is often used to distinguish instance variables from
parameters.
Example:

class Student {
String name;
Student(String name) {
[Link] = name; // [Link] = field, name = parameter
}
}

6.5 static Keyword


The static keyword makes a variable or method belong to the class itself rather than to any single object.
Example:

class Counter {
static int count = 0; // shared by all objects
Counter() { count++; }
}

6.6 final Keyword


The final keyword is used to make a variable constant, a method non-overridable, or a class non-inheritable.
Example:

final double PI = 3.14159; // constant, cannot be reassigned


final class Utility { } // cannot be extended
final void show() { } // cannot be overridden

Page 11
Java Programming Notes Quick Revision Guide

7. The Four Pillars of OOP


Four Pillars of OOP

Encapsulation Abstraction Inheritance Polymorphism

7.1 Encapsulation
Encapsulation means binding data and methods together in a class while hiding the internal details using
private fields and public getters/setters.
Syntax:

private dataType field;


public dataType getField() { return field; }
public void setField(dataType val) { field = val; }

Example:

class Account {
private double balance;
public double getBalance() { return balance; }
public void setBalance(double b) { balance = b; }
}

7.2 Inheritance
Inheritance allows a class (child) to acquire the fields and methods of another class (parent) using the
'extends' keyword.
Syntax:

class Child extends Parent {


// additional fields/methods
}

Example:

class Animal {
void eat() { [Link]("eating"); }
}
class Dog extends Animal {
void bark() { [Link]("barking"); }
}
// Dog d = new Dog(); [Link](); [Link]();

Page 12
Java Programming Notes Quick Revision Guide

A A A

B B

B C
Single C

Multilevel Hierarchical

Note: Java does NOT support multiple inheritance with classes (only via interfaces).

7.3 Polymorphism
Polymorphism means one action can be performed in different ways, achieved through method overloading
(compile-time) and method overriding (runtime).

7.3.1 Method Overriding


Method overriding happens when a subclass provides its own specific implementation of a method already
defined in its parent class.
Syntax:

class Parent {
void show() { }
}
class Child extends Parent {
@Override
void show() { } // same signature as parent
}

Example:

class Animal {
void sound() { [Link]("Some sound"); }
}
class Cat extends Animal {
@Override
void sound() { [Link]("Meow"); }
}

7.4 Abstraction
Abstraction means hiding the implementation details and showing only the essential features, achieved using
abstract classes and interfaces.

Page 13
Java Programming Notes Quick Revision Guide

7.4.1 Abstract Class


An abstract class cannot be instantiated on its own and may contain both abstract (unimplemented) and
normal methods.
Syntax:

abstract class ClassName {


abstract void methodName(); // no body
void normalMethod() { } // has a body
}

Example:

abstract class Shape {


abstract double area();
}
class Circle extends Shape {
double radius = 5;
double area() { return 3.14 * radius * radius; }
}

7.4.2 Interface
An interface is a fully abstract type that only declares method signatures, which implementing classes must
define using 'implements'.
Syntax:

interface InterfaceName {
void methodName(); // abstract by default
}
class ClassName implements InterfaceName {
public void methodName() { }
}

Example:

interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() { [Link]("Car started"); }
}

Page 14
Java Programming Notes Quick Revision Guide

8. Packages & Access Modifiers

8.1 Packages
A package is a namespace that groups related classes and interfaces together to keep the project organized.
Syntax:

package packageName;
import [Link];

Example:

package [Link];

import [Link]; // built-in package


import [Link]; // user-defined package

8.2 Access Modifiers


Access modifiers control the visibility of classes, fields, and methods to other classes.
• public — accessible from anywhere.
• private — accessible only within the same class.
• protected — accessible within the same package and by subclasses.
• default (no modifier) — accessible only within the same package.
Example:

public class Student {


private String name; // only inside this class
protected int age; // package + subclasses
public void show() { } // accessible everywhere
}

Page 15
Java Programming Notes Quick Revision Guide

9. Exception Handling

9.1 What is an Exception?


An exception is an unwanted event that disrupts the normal flow of a program during execution.

Throwable

Exception Error

Checked Unchecked■(RuntimeException)

Checked = must handle at compile time | Unchecked = occurs at runtime

9.2 try-catch-finally
The try block contains risky code, catch handles the exception if it occurs, and finally always executes
regardless of the outcome.
Syntax:

try {
// risky code
} catch (ExceptionType e) {
// handle exception
} finally {
// always runs
}

Example:

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

Page 16
Java Programming Notes Quick Revision Guide

9.3 throw and throws


'throw' is used to manually raise an exception, while 'throws' declares that a method might raise an exception.
Syntax:

throw new ExceptionType("message");


returnType methodName() throws ExceptionType { }

Example:

void checkAge(int age) throws Exception {


if (age < 18) {
throw new Exception("Not eligible to vote");
}
}

9.4 Custom Exceptions


A custom exception is a user-defined class that extends Exception to represent a specific application error.
Syntax:

class MyException extends Exception {


MyException(String message) {
super(message);
}
}

Example:

class InsufficientFundsException extends Exception {


InsufficientFundsException(String msg) { super(msg); }
}
// throw new InsufficientFundsException("Balance too low");

Page 17
Java Programming Notes Quick Revision Guide

10. Multithreading

10.1 What is a Thread?


A thread is the smallest unit of a program that can run independently, allowing multiple tasks to execute at the
same time.

10.2 Creating a Thread (extends Thread)


A thread can be created by extending the Thread class and overriding its run() method.
Syntax:

class MyThread extends Thread {


public void run() {
// code to run
}
}
MyThread t = new MyThread();
[Link]();

Example:

class MyThread extends Thread {


public void run() {
[Link]("Thread running");
}
}
MyThread t1 = new MyThread();
[Link]();

10.3 Creating a Thread (implements Runnable)


A thread can also be created by implementing the Runnable interface, which is preferred when a class already
extends another class.
Syntax:

class MyRunnable implements Runnable {


public void run() {
// code to run
}
}
Thread t = new Thread(new MyRunnable());
[Link]();

Example:

class Task implements Runnable {


public void run() {
[Link]("Task running");
}
}
Thread t1 = new Thread(new Task());
[Link]();

10.4 Thread Lifecycle


A thread moves through five states during its life: New, Runnable, Running, Blocked/Waiting, and Terminated.

Page 18
Java Programming Notes Quick Revision Guide

11. Collections Framework

11.1 What is the Collections Framework?


The Collections Framework is a set of ready-made classes and interfaces used to store and manipulate
groups of objects.

Collection

List Set Queue Map*

ArrayList■LinkedList HashSet■TreeSet PriorityQueue■ArrayDeque

*Map is a separate hierarchy (not part of Collection)

11.2 ArrayList
ArrayList is a resizable array that allows fast access and permits duplicate elements.
Syntax:

ArrayList<Type> list = new ArrayList<>();

Example:

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


[Link]("Amit");
[Link]("Riya");
[Link]([Link](0)); // Amit

11.3 HashMap
HashMap stores data in key-value pairs and allows fast lookup of a value using its unique key.
Syntax:

HashMap<KeyType, ValueType> map = new HashMap<>();

Example:

HashMap<String, Integer> marks = new HashMap<>();


[Link]("Amit", 85);
[Link]([Link]("Amit")); // 85

Page 19
Java Programming Notes Quick Revision Guide

11.4 HashSet
HashSet stores a collection of unique elements and does not allow duplicate values.
Syntax:

HashSet<Type> set = new HashSet<>();

Example:

HashSet<Integer> nums = new HashSet<>();


[Link](10);
[Link](10); // duplicate, ignored
[Link]([Link]()); // 1

Page 20
Java Programming Notes Quick Revision Guide

12. Generics, Lambda Expressions & File Handling

12.1 Generics
Generics allow a class or method to work with any data type while providing type safety at compile time.
Syntax:

class ClassName<T> {
T value;
}

Example:

class Box<T> {
T item;
void set(T item) { [Link] = item; }
T get() { return item; }
}
Box<String> b = new Box<>();
[Link]("Hello");

12.2 Lambda Expressions


A lambda expression is a short way to write an anonymous function, mainly used to implement functional
interfaces.
Syntax:

(parameters) -> { body }

Example:

Runnable r = () -> [Link]("Running");


[Link]();

// with a functional interface


Comparator<Integer> comp = (a, b) -> a - b;

12.3 Functional Interface


A functional interface is an interface with exactly one abstract method, and it is commonly used with lambda
expressions.
Syntax:

@FunctionalInterface
interface InterfaceName {
void method();
}

Example:

@FunctionalInterface
interface Greeting {
void greet(String name);
}
Greeting g = (name) -> [Link]("Hi " + name);
[Link]("Harish");

Page 21
Java Programming Notes Quick Revision Guide

12.4 File Handling


Java's File and I/O classes are used to create, read, write, and delete files on the system.
Syntax:

File f = new File("[Link]");


FileWriter fw = new FileWriter(f);
[Link]("text");
[Link]();

Example:

import [Link].*;

FileWriter writer = new FileWriter("[Link]");


[Link]("Hello File");
[Link]();

Scanner sc = new Scanner(new File("[Link]"));


while ([Link]()) {
[Link]([Link]());
}

Page 22
Java Programming Notes Quick Revision Guide

13. Wrapper Classes & Quick Revision

13.1 Wrapper Classes


Wrapper classes convert primitive data types into objects so they can be used with collections and generics.
• int -> Integer, double -> Double, char -> Character, boolean -> Boolean
• Autoboxing — automatic conversion of primitive to wrapper object.
• Unboxing — automatic conversion of wrapper object back to primitive.
Example:

int a = 10;
Integer obj = a; // autoboxing
int b = obj; // unboxing
[Link]([Link]("25") + 5); // 30

13.2 Quick Keyword Summary


These are the most commonly confused keywords, grouped here for fast last-minute revision.
• this -> refers to the current object.
• super -> refers to the parent class (used to call parent constructor/methods).
• static -> belongs to the class, shared by all objects.
• final -> makes a variable constant, method non-overridable, or class non-inheritable.
• abstract -> a class/method with no full implementation, must be completed by a subclass.
Example:

class Animal {
void sound() { [Link]("Animal sound"); }
}
class Dog extends Animal {
void sound() {
[Link](); // calls parent method
[Link]("Bark");
}
}

Page 23

You might also like