Core Java
Welcome to Core Java! This beginner-friendly guide will help you understand the building blocks of Java in a clear and simple way. Whether you’re completely new or revisiting, you’ll learn how Java works, how to write and run code, and how to apply concepts with confidence.
🔹 What is Java?
- Java is a high-level, object-oriented programming language.
• It was developed by Sun Microsystems (now owned by Oracle).
• Java is platform-independent, meaning your code runs on any system with Java installed (thanks to JVM – Java Virtual Machine).
• It’s used in Android apps, web applications, enterprise software, games, and more.
🔹 Key Features of Java
- Simple: Easy to learn if you know basic programming.
• Object-Oriented: Everything is treated as objects.
• Secure: Provides a secure environment for code execution.
• Platform Independent: Write once, run anywhere.
• Robust: Strong memory management and exception handling.
• Multithreaded: Allows multiple tasks to run concurrently.
🔹 How Java Works (Compilation & Execution)
- You write code in a `.java` file.
2. The Java compiler converts it to bytecode (`.class` file).
3. JVM interprets the bytecode and runs it on your system.
🔹 Installing Java on Your System
- Step 1: Download Java JDK (Java Development Kit) from Oracle’s official site.
• Step 2: Install it and set JAVA_HOME and PATH environment variables.
• Step 3: Use terminal/command prompt to check installation: `java -version`
🔹 Your First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, Java!”);
}
}
- Save this as HelloWorld.java
• Compile: `javac HelloWorld.java`
• Run: `java HelloWorld`
• Output: Hello, Java!
🔹 Java Syntax Basics
- Case-sensitive: `Hello` ≠ `hello`
• Class names start with uppercase
• Method names start with lowercase
• Statements end with semicolons
• Code blocks use curly braces `{}`
Java Environment Setup
To start Java programming, setting up the right environment is essential. This includes installing the Java Development Kit (JDK), setting up an editor or IDE, and configuring your system’s environment variables.
Step-by-Step Guide to Setting Up Java:
- Download Java JDK:
Visit the official Oracle website or use a distribution like OpenJDK. - Install Java:
Run the installer and follow the on-screen instructions. - Set Environment Variables:
Add the JDK bin directory to your system’s PATH. - Verify Installation:
Open the terminal or command prompt and type ‘java -version’ and ‘javac -version’. - Choose an IDE or Code Editor:
Options include IntelliJ IDEA, Eclipse, VS Code, or simple text editors like Notepad++.
Helpful Tips for Beginners:
- Always use the latest LTS version of Java.
- Understand the difference between JRE and JDK.
- Use an IDE with autocomplete and error highlighting to make learning easier.
- Practice writing, compiling, and running simple programs.
- Use online resources like W3Schools, GeeksforGeeks, and Java documentation.
[Insert Image: Screenshot of JAVA_HOME and PATH configuration in environment variables]
Summary:
Setting up Java is your first step into the programming world. Make sure to install the correct version, configure your environment properly, and choose a comfortable code editor. Once you’re set up, you’re ready to write your first Java program!
Core Java for Beginners – Page 3
Understanding Java Program Structure
Before diving into complex concepts, it’s crucial to understand the basic structure of a Java program. Every Java program is composed of classes, methods, and statements that follow a specific syntax.
Basic Anatomy of a Java Program:
Here’s a simple program and explanation of its parts:
public class HelloJava {
public static void main(String[] args) {
System.out.println(“Welcome to Java!”);
}
}
Explanation of Each Part:
- public class HelloJava – Declares a class named HelloJava. The class name should match the filename.
- public static void main(String[] args) – This is the main method. Java program execution starts here.
- System.out.println(…) – This line prints text to the console.
- Curly braces {} – Define the beginning and end of class and method blocks.
- Semicolons ; – Used to terminate each statement in Java.
Common Mistakes to Avoid:
- Forgetting the semicolon at the end of a statement.
- Mismatched curly braces.
- Incorrect class or method names.
- Not saving the file with the exact class name (e.g., HelloJava.java).
Summary:
Understanding the structure of a Java program is your foundation. Once you grasp how classes, methods, and statements work together, you can build larger, more functional programs with ease. Practice writing small programs to reinforce this structure.
Core Java for Beginners – Page 4
Java Data Types and Variables
In Java, variables are containers that store data values. Each variable has a data type that determines the size and type of information it can hold. Understanding Java data types is essential to avoid errors and write efficient code.
Declaring a Variable in Java:
Syntax:
dataType variableName = value;
Example:
int age = 25;
Primitive Data Types:
Java has 8 primitive data types:
- byte – 1 byte, stores whole numbers from -128 to 127
- short – 2 bytes, stores numbers from -32,768 to 32,767
- int – 4 bytes, stores whole numbers (commonly used)
- long – 8 bytes, for larger whole numbers
- float – 4 bytes, stores decimal numbers
- double – 8 bytes, more precise decimal values
- boolean – stores true or false
- char – stores a single character, like ‘A’ or ‘z’
[Insert Image: Table Comparing Java Data Types – size, range, example]
Reference Data Types:
Reference types are used for objects and arrays. They store memory addresses, not the actual value.
Examples include:
• String
• Arrays
• Classes
• Interfaces
Type Conversion (Casting):
Java allows automatic and manual type conversion.
- Implicit Casting (Widening) – smaller to larger type:
int to long - Explicit Casting (Narrowing) – larger to smaller type:
double to int
Example:
int x = (int) 9.5; // x = 9
Summary:
Java variables are strongly typed, meaning each one must have a declared type. Knowing the right data type to use ensures efficient memory usage and helps prevent bugs. Practice creating variables of different types and performing conversions to solidify your understanding.
Core Java for Beginners – Page 5
Java Operators and Expressions
Operators in Java are special symbols or keywords that perform operations on variables and values. Understanding how to use operators will allow you to perform arithmetic, comparisons, logic checks, and more in your code.
1. Arithmetic Operators:
These are used for mathematical calculations:
- + (Addition): a + b
- – (Subtraction): a – b
- * (Multiplication): a * b
- / (Division): a / b
- % (Modulus): a % b (returns remainder)
2. Assignment Operators:
- = (Assign): x = 5
- += (Add and assign): x += 3 (same as x = x + 3)
- -= (Subtract and assign): x -= 2
- *= (Multiply and assign): x *= 2
- /= (Divide and assign): x /= 2
- %= (Modulus and assign): x %= 3
3. Comparison Operators:
- == (Equal to)
- != (Not equal to)
- > (Greater than)
- < (Less than)
- >= (Greater than or equal to)
- <= (Less than or equal to)
4. Logical Operators:
- && (Logical AND): true if both are true
- || (Logical OR): true if at least one is true
- ! (Logical NOT): reverses the boolean value
5. Unary Operators:
- + (Unary plus)
- – (Unary minus)
- ++ (Increment): increases value by 1
- — (Decrement): decreases value by 1
6. Ternary Operator:
A shortcut for `if-else` condition. Syntax:
condition ? value_if_true : value_if_false;
Example:
int result = (a > b) ? a : b;
[Insert Image: Table of Java Operators with Examples and Precedence Order]
Summary:
Java operators let you perform calculations and decision-making within your code. By combining them properly, you can write cleaner and more dynamic programs. Practice using all types of operators to better understand how they work together.
Core Java for Beginners – Page 6
Control Statements in Java
Control statements in Java allow you to control the flow of execution of your program. They help your code make decisions, repeat operations, or jump to specific parts.
Types of Control Statements:
Java has three main types of control statements:
- Decision-Making Statements (if, if-else, switch)
- Looping Statements (for, while, do-while)
- Branching Statements (break, continue, return)
1. Decision-Making Statements
➤ if Statement:
Executes a block if condition is true.
Example:
if (a > b) {
System.out.println(“A is greater”);
}
➤ if-else Statement:
Adds an alternate block when condition is false.
Example:
if (a > b) {
System.out.println(“A is greater”);
} else {
System.out.println(“B is greater”);
}
➤ switch Statement:
Used when multiple conditions are compared with the same variable.
Example:
switch(day) {
case 1: System.out.println(“Sunday”); break;
case 2: System.out.println(“Monday”); break;
default: System.out.println(“Other Day”);
}
2. Looping Statements
- for loop – Repeats code a fixed number of times.
- while loop – Repeats as long as condition is true.
- do-while loop – Similar to while, but executes at least once.
3. Branching Statements
- break – Exits the loop or switch.
- continue – Skips to the next iteration of a loop.
- return – Exits from the current method.
[Insert Image: Flowchart Showing if-else and Looping Flow]
Summary:
Control statements guide how your program makes decisions and repeats actions. Understanding them allows you to create dynamic, responsive applications. Try writing a simple program with loops and conditions to practice!
Core Java for Beginners – Page 7
Java Arrays – Working with Collections of Data
An array is a container object that holds a fixed number of values of a single data type. It’s one of the most useful ways to store and manage multiple values in Java programs.
Why Use Arrays?
- Arrays store multiple values under a single name.
- They reduce code complexity when working with related data.
- You can loop through arrays easily using `for` or `for-each` loops.
- They are useful for storing data like marks, names, temperatures, etc.
Declaring and Initializing Arrays:
- Declaration:
int[] numbers;
String[] names; - Allocation:
numbers = new int[5]; - Declaration + Initialization:
int[] numbers = {10, 20, 30, 40, 50};
Accessing Array Elements:
You can access elements using index (starting from 0).
Example:
System.out.println(numbers[2]); // Outputs 30
Looping Through an Array:
Using traditional for loop:
for(int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Using enhanced for-each loop:
for(int num : numbers) {
System.out.println(num);
}
[Insert Image: Java Array Memory Layout or Looping Visual]
Common Mistakes to Avoid:
- ArrayIndexOutOfBoundsException – trying to access index that doesn’t exist.
- Not initializing the array before use.
- Using wrong data types inside an array.
Summary:
Arrays are fundamental in Java for storing groups of data. Learn how to declare, initialize, and loop through arrays. Understanding arrays is the first step toward mastering more advanced data structures like lists and maps.
Core Java for Beginners – Page 8
Object-Oriented Programming (OOP) Concepts in Java
Java is a fully object-oriented programming language. Understanding its key principles helps you structure your code better and build scalable, reusable applications. Let’s dive into the four core pillars of OOP: Abstraction, Encapsulation, Inheritance, and Polymorphism.
🔹 1. Abstraction
Abstraction is the process of hiding complex implementation details and showing only essential features to the user.
Example: When you drive a car, you don’t need to know how the engine works — just how to steer, brake, and accelerate.
In Java:
– Achieved using abstract classes and interfaces.
– Example:
abstract class Animal {
abstract void makeSound();
}
🔹 2. Encapsulation
Encapsulation is the process of wrapping data and code together as a single unit. It restricts direct access to some of the object’s components, which means you can hide internal object details.
In Java:
– Achieved by making variables `private` and providing `public` getter/setter methods.
– Example:
public class Person {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
🔹 3. Inheritance
Inheritance allows a class to inherit properties and behaviors from another class.
This promotes code reuse and a hierarchical classification.
In Java:
– Use `extends` keyword.
– Example:
class Dog extends Animal {
void makeSound() {
System.out.println(“Bark”);
}
}
🔹 4. Polymorphism
Polymorphism means many forms. It allows one interface to be used for a general class of actions.
In Java:
– Achieved through method overloading and method overriding.
– Example:
class Shape {
void draw() {
System.out.println(“Drawing Shape”);
}
}
class Circle extends Shape {
void draw() {
System.out.println(“Drawing Circle”);
}
}
[Insert Image: Diagram of OOP Pillars: Abstraction, Encapsulation, Inheritance, Polymorphism]
🌟 Real-World Analogy:
Imagine a remote control:
– Abstraction: You press buttons without knowing internal wiring.
– Encapsulation: All circuits are protected inside.
– Inheritance: A universal remote inherits features from standard remotes.
– Polymorphism: Same button can behave differently on different devices.
Summary:
OOP is the foundation of Java programming. Mastering these concepts will help you write cleaner, more modular, and maintainable code. Try building small classes that demonstrate each principle to solidify your learning.
Core Java for Beginners – Page 9
Classes and Objects in Java
Everything in Java revolves around classes and objects. A class is a blueprint for creating objects, and objects are instances of classes.
🔸 What is a Class?
A class in Java is a user-defined data type. It acts as a blueprint that defines variables (fields) and methods (functions) that the created objects will have.
Syntax Example:
public class Car {
String color;
int speed;
void drive() {
System.out.println(“The car is moving”);
}
}
🔸 What is an Object?
An object is an instance of a class. When a class is defined, no memory is allocated. Memory is allocated only when an object is created.
Syntax Example:
Car myCar = new Car();
🔸 Members of a Class:
- Fields (variables): hold data or state.
- Methods (functions): define behavior or actions.
- Constructors: special methods used to initialize objects.
- Blocks and Nested Classes (advanced topics).
🔸 Constructor Example:
public class Car {
Car() {
System.out.println(“Car is created”);
}
}
🔸 Benefits of Using Classes & Objects:
- Organizes code and data into reusable modules.
- Enables code reuse through object instantiation.
- Supports encapsulation by keeping data secure.
- Allows abstraction to hide complexity from users.
[Insert Image: Diagram Showing Class Structure with Object Creation Flow]
🔸 Common Mistakes to Avoid:
- Not initializing the object with `new` keyword.
- Forgetting to define a constructor or method properly.
- Mismatch between class name and filename.
- Attempting to access private fields directly.
Summary:
Classes and objects form the heart of Java programming. They let you create modular, reusable, and organized code. Mastering this concept will open doors to real-world programming and software development.
Core Java for Beginners – Page 10
Constructors in Java
A constructor in Java is a special method used to initialize objects. It has the same name as the class and is automatically called when an object is created. Constructors play a key role in setting up initial values and preparing objects for use.
Types of Constructors:
- Default Constructor – Created by Java if no constructor is written. It takes no parameters.
- No-Argument Constructor – Defined by the programmer with no parameters.
- Parameterized Constructor – Accepts parameters to initialize object fields with specific values.
Example: No-Argument Constructor
class Bike {
Bike() {
System.out.println(“Bike is created”);
}
public static void main(String[] args) {
Bike b = new Bike();
}
}
Example: Parameterized Constructor
class Car {
String color;
Car(String c) {
color = c;
}
void showColor() {
System.out.println(color);
}
public static void main(String[] args) {
Car myCar = new Car(“Red”);
myCar.showColor();
}
}
Constructor Overloading:
You can define multiple constructors with different parameter lists. This allows object initialization in various ways.
Example:
Car()
Car(String color)
Car(String color, int speed)
[Insert Image: Constructor Flow with Class and Object Creation]
Key Notes on Constructors:
- Constructors do not have a return type.
- You cannot use `return` in constructors like in methods.
- They are invoked automatically during object creation.
- You can call one constructor from another using `this()`.
Summary:
Constructors simplify and standardize the initialization of objects. Learning to use constructors effectively will enhance your ability to write organized and powerful classes.
Core Java for Beginners – Page 12
Inheritance in Java
Inheritance is one of the core concepts of Object-Oriented Programming (OOP) in Java. It allows one class (child/subclass) to acquire the fields and methods of another class (parent/superclass). This promotes code reuse and establishes a natural hierarchy between classes.
Benefits of Inheritance:
- Code reusability: Share functionality between classes.
- Improves structure: Creates a logical hierarchy.
- Easier maintenance: Common changes in one place.
- Polymorphism support: Enable overriding and dynamic method dispatch.
Basic Syntax:
class Animal {
void makeSound() {
System.out.println(“Animal sound”);
}
}
class Dog extends Animal {
void makeSound() {
System.out.println(“Bark”);
}
}
Types of Inheritance in Java:
- Single Inheritance – One class inherits another.
- Multilevel Inheritance – Class inherits from a class which inherits another.
- Hierarchical Inheritance – Multiple classes inherit from one superclass.
- Java doesn’t support multiple inheritance with classes (only with interfaces).
Using the super Keyword:
The `super` keyword is used to refer to the immediate parent class. It is commonly used to invoke parent class methods or constructors.
Example:
super.makeSound();
[Insert Image: Inheritance Diagram with Superclass and Subclass Examples]
Summary:
Inheritance helps organize and streamline code by creating relationships between classes. It reduces redundancy, enhances clarity, and is foundational to building flexible and scalable Java applications.
Core Java for Beginners – Page 13
Polymorphism in Java
Polymorphism is another fundamental concept of Object-Oriented Programming in Java. It allows one entity—such as a method or object—to behave differently based on the context. The word ‘polymorphism’ means ‘many forms’.
Why is Polymorphism Useful?
Polymorphism provides flexibility and simplifies code maintenance by allowing a single method name or interface to work with different types of objects. It also improves code reusability and makes applications easier to scale and extend.
Types of Polymorphism in Java:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
1. Method Overloading:
When multiple methods in the same class have the same name but different parameters, it’s called method overloading.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
2. Method Overriding:
When a subclass provides its own implementation of a method that is already defined in its superclass, it is called method overriding.
Example:
class Animal {
void sound() {
System.out.println(“Animal sound”);
}
}
class Dog extends Animal {
void sound() {
System.out.println(“Bark”);
}
}
Dynamic Method Dispatch:
This is the mechanism by which a call to an overridden method is resolved at runtime rather than compile-time. It allows Java to support runtime polymorphism.
[Insert Image: Diagram Showing Compile-time vs Runtime Polymorphism]
Summary:
Polymorphism enables objects to be treated as instances of their parent class, making code more flexible and extensible. It is essential for implementing runtime behavior changes and simplifying system designs.
Core Java for Beginners – Page 14
Abstraction in Java
Abstraction is one of the four key pillars of Object-Oriented Programming. In Java, abstraction is the concept of hiding internal details and showing only the essential features of an object. This helps reduce complexity and focus on what an object does rather than how it does it.
Why Use Abstraction?
- Simplifies complex systems by exposing only relevant parts.
- Increases security by hiding implementation details.
- Promotes cleaner, more readable code.
- Helps in defining a template (or contract) for subclasses.
Abstract Classes:
An abstract class is a class that cannot be instantiated. It may or may not include abstract methods (methods without a body). Subclasses of an abstract class must implement its abstract methods.
Example:
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
System.out.println(“Bark”);
}
}
Interfaces:
An interface in Java is a completely abstract class. It contains only abstract methods (until Java 8) and constants. Classes use `implements` keyword to agree to the interface’s contract.
Example:
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println(“Drawing Circle”);
}
}
Difference Between Abstract Class and Interface:
[Insert Table: Abstract Class vs Interface (supports fields, multiple inheritance, default methods, etc.)]
Best Practices:
- Use abstract classes when there’s a common base behavior and partial implementation.
- Use interfaces for pure abstraction or multiple inheritance-like behavior.
- Don’t overuse abstraction—keep it simple and meaningful.
Summary:
Abstraction allows developers to manage complexity by working at a higher level. It defines a framework while allowing details to be handled by subclasses or implementers.
Core Java for Beginners – Page 15
Encapsulation in Java
Encapsulation is the technique of wrapping data (variables) and code (methods) together into a single unit, typically a class. It is one of the key principles of Object-Oriented Programming that promotes information hiding and security.
Why is Encapsulation Important?
- Keeps internal object details private and secure.
- Prevents unauthorized access and misuse of class data.
- Promotes maintainability and scalability.
- Makes code more modular and easier to test.
Example of Encapsulation:
public class Employee {
private String name;
private int salary;
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public int getSalary() {
return salary;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
}
Steps to Apply Encapsulation:
- Declare the class variables as `private`.
- Provide `public` getter and setter methods to access and update the value of private variables.
- Optionally, validate data within setter methods to enforce rules.
[Insert Image: Encapsulation diagram showing private fields with public methods]
Encapsulation Benefits Recap:
- Improves code maintainability by reducing dependencies.
- Increases control over data.
- Reduces the chance of accidental interference with internal logic.
Summary:
Encapsulation allows you to control access to your class’s internal state. It supports better software design and helps in building reliable and maintainable Java applications.
Core Java for Beginners – Page 16
Packages in Java
A package in Java is a namespace that organizes classes and interfaces. Think of it as a folder in your computer that contains related files. Packages help to avoid class name conflicts and make code easier to locate and maintain.
Why Use Packages?
- Helps group related classes and interfaces.
- Avoids name conflicts.
- Makes locating and using classes easier.
- Controls access with public, private, and protected keywords.
Types of Packages:
- Built-in Packages (from Java API, like java.util, java.io).
- User-defined Packages (custom packages created by developers).
How to Create a Package:
- Declare the package at the top of your Java file:
`package mypackage;`
2. Save your file in a folder named `mypackage`.
3. Compile using: `javac -d . ClassName.java`
4. Use the package by importing it in another file: `import mypackage.ClassName;`
Example:
package mypackage;
public class MyClass {
public void display() {
System.out.println(“Hello from MyClass”);
}
}
Importing Packages:
To use a class from a package, you must import it using:
`import packageName.ClassName;`
or
`import packageName.*;` (to import all classes)
[Insert Image: Java package structure illustration]
Summary:
Packages in Java allow you to better organize your code, promote reuse, and avoid naming collisions. Understanding packages is essential for managing large codebases and using external libraries effectively.
Core Java for Beginners – Page 17
Access Modifiers in Java
Access modifiers in Java define the scope and visibility of classes, variables, methods, and constructors. They are essential for applying encapsulation and ensuring proper control over what can be accessed where.
Types of Access Modifiers:
- public – Accessible from anywhere.
- protected – Accessible within the same package and subclasses.
- default (no modifier) – Accessible only within the same package.
- private – Accessible only within the same class.
[Insert Table: Access Level Comparison for public, protected, default, and private]
Example:
class Person {
public String name;
private int age;
protected String nationality;
String gender; // default access
public void showName() {
System.out.println(“Name: ” + name);
}
}
When to Use Each Modifier:
- Use `public` for utility methods or constants you want accessible everywhere.
- Use `private` for sensitive data and internal helper methods.
- Use `protected` when designing for inheritance.
- Use default access for classes and methods intended for internal package use only.
Best Practices:
- Start with `private` access and increase visibility only when required.
- Limit `public` exposure to reduce risks of misuse.
- Avoid using protected unless designing class hierarchies.
Summary:
Access modifiers give you precise control over your code’s visibility and maintainability. They are key for safe encapsulation and designing clean APIs in Java.
Core Java for Beginners – Page 18
Static Keyword in Java
The `static` keyword in Java is used to indicate that a particular member belongs to the class, rather than to any specific instance of the class. This means you can access static variables and methods without creating an object of the class.
Where Can You Use `static`?
- Static Variables – Shared across all instances.
- Static Methods – Belong to the class and not any object.
- Static Blocks – Used for static initialization of a class.
- Static Classes – Only allowed for inner classes (nested static class).
Example: Static Variable and Method
class Student {
int rollNo;
static String college = “ABC University”;
Student(int r) {
rollNo = r;
}
void display() {
System.out.println(rollNo + ” ” + college);
}
public static void main(String[] args) {
Student s1 = new Student(101);
Student s2 = new Student(102);
s1.display();
s2.display();
}
}
Static Block:
Static blocks run once when the class is loaded into memory. They’re commonly used for static initialization.
Example:
static {
System.out.println(“Static block executed”);
}
Important Rules for Static:
- You cannot access non-static variables or methods from a static method.
- Static methods can only access other static members directly.
- Static blocks run before constructors during class loading.
[Insert Image: Static memory concept diagram]
Summary:
The `static` keyword allows shared functionality across all instances of a class and is key for utility methods, constants, and shared values. It should be used carefully to maintain clarity and avoid misuse of shared state.
Core Java for Beginners – Page 19
Final Keyword in Java
The `final` keyword in Java is a non-access modifier used to restrict the user. It can be applied to variables, methods, and classes. Once something is declared as final, its value or behavior cannot be changed.
Where Can You Use `final`?
- Final Variable – The value cannot be changed once assigned.
- Final Method – Cannot be overridden by subclasses.
- Final Class – Cannot be inherited by any class.
Example – Final Variable:
final int MAX = 100;
// MAX = 200; // This will cause a compile-time error
Example – Final Method:
class Parent {
final void show() {
System.out.println(“This is a final method.”);
}
}
class Child extends Parent {
// void show() { } // Error! Cannot override final method
}
Example – Final Class:
final class Car {
void drive() {
System.out.println(“Driving…”);
}
}
// class SportsCar extends Car { } // Error! Cannot extend final class
[Insert Image: Diagram with final variable, method, and class icons]
Best Practices with final:
- Use final variables for constants (e.g., `final int PI = 3.14`).
- Use final methods in base classes to prevent unexpected behavior from being overridden.
- Use final classes when you want to secure the implementation, such as utility or security classes.
Summary:
The `final` keyword is a powerful tool for creating immutable data, preventing inheritance, and locking down methods. It enhances code stability, clarity, and security when used appropriately.
Core Java for Beginners – Page 20
Constructors in Java
A constructor in Java is a special method that is used to initialize objects. It has the same name as the class and does not have a return type. Constructors are automatically called when an object is created.
Key Characteristics of Constructors:
- Same name as the class.
- No return type (not even void).
- Called automatically when an object is created.
Types of Constructors in Java:
- Default Constructor – No parameters.
- Parameterized Constructor – Accepts parameters.
- Copy Constructor (manual) – Used to copy values from one object to another.
Example – Default Constructor:
class Car {
Car() {
System.out.println(“Car is created”);
}
public static void main(String[] args) {
Car myCar = new Car();
}
}
Example – Parameterized Constructor:
class Car {
String model;
Car(String m) {
model = m;
}
void display() {
System.out.println(“Model: ” + model);
}
public static void main(String[] args) {
Car car1 = new Car(“Honda”);
car1.display();
}
}
Constructor Overloading:
Just like method overloading, Java allows constructor overloading. This means a class can have multiple constructors with different parameters.
Best Practices:
- Always define at least one constructor explicitly if you need specific initialization.
- Use constructor overloading for flexibility.
- Avoid putting heavy logic inside constructors.
[Insert Image: Diagram showing constructor overloading with arrows]
Summary:
Constructors play a critical role in object creation and initialization in Java. Mastering constructors enables you to build flexible and reliable Java applications.
Core Java for Beginners – Page 21
Method Overloading in Java
Method Overloading is a feature in Java that allows a class to have more than one method with the same name, but different parameters (different number or type of parameters). It increases the readability of the program and allows flexibility in calling the method.
Key Characteristics of Method Overloading:
- Method name remains the same.
- Parameters must differ in number or type.
- Return type may vary but is not enough alone to overload.
- Performed within the same class.
Benefits of Method Overloading:
- Improves code clarity and usability.
- Supports flexibility when calling methods with different data.
- Reduces code duplication.
Example of Method Overloading:
class MathOps {
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;
}
}
Real-World Analogy:
Think of a ‘print’ function in a printer. You can print a photo, a text file, or a document. The name ‘print’ is the same, but the input format differs. Method overloading works similarly in Java.
[Insert Image: Illustration showing method overloading with arrows pointing to different method definitions]
Summary:
Method Overloading enables a class to perform a similar action in different ways depending on input. It enhances code efficiency, clarity, and logical structure — an essential skill for Java developers.
Core Java for Beginners – Page 22
Method Overriding in Java
Method Overriding in Java is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This enables dynamic method dispatch and runtime polymorphism.
Key Characteristics of Method Overriding:
- Same method name as in the superclass.
- Same parameters and return type.
- Must occur in an inheritance context (i.e., between superclass and subclass).
- The method in the subclass should have the same signature as in the superclass.
Example of Method Overriding:
class Animal {
void sound() {
System.out.println(“Animal makes a sound”);
}
}
class Dog extends Animal {
void sound() {
System.out.println(“Dog barks”);
}
}
public class TestOverride {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Outputs: Dog barks
}
}
Rules to Remember:
- The overriding method cannot have a more restrictive access modifier.
- Private, static, and final methods cannot be overridden.
- Use `@Override` annotation to ensure correctness.
Why Use Method Overriding?
Overriding is useful for achieving runtime polymorphism. It allows a subclass to offer specific behavior while still maintaining the interface defined by the superclass.
[Insert Image: Diagram showing base class and derived class with overridden methods]
Summary:
Method Overriding is key to achieving polymorphism in Java. It allows for dynamic execution of methods based on the actual object, enabling flexible and scalable code.
Core Java for Beginners – Page 23
Java Arrays
An array in Java is a container object that holds a fixed number of elements of a single type. It is used to store multiple values in a single variable, instead of declaring separate variables for each value.
Key Characteristics of Arrays:
- Arrays are indexed starting from 0.
- All elements in the array must be of the same type.
- Size of the array is fixed once declared.
- Efficient for accessing elements using an index.
Types of Arrays:
- Single-Dimensional Array
2. Multi-Dimensional Array (e.g., 2D arrays)
Example – Single-Dimensional Array:
class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
Example – Multi-Dimensional Array:
class MultiArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j] + ” “);
}
System.out.println();
}
}
}
[Insert Image: Visual of memory layout of arrays]
Best Practices:
- Always initialize arrays to avoid null reference errors.
- Use `array.length` to loop safely.
- Consider using ArrayList for dynamic sizing if flexibility is needed.
Summary:
Arrays are a powerful structure for managing multiple values of the same type. They allow for efficient indexing and processing but are limited by fixed size. Use arrays when working with known quantities of items.
Core Java for Beginners – Page 24
Java Strings
In Java, Strings are objects that represent sequences of characters. They are widely used for storing and manipulating textual data. Java provides the `String` class, which is immutable — once a string object is created, its value cannot be changed.
Key Characteristics of Strings:
- Strings are objects of the `String` class.
- Strings are immutable — modifications create new objects.
- Can be created using string literals or the `new` keyword.
- Stored in a special memory area called the ‘String pool’.
Creating Strings in Java:
String s1 = “Hello”; // Using string literal
String s2 = new String(“World”); // Using new keyword
Commonly Used String Methods:
- length() – Returns the length of the string.
- charAt(int index) – Returns the character at the specified index.
- substring(int beginIndex, int endIndex) – Returns a new string that is a substring.
- toLowerCase() / toUpperCase() – Converts string to lowercase or uppercase.
- equals(String another) – Compares strings for equality.
- contains(CharSequence seq) – Checks if the sequence is present in the string.
- replace(char old, char new) – Replaces characters in the string.
Example:
public class StringDemo {
public static void main(String[] args) {
String name = “Java”;
System.out.println(name.length());
System.out.println(name.toUpperCase());
System.out.println(name.substring(1,3));
}
}
[Insert Image: Diagram of String pool memory and immutability concept]
Best Practices:
- Use string literals to take advantage of the string pool.
- Avoid using `new String()` unless necessary.
- Use `StringBuilder` or `StringBuffer` when performing many string modifications (e.g., in loops).
Summary:
Strings are fundamental in Java. Understanding how to use and optimize them helps write more efficient and effective programs. Their immutability makes them thread-safe and secure for common operations.
Core Java for Beginners – Page 25
StringBuffer and StringBuilder in Java
While the `String` class in Java is immutable, Java provides two mutable alternatives for string manipulation: `StringBuffer` and `StringBuilder`. These classes allow us to modify the contents of strings without creating new objects.
Key Characteristics:
- Both `StringBuffer` and `StringBuilder` are mutable, meaning their content can be modified.
- Both support similar methods for appending, inserting, deleting, and replacing text.
- `StringBuffer` is synchronized and thread-safe, whereas `StringBuilder` is not synchronized but faster.
Example – Using StringBuffer:
public class BufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(“Hello”);
sb.append(” Java”);
System.out.println(sb); // Output: Hello Java
}
}
Example – Using StringBuilder:
public class BuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(“Code”);
sb.append(” Faster”);
System.out.println(sb); // Output: Code Faster
}
}
Differences at a Glance:
– `String`: Immutable, less memory-efficient for modifications.
– `StringBuffer`: Mutable, thread-safe, slightly slower.
– `StringBuilder`: Mutable, not thread-safe, faster performance.
When to Use:
- Use `String` when immutability is required.
• Use `StringBuffer` for thread-safe operations.
• Use `StringBuilder` for faster performance in single-threaded applications.
[Insert Image: Comparison chart of String, StringBuffer, and StringBuilder]
Summary:
`StringBuffer` and `StringBuilder` provide flexibility in modifying string content, reducing memory overhead. Choose the right class based on whether thread safety or speed is your priority.
Core Java for Beginners – Page 26
Java Wrapper Classes
Wrapper classes in Java allow primitive data types to be treated as objects. Each primitive type (int, char, float, etc.) has a corresponding wrapper class (Integer, Character, Float, etc.). Wrapper classes are part of the java.lang package and provide methods to work with primitive values as objects.
Primitive Types and Their Wrapper Classes:
- byte → Byte
- short → Short
- int → Integer
- long → Long
- float → Float
- double → Double
- char → Character
- boolean → Boolean
Why Use Wrapper Classes?
- To use primitives in collections like ArrayList, HashMap, etc. (collections work with objects, not primitives).
- To convert between strings and primitive types using parsing methods.
- To use built-in methods provided by wrapper classes.
Example – Integer Wrapper:
public class WrapperExample {
public static void main(String[] args) {
int num = 100;
Integer obj = Integer.valueOf(num); // Boxing
int value = obj.intValue(); // Unboxing
System.out.println(“Value: ” + value);
}
}
Auto-boxing and Auto-unboxing:
Java automatically converts between primitives and wrapper classes:
Integer x = 5; // auto-boxing
int y = x; // auto-unboxing
Best Practices:
- Avoid unnecessary boxing/unboxing in performance-sensitive code.
- Prefer primitive types unless objects are required (e.g., for collections).
[Insert Image: Diagram showing primitive to wrapper mapping]
Summary:
Wrapper classes bridge the gap between primitive types and object-oriented programming in Java. Understanding them is essential for working with collections, generics, and data conversions.
Core Java for Beginners – Page 27
Java Type Casting
Type casting in Java refers to converting a variable from one data type to another. There are two main types: Widening (automatic) and Narrowing (manual) casting.
1. Widening Casting (Implicit):
Widening casting happens automatically when converting a smaller type to a larger type:
byte → short → int → long → float → double
Example:
int a = 10;
double b = a; // automatically converts int to double
System.out.println(b); // Output: 10.0
2. Narrowing Casting (Explicit):
Narrowing casting must be manually done by placing the type in parentheses:
double → float → long → int → short → byte
Example:
double x = 9.78;
int y = (int) x; // manually converts double to int
System.out.println(y); // Output: 9
Important Notes:
- Widening is safe and does not lead to data loss.
- Narrowing may result in data loss or unexpected behavior.
- Always use narrowing when you’re certain the value fits the target type.
Use Case – Type Casting in Math:
When performing operations with mixed data types, Java automatically uses widening. To control precision or format results, use narrowing where needed.
[Insert Image: Type casting flow chart from byte to double and back]
Summary:
Java’s type casting allows conversion between data types for flexibility and compatibility. Understand when to use widening or narrowing to ensure safe and correct value transformation.
Core Java for Beginners – Page 28
Java Operators
Operators in Java are special symbols that perform specific operations on one, two, or three operands, and then return a result. Operators form the foundation of most expressions in Java.
Types of Operators in Java:
- Arithmetic Operators
- Relational (Comparison) Operators
- Logical Operators
- Assignment Operators
- Unary Operators
- Bitwise Operators
- Ternary Operator
1. Arithmetic Operators:
Used for basic arithmetic operations: +, -, *, /, %
Example:
int a = 10;
int b = 5;
System.out.println(a + b); // Output: 15
2. Relational Operators:
Used to compare two values: ==, !=, >, <, >=, <=
3. Logical Operators:
Used to combine multiple conditions: &&, ||, !
4. Assignment Operators:
Used to assign values: =, +=, -=, *=, /=, %=
5. Unary Operators:
Used with only one operand: +, -, ++, –, !
6. Bitwise Operators:
Operate on bits and perform bit-by-bit operations: &, |, ^, ~, <<, >>, >>>
7. Ternary Operator:
Short form of if-else: condition ? value_if_true : value_if_false
Example:
int x = 10;
int y = 20;
int max = (x > y) ? x : y;
System.out.println(“Maximum: ” + max);
[Insert Image: Chart comparing all operator types with symbols and examples]
Summary:
Java operators allow manipulation of data and logic within expressions. Mastering operator types and their precedence is essential for writing efficient Java code.
Core Java for Beginners – Page 29
Java Control Statements
Control statements in Java allow the flow of execution to be directed according to logic. They help in making decisions, looping over data, and skipping code blocks when necessary.
Types of Control Statements:
- Decision-making statements
- Looping statements
- Branching statements
1. Decision-Making Statements:
Used to take decisions based on conditions.
- if statement
- if-else statement
- if-else-if ladder
- switch statement
2. Looping Statements:
Used to execute a block of code multiple times.
- for loop
- while loop
- do-while loop
- for-each loop
3. Branching Statements:
Used to alter the flow inside loops or methods.
- break
- continue
- return
Example – if-else:
int age = 18;
if(age >= 18) {
System.out.println(“You are eligible to vote.”);
} else {
System.out.println(“You are not eligible to vote.”);
}
Example – for loop:
for(int i = 1; i <= 5; i++) {
System.out.println(“Hello ” + i);
}
[Insert Image: Flowchart showing control statements in Java]
Summary:
Java control statements shape the logic and behavior of a program. They allow us to build intelligent and efficient flow within our applications by guiding decisions, iterations, and exits.
Core Java for Beginners – Page 30
Java Looping Constructs
Loops are fundamental in programming. In Java, they help us execute a block of code repeatedly based on a condition. Mastering loops is essential for tasks like iterating through arrays, performing calculations, or running logic until a certain state is reached.
Types of Loops in Java:
- for loop – Best used when the number of iterations is known.
- while loop – Used when condition needs to be checked before each iteration.
- do-while loop – Runs the code at least once before checking the condition.
- for-each loop – Simplified version for iterating over arrays and collections.
Example – for loop:
for(int i = 1; i <= 5; i++) {
System.out.println(“Count: ” + i);
}
Example – while loop:
int i = 1;
while(i <= 5) {
System.out.println(“Value: ” + i);
i++;
}
Example – do-while loop:
int i = 1;
do {
System.out.println(“Number: ” + i);
i++;
} while(i <= 5);
Example – for-each loop:
int[] numbers = {10, 20, 30, 40};
for(int num : numbers) {
System.out.println(num);
}
When to Use:
- Use `for` when working with counters.
• Use `while` when the loop condition depends on dynamic changes.
• Use `do-while` when you need the loop to run at least once.
• Use `for-each` when iterating through arrays or collections.
[Insert Image: Comparison chart of Java loop types]
Summary:
Loops enable repetitive execution, a powerful tool in Java. Understanding each type of loop helps in writing cleaner, efficient, and well-controlled code structures.