0% found this document useful (0 votes)
6 views

Java Programming Unit-1 Mega Notes

The document provides comprehensive notes on Java programming, covering key concepts such as Java features, class definitions, object creation, and data types. It outlines the Java programming environment, including the Java Development Kit (JDK) and Java Virtual Machine (JVM), along with examples of simple Java programs. Additionally, it explains fundamental programming constructs like tokens, operators, typecasting, and variable scope.
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)
6 views

Java Programming Unit-1 Mega Notes

The document provides comprehensive notes on Java programming, covering key concepts such as Java features, class definitions, object creation, and data types. It outlines the Java programming environment, including the Java Development Kit (JDK) and Java Virtual Machine (JVM), along with examples of simple Java programs. Additionally, it explains fundamental programming constructs like tokens, operators, typecasting, and variable scope.
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
You are on page 1/ 42

🌟 DiplomaTech Academy 🌟

📘 Java Programming Notes (314317)


UNIT 1- NOTES

📌 Syllabus 📚​
1.1 ✨ Java Features and the Java Programming Environment​
Unit I: Basic Syntactical Constructs in Java​

1.2 🛠️ Defining a Class, Creating Objects, Accessing Class Members​


1.3 🧩 Java Tokens, Data Types, Symbolic Constants, Scope of Variables,
Typecasting, Operators & Expressions, Decision Making, and Looping

📜
Statements​

🔄
1.4 Arrays, Strings, StringBuffer Classes, Vectors, Wrapper Classes​
1.5 Constructors and Methods, Types of Constructors,
Method/Constructor Overloading, Nesting of Methods, Command-Line
Arguments, Garbage Collection, Visibility Control (public, private, protected,
default, private protected)

📞 Made by Mohade Sir​


📌 Contact: 8261884261
🌟 Introduction to Java
●​ 👨‍💻 Creator: James Gosling of Sun Microsystems, 1991.
●​ 🌳 Original Name: OAK (named after an oak tree). Later renamed Java.
●​ 🏢 Ownership: Acquired by Oracle Corporation on 27th Jan 2010.

✨ Features of Java
1. Data Abstraction and Encapsulation 🔒💡
●​ Encapsulation binds data (variables) and methods (functions) together within
a class.
●​ It ensures data hiding, restricting direct access to class members and
exposing them via methods.
●​ Abstraction focuses on showing only essential features while hiding the
implementation details.
●​ These concepts promote modularity and make the code more secure and
maintainable.

2. Inheritance 🌳🔁
●​ Inheritance allows a class (child) to reuse the properties and methods of
another class (parent).
●​ It promotes hierarchical organization, enabling efficient code structuring.
●​ Reduces redundancy by avoiding code duplication.
●​ Enables method overriding, where the child class can provide a specific
implementation of a parent class method.

3. Polymorphism 🔄🔧
●​ Polymorphism allows a single interface to represent multiple
implementations.
●​ Compile-time polymorphism is achieved through method overloading.
●​ Runtime polymorphism is achieved using method overriding.
●​ It enhances flexibility and enables the dynamic execution of methods based
on the object type.

4. Platform Independence 🌐💻
●​ Java is platform-independent because its bytecode can run on any platform
with a JVM.
●​ The principle "Write Once, Run Anywhere" ensures cross-platform
compatibility.
●​ This independence is achieved through the Java Virtual Machine (JVM)
abstraction.
●​ The same .class file can execute on different operating systems without
modifications.

5. Portability 📱🌍
●​ Bytecode makes Java hardware-independent, allowing programs to run on
various devices.
●​ Portability eliminates the need for recompilation when switching platforms.
●​ Java’s runtime environment ensures programs work seamlessly across
devices.
●​ Consistency in Java's library APIs supports universal development
standards.

6. Robust 💪⚡
●​ Java handles runtime errors efficiently through its powerful
exception-handling mechanism.
●​ Built-in garbage collection manages memory automatically, preventing
memory leaks.
●​ It eliminates the complexity of pointer management, reducing error risks.
●​ Strong type-checking during compilation ensures code reliability.

7. Supports Multithreading 🧵💻
●​ Java enables programs to perform multiple tasks simultaneously within the
same application.
●​ Threads improve CPU utilization by running parallel processes.
●​ The built-in Thread class and Runnable interface simplify multithreading
implementation.
●​ It supports synchronization, ensuring thread safety while accessing shared
resources.

8. Supports Distributed Applications 🌍🔗


●​ Java simplifies the development of networked applications through built-in
APIs.
●​ Technologies like RMI (Remote Method Invocation) facilitate calling
methods on remote objects.
●​ EJB (Enterprise JavaBeans) provides server-side support for distributed
systems.
●​ Java’s socket programming and CORBA (Common Object Request Broker
Architecture) allow seamless communication.

9. Secure 🔐🛡️
●​ Java incorporates bytecode verification, ensuring the integrity of code
execution.
●​ Absence of pointers eliminates direct memory access, reducing
vulnerabilities.
●​ The Java Security API provides encryption, authentication, and secure
communication.
●​ The JVM runs code within a sandbox, preventing malicious activities and
unauthorized access.

10. Architectural Neutral 🖥️🌐


●​ Java's bytecode is independent of processor architecture, making it universal.
●​ The JVM bridges the gap between Java programs and machine-specific
instructions.
●​ This neutrality ensures that programs work seamlessly across diverse
environments.
●​ Java developers focus on writing code, not worrying about hardware
compatibility.

11. Dynamic 🏃‍♂️💫


●​ Java supports dynamic linking, loading classes and libraries during runtime
as needed.
●​ It enables applications to be adaptable in changing environments.
●​ The Reflection API allows runtime inspection and manipulation of classes
and objects.
●​ Dynamically loaded classes provide extensibility, making the system more
modular and efficient.
🛠️ Java Programming Environment
1.​ JDK (Java Development Kit)​

○​ A collection of tools for designing, developing, debugging, and


running Java programs.
2.​ Tools in JDK:​

🖥️ Appletviewer: Runs Java applets without a browser.


⚙️ Javac (Compiler): Compiles Java files.
○​
○​
■​ Example: C:\>javac filename.java
○​ 🏃 Java (Interpreter): Interprets and executes compiled Java files.
■​ Example: C:\>java filename
○​ 🔍 Javap (Disassembler): Converts bytecode into program

○​ 🛠️ Javah: Generates C header files for native methods.


description.

○​ 🌐 Javadoc: Creates HTML documentation from Java source files.


○​ 🐞 Jdb (Debugger): Helps find and fix errors in Java programs.

💻 Java Virtual Machine (JVM) & Bytecode


🌐 Java Virtual Machine (JVM)
●​ JVM is an abstract machine that executes Java bytecode.
●​ Platform-dependent implementations exist for various hardware/software
platforms.

Operations Performed by JVM:

📥 Loads Code – Reads bytecode into memory.


✅ Verifies Code – Ensures integrity and security.
●​

🏃 Executes Code – Runs bytecode instructions.


●​

⚙️ Provides Runtime Environment – Allocates resources for execution.


●​
●​
📜 Bytecode
●​ Bytecode is the instruction set for the JVM.
●​ Generated upon compiling Java code and stored in .class files.

Key Points:

●​ Acts as a machine-independent representation.


●​ Enables platform independence with a JVM.
●​ JVM resources, not the processor, execute bytecode.
●​ Stack-based execution in JVM.

Working Together:

●​ Java source code → Compiled into bytecode.


●​ JVM interprets bytecode → Allocates resources → Executes on any
platform with JVM.

✏️ Simple Java Programming


Steps to Write and Compile a Simple Program

Install JDK

○​ Download and install the Java Development Kit (JDK).

Set the Path​

○​ My Computer → Properties → Environment Variables.


○​ Add a new user variable:
■​ Name: Path
■​ Value: C:\Program Files\Java\jdk1.6.0\bin.
Create and Save the Program​
// Importing Scanner class (for possible future use)

import java.util.*;
class HelloDiplomatechians {
public static void main(String[] args) {
System.out.println("Hello,
Diplomatechians!");
System.out.println("Welcome to DiplomaTech
Academy!");
}

Compile and Execute​

○​ Open Command Prompt:


■​ Compile: javac Simple.java → Creates
Simple.class.
■​ Output - hello diplomatechians , welcome to diplomatech
academy

🔍 Understanding the Program


●​ class: Declares a class in Java.
●​ public: Makes the method accessible to all.
●​ static: Allows calling without object creation.
●​ void: Return type; means no value is returned.
●​ main: Entry point of the program.
●​ String[] args: Handles command-line arguments.
●​ System.out.println(): Prints output to the console.
🔄 Alternate Ways to Write the Main Method
●​ public static void main(String[] args)
●​ public static void main(String []args)
●​ public static void main(String args[])
●​ public static void main(String... args)

🛠️ Defining a Class in Java


A class in Java is a blueprint or template used to create objects. It defines the
properties (also called fields or member variables) and behaviors (also called
methods) that the objects created from this class will have. Think of it as a
recipe—objects are the result of following the recipe.

📝 Detailed Definition:
●​ Class is a user-defined data type that holds both data and methods.
●​ It acts as a template for creating objects, which are instances of the class.
●​ Classes define fields (attributes or properties) and methods (actions or
behaviors).

Key Points:

●​ A class can contain:


○​ Variables: Store data for objects.
○​ Methods: Define behaviors or functions that can be performed on the
data.
○​ Constructors: Special methods used to initialize objects.

Syntax:​

class ClassName {
// Variables (properties)a
// Methods (functions)
}

🧑‍💻 Example:

class Car {
// Properties (Variables)
String color; // Color of the car
String model; // Model of the car

// Behavior (Method)
void drive() {
System.out.println(model + " is driving 🚗");
}
}

🧰 Creating Objects in Java


An object is an instance of a class. Once a class is defined, we can create as many
objects (instances) as we want using the class blueprint.
📝 Detailed Definition:
●​ Object is an instance of a class. It represents a specific example of the class
with actual data.
●​ new is used to allocate memory for an object.
●​ An object can access the class members (variables and methods) using the
dot (.) operator.

Key Points:

●​ Objects are created using the new keyword.


●​ The constructor is called when an object is created.

Syntax:​

ClassName objectName = new ClassName();

🧑‍💻 Example:
Car myCar = new Car(); // Creating an object of the
'Car' class

●​ myCar is an object of the Car class. It represents a specific car.

🔑 Accessing Class Members (Variables and Methods)


Once an object is created, we can access its fields (variables) and methods
(behaviors).

📝 Detailed Definition:
●​ Fields: These represent the properties of an object.
●​ Methods: These define the behaviors that objects can perform.
●​ You access an object’s members using the dot (.) operator.

Key Points:

Accessing Fields:​

objectName.fieldName;

●​

Accessing Methods:​

objectName.methodName();

🧑‍💻 Example:
Car myCar = new Car(); // Creating object
myCar.color = "Red"; // Accessing and setting
'color' field
myCar.model = "Tesla"; // Accessing and setting
'model' field
myCar.drive(); // Calling the 'drive' method

💡 Summary of Class Members:


●​ Fields: Variables that store object data (e.g., color, model).
●​ Methods: Functions that perform actions (e.g., drive()).

// Defining the class


class Person {
// Class members (variables)
String name; // Name of the person
int age; // Age of the person
// Method to print information
void introduce() {
System.out.println("Hello, my name is " + name + "
and I am " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of the Person class
Person person1 = new Person(); // Creating an
object called 'person1'

// Assigning values to the object's variables


person1.name = "John"; // Setting the name for
person1
person1.age = 25; // Setting the age for
person1 // Accessing the object's method
person1.introduce(); // Calling the method to
print info
}
}
1.3 Java Tokens, Data Types, Symbolic Constants, Scope of Variables,

🧩
Typecasting, Operators & Expressions, Decision Making, and Looping
Statements

1.1 Tokens in Java 🌟


Java programs are made up of tokens. A token is the smallest unit in a program,
which the Java compiler can recognize. Tokens can be:

●​ Keywords: class, public, static, etc.


●​ Identifiers: Names for variables, functions, etc.
●​ Literals: Constant values, like 10, 'a', "Hello".
●​ Operators: +, -, *, etc.
●​ Separators: ;, {}, [], (), etc.

1.2 Data Types 📊


Java is a strongly typed language, meaning that each variable must be declared
with a data type. Data types in Java are divided into two categories:

1.​ Primitive Data Types (basic data types that are built into Java):​

○​ int: Integer numbers, e.g., 10, 100.


○​ float: Decimal numbers (single precision), e.g., 3.14.
○​ char: Single characters, e.g., 'a'.
○​ boolean: true or false.
○​ double: Decimal numbers (double precision), e.g., 3.14159.
○​ long: Larger integers, e.g., 1000000L.
○​ short: Smaller integers, e.g., -32768.
○​ byte: Very small integers, e.g., -128 to 127.
2.​ Reference Data Types (objects and arrays):​

○​ String: A sequence of characters, e.g., "Hello".


○​ Arrays: A collection of elements of the same type, e.g., int[] arr
= {1, 2, 3};.
2. Symbolic Constants 💡
A symbolic constant is a variable whose value cannot change after it is initialized.
Constants are declared using the final keyword in Java.

final int MAX_VALUE = 100; // MAX_VALUE cannot be changed later

3. Scope of Variables 🌍
The scope of a variable determines where it can be accessed. In Java, there are two
main types of variables based on scope:

●​ Local Variables: Variables declared inside a method or a block, accessible


only within that method/block.
●​ Global Variables: Also called instance variables or class variables, they
are declared outside methods and can be accessed by all methods in a class.

Example: Local and Global Variables


public class Example {
int globalVar = 50; // Global variable (accessible
anywhere in the class)
public void myMethod() {
int localVar = 10; // Local variable (accessible only
in myMethod)
System.out.println("Global: " + globalVar); // Can
access global variable
System.out.println("Local: " + localVar); // Access
local variable within the method
}
}
4. Typecasting 🔄
Typecasting is used to convert one data type into another. Java supports two types
of typecasting:

1.​ Implicit Typecasting (Widening): Automatically converts smaller types


into larger types.​

○​ Example: int to float or float to double.


2.​ Explicit Typecasting (Narrowing): Manually converting larger types to
smaller types, often with potential data loss.​

○​ Example: double to int.

int num = 10;


double numDouble = num; // Implicit casting

double pi = 3.14;
int piInt = (int) pi; // Explicit casting

5. Operators 🔧
Operators are symbols that perform operations on variables and values. Here's the
breakdown of operators in Java:
Arithmetic Operators ➕➖✖️➗
Used for mathematical calculations.

Relational Operators 🧑‍🤝‍🧑


Used for comparing two values.

Logical Operators 🔐
Used for logical operations.

Assignment Operators 📝

6. Decision Making (Conditional Statements) 🧐


Decision-making allows us to execute code based on conditions.

if Statement 🟢
Executes a block of code if a condition is true.

if (condition) {
// code to be executed if condition is true
}
import java.util.Scanner;
public class IfExample {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner sc = new Scanner(System.in);
// Ask user for input
System.out.print("Enter a number: ");
int number = sc.nextInt();

// If statement to check if the number is


positive
if (number > 0) {
System.out.println("The number is
positive.");
}
}
}
if-else Statement 🔴
Executes one block of code if the condition is true, otherwise another block if false.

if (condition1 && condition2) {


// Executes if both conditions are true
} else {
// Executes if either condition is false
}

public class IfElseExample {


public static void main(String[] args) {
int number = 15; // Declare and initialize a
variable

// Check if the number is between 10 and 20


using AND (&&)
if (number > 10 && number < 20) {
System.out.println("The number is between
10 and 20.");
} else {
System.out.println("The number is outside
the range of 10 to 20.");
}
}
}
switch Statement 🔄
Executes one out of many blocks of code based on a variable's value.

switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
// other cases
default:
// code block if no match is found
}
code:
import java.util.Scanner;

public class SwitchExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a number (1-3): ");


int number = sc.nextInt();

switch (number) {
case 1:
System.out.println("You chose One");
break;
case 2:
System.out.println("You chose Two");
break;
case 3:
System.out.println("You chose Three");
break;
default:
System.out.println("Invalid choice");
}
}
}

Nested if-else Statement in Java:

A nested if-else statement is an if statement inside another if statement. It


allows you to check multiple conditions.

if (condition1) {
if (condition2) {
// Block of code if both condition1 and condition2
are true
} else {
// Block of code if condition1 is true but
condition2 is false
}
} else {
// Block of code if condition1 is false
}
import java.util.Scanner;

public class NestedIfExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Taking input from the user


System.out.print("Enter your age: ");
int age = sc.nextInt();

// Nested if-else logic


if (age >= 18) {
if (age >= 65) {
System.out.println("You are a senior
citizen.");
} else {
System.out.println("You are an adult.");
}
} else {
System.out.println("You are a minor.");
}

sc.close(); // Closing scanner


}
}
7. Looping Statements 🔁
Loops allow us to repeat a block of code multiple times.

for Loop 🔄
Used when you know the number of iterations in advance.

for (initialization; condition; update) {


// code to be executed
}

public class ForLoopExample {


public static void main(String[] args) {
// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}

while Loop 🔄
Used when the number of iterations is not known, but the loop should continue
until a condition becomes false.

while (condition) {
// code to be executed
}

do-while Loop 🔁
Executes the code block at least once before checking the condition.

do {
// code to be executed
} while (condition);

public class DoWhileLoopExample {


public static void main(String[] args) {
int i = 1;

// Print numbers 1 to 5
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
break Statement in Java:

The break statement is used to exit from a loop or switch statement before
it completes normally.
public class BreakExample {
public static void main(String[] args) {
// Example of break in a for loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i); // Prints numbers 1 to 4
}
}
}

continue Statement in Java:

The continue statement is used to skip the current iteration of a loop and
continue with the next iteration.

public class ContinueExample {


public static void main(String[] args) {
// Example of continue in a for loop
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skips the current iteration when i equals
5
}
System.out.println(i); // Prints numbers 1 to 10
except 5
}
}
}

📜1.4 Java Arrays, Strings, StringBuffer Classes, Vectors, and Wrapper


Classes 🌟

This section explains essential topics in Java programming that will help you
handle data more efficiently. Each of these topics is important for developing
practical and efficient Java applications. Let’s dive into the basics with examples
and easy-to-understand explanations!

🧑‍💻 1. Arrays 🌐
Definition: An array is a collection of variables of the same type, stored in
contiguous memory locations. In Java, arrays are objects, and their size is fixed
once created.

Key Points:

●​ Declaration: Arrays can be declared and initialized in various ways.


●​ Zero-based index: Arrays use an index starting from 0.
●​ Fixed size: Once an array is created, its size cannot be changed.

Syntax:
// Declaring and initializing an array
int[] numbers = {10, 20, 30, 40, 50};
// Accessing array elements
System.out.println(numbers[0]); // Outputs 10

Example:
public class ArrayExample {
public static void main(String[] args) {
// Creating an integer array
int[] arr = {1, 2, 3, 4, 5};

// Printing all elements of the array


for(int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " +
arr[i]);
}
}
}

🧑‍💻 2. Strings 📝
Definition: A String is a sequence of characters, and in Java, Strings are objects.
Java provides the String class in the java.lang package to handle text-based
data.

Key Points:

●​ Immutable: Once a String object is created, it cannot be modified.


●​ String concatenation: We can combine strings using the + operator.
●​ String Methods: Java provides many useful methods like .length(),
.charAt(), .substring(), and .toUpperCase().

Syntax:
String greeting = "Hello, World!";
System.out.println(greeting.length()); // Outputs: 13

Example:
public class StringExample {
public static void main(String[] args) {
// Creating a string
String str = "DiplomaTech";
// Using string methods
System.out.println("Length of the string: " +
str.length()); // Outputs 12
System.out.println("Substring from index 2: "
+ str.substring(2)); // Outputs "plomaTech"
System.out.println("Uppercase string: " +
str.toUpperCase()); // Outputs "DIPLOMATECH"
}
}

🧑‍💻 3. StringBuffer Class 🧶


Definition: StringBuffer is a mutable sequence of characters. It can be
modified after it is created, unlike String which is immutable.

Key Points:

●​ Faster than String for frequent modifications.


●​ Provides methods like .append(), .insert(), .delete(),
.reverse(), etc.
●​ It’s mainly used when strings are being modified frequently in the program.

Syntax:
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb); // Outputs: Java Programming

Example:
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Tech");

// Appending new text


sb.append(" Academy");
System.out.println(sb); // Outputs: Tech
Academy

// Reversing the string


sb.reverse();
System.out.println(sb); // Outputs: ymedacA
hcet
}
}
🧑‍💻 4. Vectors 📚
Definition: A Vector is a growable array in Java that implements the List
interface. Unlike arrays, Vectors can grow or shrink in size as elements are added
or removed.

Key Points:

●​ Resizable: Vectors automatically resize when they exceed the current


capacity.
●​ Thread-safe: Vectors are synchronized, meaning they can be safely used in
multithreaded environments.
●​ Similar to ArrayList but slower because of synchronization overhead.

Syntax:

Vector<String> v = new Vector<>();

v.add("Java");

v.add("C++");

v.add("Python");

System.out.println(v); // Outputs: [Java, C++, Python]

Example:
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
// Creating a Vector object
Vector<String> vector = new Vector<>();
// Adding elements to the vector
vector.add("Java");
vector.add("Python");
vector.add("C++");

// Printing the Vector


System.out.println("Vector contents: " +
vector);
}
}

🧑‍💻 5. Wrapper Classes 🧳


Definition: Wrapper classes in Java are used to convert primitive data types into
objects. Every primitive type has a corresponding wrapper class.

Key Points:

●​ Wrapper Classes: For example, int → Integer, char →


Character, double → Double, etc.
●​ Useful for working with collections (like ArrayList), as they store only
objects and not primitives.
●​ Provide useful methods like parseInt(), toString(), etc.

Wrapper Classes for Primitives:


Primitive Type Wrapper Class
int Integer

char Character

boolean Boolean

double Double

float Float

long Long

short Short

byte Byte

Example:
public class WrapperClassExample {
public static void main(String[] args) {
// Converting primitive to Wrapper class object
int num = 10;
Integer wrapperNum = Integer.valueOf(num);

// Converting Wrapper class object to primitive


int primitiveNum = wrapperNum.intValue();

System.out.println("Wrapper object: " +


wrapperNum);
System.out.println("Primitive value: " +
primitiveNum);

// Using Wrapper class methods


String numberString = "100";
int parsedInt =
Integer.parseInt(numberString);
System.out.println("Parsed integer: " +
parsedInt);
}
}

🚀 Summary of Key Concepts:


1.​ Arrays: Fixed-size collections for storing multiple values of the same type.
2.​ Strings: Immutable objects used for storing text. String methods offer a
variety of manipulations.
3.​ StringBuffer: Mutable string objects for efficient string manipulation.
4.​ Vectors: Dynamic arrays that can grow or shrink, useful in multithreaded
environments.
5.​ Wrapper Classes: Convert primitive types into objects for use in
collections.

1.5Constructors and Methods, Types of Constructors, Method/Constructor


Overloading, Nesting of Methods, Command-Line Arguments, Garbage
Collection, Visibility Control (public, private, protected, default, private
protected)

These concepts are essential for mastering Java programming. Let’s break them
down into simple and easy-to-understand explanations with examples!
🧑‍💻 1. Constructors 🛠️
Definition: A constructor is a special method in Java used to initialize objects. It
is called when an object of a class is created. Constructors do not have a return
type, and their name is the same as the class name.

Key Points:

●​ Default Constructor: A constructor provided by Java if no constructor is


defined in the class. It initializes object members with default values (0, null,
etc.).
●​ Parameterized Constructor: A constructor that allows us to pass
parameters to initialize object members with specific values.

Types of Constructors:

1.​ Default Constructor: No parameters.


2.​ Parameterized Constructor: With parameters to initialize the object with
specific values.

Example:
public class Person {
String name;
int age;

// Default Constructor
public Person() {
name = "Unknown";
age = 0;
}

// Parameterized Constructor
public Person(String name, int age) {
name = name;
age = age;
}

public void displayInfo() {


System.out.println("Name: " + name + ", Age: "
+ age);
}

public static void main(String[] args) {


Person person1 = new Person(); // Default
constructor
person1.displayInfo(); // Outputs: Name:
Unknown, Age: 0

Person person2 = new Person("John", 25); //


Parameterized constructor
person2.displayInfo(); // Outputs: Name: John,
Age: 25
}
}

🧑‍💻 2. Method and Constructor Overloading ⚙️


Method Overloading occurs when multiple methods have the same name but
different parameters (either different number or types of parameters).

Constructor Overloading happens when a class has more than one constructor,
with each having a different number or type of parameters.

Example of Method Overloading:


public class Calculator {

// Adding two integers


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

// Adding three integers


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

public static void main(String[] args) {


Calculator calc = new Calculator();
System.out.println("Sum of two numbers: " +
calc.add(5, 10)); // Outputs: 15
System.out.println("Sum of three numbers: " +
calc.add(5, 10, 15)); // Outputs: 30
}
}

Example of Constructor Overloading:


public class Car {
String model;
int year;

// Constructor with no parameters


public Car() {
model = "Unknown";
year = 0;
}

// Constructor with parameters


public Car(String model, int year) {
this.model = model;
this.year = year;
}

public void displayDetails() {


System.out.println("Model: " + model + ",
Year: " + year);
}

public static void main(String[] args) {


Car car1 = new Car(); // Using default
constructor
car1.displayDetails(); // Outputs: Model:
Unknown, Year: 0

Car car2 = new Car("Tesla", 2022); // Using


parameterized constructor
car2.displayDetails(); // Outputs: Model:
Tesla, Year: 2022
}
}
🧑‍💻 3. Nesting of Methods 🔄
Definition: Nesting of methods refers to calling one method inside another
method. This helps in organizing code and improving readability.

Example:
public class MathOperations {
public void multiply() {
int result = 2 * 3;
System.out.println("Multiplication result: " +
result);
add(); // Calling another method inside this
method
}

public void add() {


int sum = 5 + 7;
System.out.println("Addition result: " + sum);
}

public static void main(String[] args) {


MathOperations math = new MathOperations();
math.multiply(); // This will also call the
add method
}
}

🧑‍💻 4. Command-Line Arguments 📡


Definition: Command-line arguments are parameters passed to the Java
program at the time of execution. These arguments are stored in an array of
String type.

Example:
public class CommandLineExample {
public static void main(String[] args) {
// Accessing command-line arguments
System.out.println("First argument: " +
args[0]);
System.out.println("Second argument: " +
args[1]);
}
}

Command to run:

java CommandLineExample Hello World

Output:

First argument: Hello


Second argument: World

🧑‍💻 5. Garbage Collection 🧹


Definition: Garbage Collection in Java is the process of automatically freeing up
memory by removing objects that are no longer in use. This is handled by the Java
Garbage Collector.

Key Points:
●​ Garbage collection runs in the background and is triggered when the JVM
detects that memory is low.
●​ It helps in preventing memory leaks by removing objects that are no longer
referenced.

Example:

You don’t need to explicitly call garbage collection. The JVM does it
automatically. However, you can suggest garbage collection using:

System.gc(); // Suggests JVM to run Garbage Collector

🧑‍💻 6. Visibility Control (Access Modifiers) 🔐


Definition: Visibility control in Java determines the access level of class members
(variables, methods, constructors). The four access modifiers are:

1.​ public: The member is accessible from anywhere.


2.​ private: The member is accessible only within the same class.
3.​ protected: The member is accessible within the same package and by
subclasses.
4.​ default: No access modifier is used. It’s accessible within the same package
only.

Visibility Modifiers Table:Example:


public class VisibilityExample {
// Public member
public String publicVar = "I am public!";
// Private member
private String privateVar = "I am private!";
// Protected member
protected String protectedVar = "I am protected!";
// Default member
String defaultVar = "I have default access!";

public void display() {


System.out.println(publicVar);
System.out.println(privateVar);
System.out.println(protectedVar);
System.out.println(defaultVar);
}
public static void main(String[] args) {
VisibilityExample obj = new
VisibilityExample();
obj.display(); // Outputs all variables
}
}

🚀 Summary of Key Concepts:


1.​ Constructors: Initialize objects. Can be default or parameterized.
2.​ Method/Constructor Overloading: Multiple methods/constructors with the
same name but different parameters.
3.​ Nesting of Methods: Calling one method inside another to organize code.
4.​ Command-Line Arguments: Passing parameters to the program at runtime.
5.​ Garbage Collection: Automatic memory management to clear unused
objects.
6.​ Visibility Control: Access modifiers (public, private, protected,
default) control access to class members.

You might also like