Java Programming Unit-1 Mega Notes
Java Programming Unit-1 Mega Notes
📌 Syllabus 📚
1.1 ✨ Java Features and the Java Programming Environment
Unit I: Basic Syntactical Constructs in Java
📜
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)
✨ 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.
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.
Key Points:
Working Together:
Install JDK
import java.util.*;
class HelloDiplomatechians {
public static void main(String[] args) {
System.out.println("Hello,
Diplomatechians!");
System.out.println("Welcome to DiplomaTech
Academy!");
}
📝 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:
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 🚗");
}
}
Key Points:
Syntax:
ClassName objectName = new ClassName();
🧑💻 Example:
Car myCar = new Car(); // Creating an object of the
'Car' class
📝 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
🧩
Typecasting, Operators & Expressions, Decision Making, and Looping
Statements
1. Primitive Data Types (basic data types that are built into Java):
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:
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.
Logical Operators 🔐
Used for logical operations.
Assignment Operators 📝
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();
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;
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");
}
}
}
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;
for Loop 🔄
Used when you know the number of iterations in advance.
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);
// 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
}
}
}
The continue statement is used to skip the current iteration of a loop and
continue with the next iteration.
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:
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};
🧑💻 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:
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"
}
}
Key Points:
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");
Key Points:
Syntax:
v.add("Java");
v.add("C++");
v.add("Python");
Example:
import java.util.Vector;
Key Points:
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);
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:
Types of Constructors:
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;
}
Constructor Overloading happens when a class has more than one constructor,
with each having a different number or type of parameters.
Example:
public class MathOperations {
public void multiply() {
int result = 2 * 3;
System.out.println("Multiplication result: " +
result);
add(); // Calling another method inside this
method
}
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:
Output:
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: