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

MST 1

Uploaded by

gurly101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

MST 1

Uploaded by

gurly101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

How Java Works

Java is a high-level, object-oriented programming language designed to be


platform-independent. It follows the principle of "Write Once, Run Anywhere" (WORA), meaning
that code written in Java can run on any device that has a Java Virtual Machine (JVM). Here s
how Java works in a nutshell:

1. Compilation : Java code is first written in plain text files with the extension .java . These
files are then compiled by the Java compiler ( javac ) into bytecode, which is stored in .class
files. Bytecode is an intermediate, platform-independent code that can be executed on any
system with a JVM.

2. Execution : The compiled bytecode is executed by the JVM. The JVM interprets the
bytecode or compiles it into native machine code using Just-In-Time (JIT) compilation,
depending on the needs of the program. This execution process makes Java
platform-independent because the JVM abstracts the underlying platform.

3. JVM : The JVM is responsible for managing memory, performing garbage collection
(automatically freeing up memory used by objects that are no longer in use), and ensuring
security. It acts as a bridge between the bytecode and the underlying hardware.

4. Standard Library : Java comes with a rich set of libraries and APIs (Application
Programming Interfaces) that provide pre-built functions to handle common tasks such as data
structures, networking, file I/O, graphical user interfaces, and more.

Sample Java Code

Here s a simple Java program that demonstrates the basic structure and execution of Java
code:

java
// A simple Java program to demonstrate how Java works

// Define a class named HelloWorld


public class HelloWorld {

// Main method: The entry point of any Java program


public static void main(String[] args) {
// Print a message to the console
System.out.println("Hello, World!");

// Demonstrate a simple calculation


int number1 = 10;
int number2 = 20;
int sum = number1 + number2;

// Print the result of the calculation


System.out.println("Sum of " + number1 + " and " + number2 + " is: " + sum);
}
}

Explanation of the Code

- Class Declaration ( public class HelloWorld ) : Everything in Java is encapsulated in


classes. This program defines a class named HelloWorld .

- Main Method ( public static void main(String[] args) ) : The main method is the entry
point of the program. It is where the program begins execution. The public keyword means
the method is accessible from outside the class, static means it belongs to the class rather
than an instance of the class, and void means it does not return any value. The String[]
args parameter allows the program to accept command-line arguments.

- Printing to the Console ( System.out.println ) : This line prints the message "Hello, World!"
to the console. System.out.println is used to output text.

- Variables and Arithmetic : The code then declares two integer variables ( number1 and
number2 ), adds them together, and stores the result in another variable ( sum ). Finally, it
prints the result to the console.

How to Run This Program

1. Write the Code : Save the code in a file named HelloWorld.java .

2. Compile the Code : Open a command prompt or terminal and navigate to the directory
where the file is saved. Compile the program using the following command:

sh
javac HelloWorld.java

This command will generate a HelloWorld.class file containing the bytecode.

3. Run the Code : Execute the compiled bytecode using the JVM with the following command:

sh
java HelloWorld
The output will be:

Hello, World!
Sum of 10 and 20 is: 30

This demonstrates the basic principles of how Java works, from writing and compiling code to
executing it on a JVM.

Understanding Getter and Setter Methods in Java


In object-oriented programming (OOP), encapsulation is one of the fundamental principles. It
refers to the bundling of data (variables) and methods (functions) that operate on the data into a
single unit called a class . Encapsulation also involves restricting direct access to some of an
object s components, which is where getter and setter methods come into play.

In this guide, we ll explore what getter and setter methods are, why they are used, and how to
implement them in Java with a comprehensive example.

---

Table of Contents

1. [What are Getter and Setter Methods?]( what-are-getter-and-setter-methods)


2. [Why Use Getter and Setter Methods?]( why-use-getter-and-setter-methods)
3. [Java Program Demonstrating Getter and Setter Methods](
java-program-demonstrating-getter-and-setter-methods)
4. [Explanation of the Code]( explanation-of-the-code)
5. [Benefits of Using Getter and Setter Methods]( benefits-of-using-getter-and-setter-methods)
6. [Conclusion]( conclusion)

---

What are Getter and Setter Methods?

Getter and setter methods are used to access and modify the private variables of a class
from outside that class.

- Getter Method : A method that retrieves or "gets" the value of a private variable.
- Setter Method : A method that updates or "sets" the value of a private variable.

These methods provide controlled access to the variables, allowing additional logic such as
validation or transformation when getting or setting values.

Syntax Example:

java
public class Example {
private int value;

// Getter method
public int getValue() {
return value;
}
// Setter method
public void setValue(int value) {
this.value = value;
}
}

---

Why Use Getter and Setter Methods?

Using getter and setter methods offers several advantages:

1. Encapsulation and Data Hiding : By declaring class variables as private and providing
public getter and setter methods, you can control how these variables are accessed and
modified.

2. Validation : Setter methods can include validation logic to ensure that only valid data is
assigned to the variables.

3. Flexibility and Maintainability : Changes to the internal implementation can be made without
affecting external code that uses the class. You can modify how data is stored or retrieved
internally while keeping the external interface consistent.

4. Read-Only or Write-Only Access : You can provide only a getter or a setter for a variable to
make it read-only or write-only, respectively.

5. Debugging and Logging : Getter and setter methods can include additional logic for
debugging or logging purposes.

---

Java Program Demonstrating Getter and Setter Methods

Let s create a simple Java program that demonstrates the use of getter and setter methods.

Person.java

java
// Person.java
public class Person {
// Private variables - accessible only within this class
private String name;
private int age;
private String email;

// Constructor
public Person(String name, int age, String email) {
this.setName(name);
this.setAge(age);
this.setEmail(email);
}

// Getter for name


public String getName() {
return name;
}

// Setter for name with validation


public void setName(String name) {
if (name != null && !name.trim().isEmpty()) {
this.name = name;
} else {
throw new IllegalArgumentException("Name cannot be null or empty.");
}
}

// Getter for age


public int getAge() {
return age;
}

// Setter for age with validation


public void setAge(int age) {
if (age > 0 && age <= 150) {
this.age = age;
} else {
throw new IllegalArgumentException("Age must be between 1 and 150.");
}
}

// Getter for email


public String getEmail() {
return email;
}

// Setter for email with validation


public void setEmail(String email) {
if (email != null && email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
this.email = email;
} else {
throw new IllegalArgumentException("Invalid email format.");
}
}

// Method to display person information


public void displayInfo() {
System.out.println("Person Information:");
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
System.out.println("Email: " + getEmail());
}
}

Main.java

java
// Main.java
public class Main {
public static void main(String[] args) {
try {
// Creating a new Person object using the constructor
Person person = new Person("Alice Johnson", 30, "[email protected]");

// Displaying initial information


person.displayInfo();

System.out.println("\nUpdating person information...\n");

// Updating person s information using setter methods


person.setName("Alice Smith");
person.setAge(31);
person.setEmail("[email protected]");

// Displaying updated information


person.displayInfo();

System.out.println("\nAttempting to set invalid age...");

// Attempting to set an invalid age


person.setAge(-5); // This will throw an exception

} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output

Person Information:
Name: Alice Johnson
Age: 30
Email: [email protected]

Updating person information...

Person Information:
Name: Alice Smith
Age: 31
Email: [email protected]

Attempting to set invalid age...


Error: Age must be between 1 and 150.

---

Explanation of the Code

Let s break down the code to understand how getter and setter methods work in this example.

Person Class

Private Variables

java
private String name;
private int age;
private String email;
- These variables are declared as private , meaning they cannot be accessed directly from
outside the Person class.

Constructor

java
public Person(String name, int age, String email) {
this.setName(name);
this.setAge(age);
this.setEmail(email);
}

- The constructor initializes the Person object by setting the values of name , age ,
and email using the setter methods. This ensures that any validation logic within the setters
is applied during object creation.

Getter and Setter Methods

getName() and setName()

java
public String getName() {
return name;
}

public void setName(String name) {


if (name != null && !name.trim().isEmpty()) {
this.name = name;
} else {
throw new IllegalArgumentException("Name cannot be null or empty.");
}
}

- getName() returns the value of the name variable.


- setName() sets the value of name after validating that it is neither null nor empty. If the
validation fails, it throws an IllegalArgumentException .

getAge() and setAge()

java
public int getAge() {
return age;
}

public void setAge(int age) {


if (age > 0 && age <= 150) {
this.age = age;
} else {
throw new IllegalArgumentException("Age must be between 1 and 150.");
}
}

- getAge() returns the value of the age variable.


- setAge() sets the value of age after validating that it is within a realistic range (1 to
150). If not, it throws an IllegalArgumentException .

getEmail() and setEmail()

java
public String getEmail() {
return email;
}

public void setEmail(String email) {


if (email != null && email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
this.email = email;
} else {
throw new IllegalArgumentException("Invalid email format.");
}
}

- getEmail() returns the value of the email variable.


- setEmail() sets the value of email after validating it against a simple regular expression
pattern to check for a basic email format. If the validation fails, it throws an
IllegalArgumentException .

displayInfo() Method

java
public void displayInfo() {
System.out.println("Person Information:");
System.out.println("Name: " + getName());
System.out.println("Age: " + getAge());
System.out.println("Email: " + getEmail());
}

- This method uses the getter methods to retrieve and display the person s information.

Main Class

java
public class Main {
public static void main(String[] args) {
try {
// Creating a new Person object
Person person = new Person("Alice Johnson", 30, "[email protected]");

// Displaying initial information


person.displayInfo();

// Updating information
person.setName("Alice Smith");
person.setAge(31);
person.setEmail("[email protected]");

// Displaying updated information


person.displayInfo();

// Attempting to set invalid age


person.setAge(-5); // Throws exception

} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

- The Main class demonstrates how to create and manipulate a Person object using
getter and setter methods.
- It also shows how exceptions are handled when invalid data is provided to the setter methods.

---

Benefits of Using Getter and Setter Methods


1. Control Over Data : You can control how variables are accessed and modified. For
example, you can make certain variables read-only by providing only getter methods.

2. Validation and Integrity : Setters allow you to include validation logic to maintain data
integrity. This ensures that the object s state is always valid.

3. Encapsulation : By hiding the internal representation of the object and exposing only
specific methods, you maintain a clean and understandable interface.

4. Flexibility : If you need to change how variables are stored or calculated internally, you can
do so without affecting code that uses your class, as long as the getters and setters remain
consistent.

5. Debugging and Logging : You can add logging or debugging statements within getters and
setters to monitor access and changes to variables.

6. Thread Safety : You can implement synchronization within getters and setters to make your
class thread-safe if needed.

7. Consistency : Following standard naming conventions for getters and setters makes your
code more readable and maintainable.

---

Conclusion

Getter and setter methods are essential tools in Java programming for implementing
encapsulation and maintaining control over the internal state of objects. They provide a
standardized way to access and modify private variables while allowing for additional logic such
as validation and logging.

By using getters and setters effectively, you can create robust, maintainable, and flexible code
that adheres to the principles of object-oriented programming.

---

Additional Tips:

- In modern Java development, tools like Lombok can auto-generate getter and setter
methods, reducing boilerplate code.
- Always ensure that your setter methods validate input appropriately to prevent invalid states.
- Follow standard naming conventions ( getVariableName() , setVariableName() ) for
consistency and compatibility with frameworks and tools that rely on these patterns.
References:

- [Official Java Documentation](https://docs.oracle.com/javase/tutorial/java/javaOO/index.html)


- [Effective Java by Joshua
Bloch](https://www.amazon.com/Effective-Java-Joshua-Bloch/dp/0134685997)

---

Feel free to modify and expand upon this example to suit more complex scenarios and
requirements!
Understanding Type Conversion in Java

Type conversion in Java is the process of converting a value of one data type into another. Java
provides two types of type conversions:

1. Implicit Type Conversion (Widening)


2. Explicit Type Conversion (Narrowing)

1. Implicit Type Conversion (Widening Conversion)

Implicit type conversion, also known as widening conversion , occurs automatically when a
smaller data type is converted to a larger data type. This is safe because there is no loss of
information. For example, converting an int to a long or a float to a double can be
done implicitly.

Hierarchy of Primitive Data Types:

- byte → short → int → long → float → double


- char → int → long → float → double

Example:

java
public class ImplicitTypeConversion {
public static void main(String[] args) {
int intValue = 100;
long longValue = intValue; // Implicit conversion from int to long
float floatValue = longValue; // Implicit conversion from long to float
double doubleValue = floatValue; // Implicit conversion from float to double

System.out.println("int value: " + intValue);


System.out.println("long value: " + longValue);
System.out.println("float value: " + floatValue);
System.out.println("double value: " + doubleValue);
}
}

Output:

int value: 100


long value: 100
float value: 100.0
double value: 100.0

2. Explicit Type Conversion (Narrowing Conversion)

Explicit type conversion, also known as narrowing conversion or casting , occurs when a
larger data type is converted to a smaller data type. This must be done explicitly by the
programmer because there is a risk of losing information.

Syntax for Explicit Conversion:

java
<target_data_type> variable_name = (<target_data_type>) variable_to_convert;

Example:

java
public class ExplicitTypeConversion {
public static void main(String[] args) {
double doubleValue = 100.04;
long longValue = (long) doubleValue; // Explicit conversion from double to long
int intValue = (int) longValue; // Explicit conversion from long to int

System.out.println("double value: " + doubleValue);


System.out.println("long value after casting: " + longValue);
System.out.println("int value after casting: " + intValue);
}
}

Output:

double value: 100.04


long value after casting: 100
int value after casting: 100

Explanation:

- doubleValue is explicitly cast to long , which truncates the decimal part.


- longValue is then cast to int , which retains the integer part.
3. Type Conversion between Primitive Types and Objects (Wrapper Classes)

Java provides wrapper classes for each of the primitive data types (e.g., Integer for int ,
Double for double ). Conversion between primitive types and their corresponding wrapper
classes is common in Java, especially when working with collections like ArrayList .

Boxing and Unboxing:

- Boxing : Converting a primitive type into its corresponding wrapper object (e.g., int to
Integer ).
- Unboxing : Converting a wrapper object back to its corresponding primitive type (e.g.,
Integer to int ).

Example:

java
public class BoxingUnboxing {
public static void main(String[] args) {
// Boxing
int primitiveInt = 10;
Integer wrappedInt = Integer.valueOf(primitiveInt); // Explicit boxing
Integer autoBoxedInt = primitiveInt; // Autoboxing

// Unboxing
int unboxedInt = wrappedInt.intValue(); // Explicit unboxing
int autoUnboxedInt = wrappedInt; // Auto-unboxing

System.out.println("Primitive int: " + primitiveInt);


System.out.println("Wrapped Integer (Boxing): " + wrappedInt);
System.out.println("Autoboxed Integer: " + autoBoxedInt);
System.out.println("Unboxed int: " + unboxedInt);
System.out.println("Auto-unboxed int: " + autoUnboxedInt);
}
}

Output:

Primitive int: 10
Wrapped Integer (Boxing): 10
Autoboxed Integer: 10
Unboxed int: 10
Auto-unboxed int: 10
4. Type Conversion in Expressions

Type conversion can also happen in expressions. When operands of different types are used in
an expression, Java automatically promotes the operands to the most extensive data type
involved.

Example:

java
public class TypePromotionInExpressions {
public static void main(String[] args) {
byte byteValue = 10;
int intValue = 20;
float floatValue = 30.5f;
double doubleValue = 40.5;

// In the following expression, byteValue is promoted to int, and then the result is promoted
to float, and finally to double.
double result = byteValue + intValue + floatValue + doubleValue;

System.out.println("Result of expression: " + result);


}
}

Output:

Result of expression: 101.0

Explanation:

- byteValue is promoted to int .


- The result of int + int is an int , which is then promoted to float when added to
floatValue .
- Finally, the result is promoted to double when added to doubleValue .

5. Type Conversion with Strings

Java allows converting between numeric types and String using methods provided in the
wrapper classes.
Example:

java
public class StringConversion {
public static void main(String[] args) {
int intValue = 100;
String strValue = Integer.toString(intValue); // Convert int to String
System.out.println("String value: " + strValue);

String str = "200";


int numValue = Integer.parseInt(str); // Convert String to int
System.out.println("Integer value: " + numValue);
}
}

Output:

String value: 100


Integer value: 200

Explanation:

- Integer.toString(intValue) converts the integer to a String .


- Integer.parseInt(str) converts the String back to an integer.

Summary of Type Conversion

1. Implicit (Widening) : Automatically converts a smaller type to a larger type (e.g., int to
long ).
2. Explicit (Narrowing) : Requires casting to convert a larger type to a smaller type (e.g.,
double to int ).
3. Boxing/Unboxing : Conversion between primitive types and their wrapper classes.
4. Expression Promotion : Automatic type promotion in expressions to the widest type.
5. String Conversion : Convert between numeric types and String using methods like
toString() and parseInt() .

Java’s type conversion mechanisms allow for flexibility while ensuring data safety and integrity,
especially when dealing with different data types in expressions, method arguments, and return
values.
### Understanding Constructors in Java

In Java, a **constructor** is a special method that is called when an object is instantiated.


Constructors are used to initialize the object's state, and they have the same name as the class
in which they are defined. They do not have a return type, not even `void`.

### Key Features of Constructors:

1. **Name:** The constructor's name must match the class name.


2. **No Return Type:** Constructors do not have a return type.
3. **Automatic Call:** Constructors are called automatically when an object is created.
4. **Initialization:** They are primarily used to initialize the object's attributes.
5. **Overloading:** Constructors can be overloaded, meaning you can define multiple
constructors in a class with different parameter lists.

### Types of Constructors

Java supports two types of constructors:

1. **Default Constructor (No-argument Constructor)**


2. **Parameterized Constructor**

### 1. Default Constructor

A **default constructor** is a constructor that takes no arguments. If no constructor is explicitly


defined in a class, the Java compiler automatically provides a default constructor that initializes
all member variables to their default values (e.g., `0` for `int`, `null` for objects).

**Example of Default Constructor:**

```java
public class Student {
// Instance variables
private String name;
private int age;

// Default constructor
public Student() {
name = "Unknown";
age = 18;
}

// Method to display student information


public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main(String[] args) {


// Creating an object using the default constructor
Student student = new Student();
student.displayInfo();
}
}
```

**Output:**

```
Name: Unknown
Age: 18
```

### 2. Parameterized Constructor

A **parameterized constructor** is a constructor that takes one or more parameters to initialize


an object with specific values.

**Example of Parameterized Constructor:**

```java
public class Student {
// Instance variables
private String name;
private int age;

// Parameterized constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display student information


public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Creating an object using the parameterized constructor
Student student = new Student("Alice", 22);
student.displayInfo();
}
}
```

**Output:**

```
Name: Alice
Age: 22
```

### Constructor Overloading

**Constructor overloading** occurs when a class has more than one constructor, each with a
different parameter list. The correct constructor is called based on the arguments passed during
object creation.

**Example of Constructor Overloading:**

```java
public class Student {
// Instance variables
private String name;
private int age;
private String course;

// Default constructor
public Student() {
name = "Unknown";
age = 18;
course = "Undeclared";
}

// Constructor with two parameters


public Student(String name, int age) {
this.name = name;
this.age = age;
this.course = "Undeclared";
}
// Constructor with three parameters
public Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
}

// Method to display student information


public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}

public static void main(String[] args) {


// Creating objects using different constructors
Student student1 = new Student();
Student student2 = new Student("Bob", 20);
Student student3 = new Student("Charlie", 25, "Computer Science");

student1.displayInfo();
System.out.println();
student2.displayInfo();
System.out.println();
student3.displayInfo();
}
}
```

**Output:**

```
Name: Unknown
Age: 18
Course: Undeclared

Name: Bob
Age: 20
Course: Undeclared

Name: Charlie
Age: 25
Course: Computer Science
```
**Explanation:**

- **student1** is created using the default constructor, initializing default values.


- **student2** is created using a constructor that takes two parameters (`name` and `age`).
- **student3** is created using a constructor that takes three parameters (`name`, `age`, and
`course`).

### Private Constructor

A **private constructor** is used when you want to restrict object creation from outside the class.
This is commonly used in singleton design patterns or utility classes.

**Example of Private Constructor:**

```java
public class Singleton {
private static Singleton instance = null;

// Private constructor
private Singleton() {
System.out.println("Singleton instance created");
}

// Static method to get the instance of the Singleton class


public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}

public void showMessage() {


System.out.println("Hello from Singleton!");
}

public static void main(String[] args) {


// Attempt to create multiple instances
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();

obj1.showMessage();
System.out.println(obj1 == obj2); // Will print true, as both references point to the same
instance
}
}
```

**Output:**

```
Singleton instance created
Hello from Singleton!
true
```

**Explanation:**

- The `Singleton` class restricts object creation by making its constructor private.
- The only way to get an instance is through the `getInstance()` method, ensuring that only one
instance of the class exists.

### Static Constructor (Not Supported in Java)

In some languages like C#, a static constructor is used to initialize static fields of a class.
However, **Java does not support static constructors**. Instead, static blocks are used to
initialize static variables.

**Example of Static Block in Java:**

```java
public class StaticBlockExample {
private static int counter;

// Static block
static {
counter = 10;
System.out.println("Static block executed. Counter initialized to " + counter);
}

public static void main(String[] args) {


System.out.println("Counter: " + counter);
}
}
```
**Output:**

```
Static block executed. Counter initialized to 10
Counter: 10
```

**Explanation:**

- The static block is executed when the class is first loaded into memory, initializing the `counter`
variable.

### Summary

- **Constructors** are special methods used to initialize objects.


- **Types of Constructors**:
- **Default Constructor**: Takes no arguments; provided by Java if no constructors are defined.
- **Parameterized Constructor**: Takes parameters to initialize the object with specific values.
- **Constructor Overloading** allows defining multiple constructors with different parameter lists.
- **Constructor Chaining** is the process of calling one constructor from another.
- **Private Constructors** restrict object creation from outside the class, commonly used in
singleton patterns.
- **Static Constructors** are not supported in Java, but static blocks serve a similar purpose.

Understanding constructors and their variations allows for more flexible and controlled object
creation in Java, leading to better-designed and more maintainable code.
### **Java Features**

Java is a powerful, object-oriented programming language known for its simplicity, robustness,
and versatility. Here are some of its key features:

1. **Simple**: Java has a clean syntax, easy to learn and use.


2. **Object-Oriented**: Java is built around the concept of objects, making it easy to model
real-world scenarios.
3. **Platform-Independent**: Java programs are compiled into bytecode, which can run on any
platform with a Java Virtual Machine (JVM).
4. **Secure**: Java provides a secure environment for developing and running applications by
incorporating security features like access control, cryptography, and more.
5. **Robust**: Java has strong memory management, exception handling, and type-checking
mechanisms.
6. **Multithreaded**: Java supports multithreading, allowing multiple tasks to run concurrently.
7. **High Performance**: Java's Just-In-Time (JIT) compiler enhances the performance of
applications.
8. **Distributed**: Java has strong networking capabilities, making it suitable for distributed
computing.
9. **Dynamic**: Java supports dynamic loading of classes and automatic garbage collection.

### **Java Syntax**

Java syntax defines the set of rules and structure for writing valid Java programs.

- **Class Declaration**: A class is declared using the `class` keyword.


- **Main Method**: The entry point of any Java program is the `main` method.
- **Statements**: Java statements end with a semicolon `;`.
- **Blocks**: Code blocks are enclosed in curly braces `{}`.

**Example:**

```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```

**Explanation:**

- `public`: Access modifier, making the class accessible everywhere.


- `class`: Defines a new class.
- `HelloWorld`: Name of the class.
- `main`: The main method where the program execution begins.
- `System.out.println()`: Prints the output to the console.

### **Java Data Types**

Java supports a variety of data types divided into two categories:

1. **Primitive Data Types**


2. **Reference/Object Data Types**

#### **1. Primitive Data Types**

Primitive data types are the most basic data types available in Java. There are 8 primitive data
types:

- **byte**: 8-bit integer, range: -128 to 127


- **short**: 16-bit integer, range: -32,768 to 32,767
- **int**: 32-bit integer, range: -2^31 to 2^31-1
- **long**: 64-bit integer, range: -2^63 to 2^63-1
- **float**: 32-bit floating point, single-precision
- **double**: 64-bit floating point, double-precision
- **char**: 16-bit Unicode character
- **boolean**: Represents two values, `true` or `false`

**Example:**

```java
public class DataTypesExample {
public static void main(String[] args) {
int age = 25;
double salary = 50000.50;
char grade =

'A';
boolean isEmployed = true;

System.out.println("Age: " + age);


System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Employed: " + isEmployed);
}
}
```
**Explanation:**

- `int age = 25;` declares an integer variable `age` and assigns it a value of 25.
- `double salary = 50000.50;` declares a floating-point variable `salary`.
- `char grade = 'A';` declares a character variable `grade`.
- `boolean isEmployed = true;` declares a boolean variable `isEmployed`.

**Output:**

```
Age: 25
Salary: 50000.5
Grade: A
Employed: true
```

#### **2. Reference/Object Data Types**

Reference data types are constructed from primitive data types and other objects. They include:

- **String**: Represents a sequence of characters.


- **Arrays**: Collection of similar data types.
- **Classes, Interfaces, Enums**: User-defined data types.

**Example:**

```java
public class ReferenceDataTypesExample {
public static void main(String[] args) {
String name = "John Doe";
int[] numbers = {1, 2, 3, 4, 5};

System.out.println("Name: " + name);


System.out.println("Numbers: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
```

**Output:**
```
Name: John Doe
Numbers:
12345
```

### **Control Statements**

Control statements determine the flow of execution in a program. Java supports the following
control statements:

1. **Decision-Making Statements**
2. **Looping Statements**
3. **Branching Statements**

#### **1. Decision-Making Statements**

- **if Statement**: Executes a block of code if a specified condition is true.

```java
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
```

- **if-else Statement**: Executes one block of code if a condition is true, another if it is false.

```java
int number = -10;
if (number > 0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is negative.");
}
```

- **else-if Ladder**: Checks multiple conditions.

```java
int number = 0;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
```

- **switch Statement**: Selects one of many blocks of code to be executed.

```java
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}
```

#### **2. Looping Statements**

- **for Loop**: Executes a block of code a specified number of times.

```java
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
```

- **while Loop**: Repeats a block of code while a condition is true.

```java
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
```

- **do-while Loop**: Executes a block of code once, then repeats it while a condition is true.

```java
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
```

#### **3. Branching Statements**

- **break Statement**: Exits a loop or switch statement.

```java
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("Count: " + i);
}
```

- **continue Statement**: Skips the current iteration of a loop.

```java
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Count: " + i);
}
```

### **Operators and Their Precedence**

Operators are special symbols used to perform operations on variables and values. Java
provides several types of operators:

1. **Arithmetic Operators**: `+`, `-`, `*`, `/`, `%`


2. **Relational Operators**: `==`, `!=`, `>`, `<`, `>=`, `<=`
3. **Logical Operators**: `&&`, `||`, `!`
4. **Bitwise Operators**: `&`, `|`, `^`, `~`, `<<`, `>>`, `>>>`
5. **Assignment Operators**: `=`, `+=`, `-=`, `*=`, `/=`, `%=`
6. **Unary Operators**: `+`, `-`, `++`, `--`, `~`, `!`
7. **Ternary Operator**: `?:`

**Example:**

```java
public class OperatorsExample {
public static void main(String[] args) {
int a = 10, b = 5;

// Arithmetic operators
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));

// Relational operators
System.out.println("a == b: " + (a == b));
System.out.println("a != b: " + (a != b));

// Logical operators
System.out.println("(a > b) && (a > 0): " + ((a > b) && (a > 0)));

// Unary operators
int c = ++a;
System.out.println("Value of c after increment: " + c);

// Ternary operator
String result = (a > b) ? "a is greater" : "b is greater";
System.out.println("Result: " + result);
}
}
```

**Output:**

```
a + b = 15
a-b=5
a * b = 50
a/b=2
a == b: false
a != b: true
(a > b) && (a > 0): true
Value of c after increment: 11
Result: a is greater
```

**Operator Precedence:** The order in which operators are evaluated in an expression. For
example, multiplication (`*`) has higher precedence than addition (`+`).

### **Introduction to Class**

A class in Java is a blueprint for creating objects. It encapsulates data (instance variables) and
behavior (methods) into a single unit.

#### **Instance Members and Member Functions**

- **Instance Members**: Variables defined inside a class but outside any method. These
represent the state of an object.
- **Member Functions (Methods)**: Blocks of code that perform operations on instance variables
and define the behavior of an object.

**Example:**

```java
public class Car {
// Instance variables
String model;
int year;

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

// Member function
public void displayInfo() {
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}

public static void main(String[] args) {


// Creating an object of Car class
Car myCar = new Car("Tesla Model S", 2022);
myCar.displayInfo();
}
}
```

**Output:**

```
Model: Tesla Model S
Year: 2022
```

### **String Handling**

Strings in Java are objects that represent sequences of characters. The `String` class provides
a wide range of methods for string manipulation.

#### **String Creation**

- **Using String Literal**: Strings can be created by directly assigning a string literal to a `String`
variable.

```java
String greeting = "Hello, World!";
```

- **Using the `new` Keyword**: Strings can also be created using the `new` keyword.

```java
String greeting = new String("Hello, World!");
```

#### **String Methods**

1. **Length**: `length()` returns the number of characters in a string.

```java
String str = "Hello";
System.out.println("Length: " + str.length());
```

2. **Concatenation**: `concat()` joins two strings.

```java
String str1 = "Hello, ";
String str2 = "World!";
String result = str1.concat(str2);
System.out.println(result);
```
### **Understanding a Class in Java**

A **class** in Java is a blueprint or template from which objects are created. A class
encapsulates data (attributes) and methods (functions) that operate on the data. In
object-oriented programming, a class defines the properties and behaviors of objects, which are
instances of the class.

### **Anatomy of a Java Class**

A Java class typically consists of the following components:

1. **Class Declaration**
2. **Instance Variables (Fields)**
3. **Constructors**
4. **Methods**
5. **Access Modifiers**
6. **Main Method (if applicable)**

Let’s break down each part of a class:

#### **1. Class Declaration**

This is where the class is defined. It includes the class keyword, the name of the class, and
optionally, access modifiers and other keywords.

```java
public class Car {
// class body
}
```

- `public`: Access modifier that makes the class accessible from any other class.
- `class`: Keyword used to declare a class.
- `Car`: The name of the class.

#### **2. Instance Variables (Fields)**

These are variables defined within a class but outside any methods. They represent the
properties or attributes of the class.

```java
public class Car {
// Instance variables
String model;
String color;
int year;
}
```

- `String model;`: Represents the model of the car.


- `String color;`: Represents the color of the car.
- `int year;`: Represents the manufacturing year of the car.

#### **3. Constructors**

A constructor is a special method that is called when an object is instantiated. It is used to


initialize the object’s state.

```java
public class Car {
String model;
String color;
int year;

// Constructor
public Car(String model, String color, int year) {
this.model = model;
this.color = color;
this.year = year;
}
}
```

- `public Car(String model, String color, int year)`: Constructor with parameters to initialize the
car’s properties.

#### **4. Methods**

Methods define the behaviors of the class. They perform operations on the instance variables.

```java
public class Car {
String model;
String color;
int year;

public Car(String model, String color, int year) {


this.model = model;
this.color = color;
this.year = year;
}

// Method to display car details


public void displayDetails() {
System.out.println("Model: " + model);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
}
}
```

- `public void displayDetails()`: Method to print out the details of the car.

#### **5. Access Modifiers**

Access modifiers control the visibility of classes, methods, and variables. The main access
modifiers are:

- `public`: The member is accessible from any other class.


- `private`: The member is accessible only within its own class.
- `protected`: The member is accessible within its own package and by subclasses.
- (default, no modifier): The member is accessible within its own package.

```java
public class Car {
private String model;
private String color;
private int year;

public Car(String model, String color, int year) {


this.model = model;
this.color = color;
this.year = year;
}

public void displayDetails() {


System.out.println("Model: " + model);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
}
}
```
- `private String model;`: The `model` variable is accessible only within the `Car` class.

#### **6. Main Method**

The `main` method is the entry point of a Java program. It is where the program begins
execution.

```java
public class Car {
private String model;
private String color;
private int year;

public Car(String model, String color, int year) {


this.model = model;
this.color = color;
this.year = year;
}

public void displayDetails() {


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

public static void main(String[] args) {


// Creating an object of the Car class
Car myCar = new Car("Tesla Model S", "Red", 2022);
// Calling the method to display details
myCar.displayDetails();
}
}
```

- `public static void main(String[] args)`: The main method where program execution begins.
- `Car myCar = new Car("Tesla Model S", "Red", 2022);`: Instantiates a `Car` object.
- `myCar.displayDetails();`: Calls the `displayDetails` method to print the car details.

### **Complete Program Example**

Here's the complete example that combines all the elements discussed:

```java
public class Car {
// Instance variables (Fields)
private String model;
private String color;
private int year;

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

// Method to display car details


public void displayDetails() {
System.out.println("Model: " + model);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
}

// Main method (Entry point of the program)


public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Tesla Model S", "Red", 2022);
// Calling the method to display details
myCar.displayDetails();
}
}
```

### **Explanation:**

- **Class Declaration (`public class Car`)**: The `Car` class is declared as public, meaning it can
be accessed from anywhere.
- **Instance Variables (`private String model`, `private String color`, `private int year`)**: These
variables store the attributes of a car.
- **Constructor (`public Car(String model, String color, int year)`)**: Initializes the car’s attributes
when an object is created.
- **Method (`public void displayDetails()`)**: A method that prints the car's details to the console.
- **Main Method (`public static void main(String[] args)`)**: The starting point of the program
where a `Car` object is created and its details are displayed.

### **Summary**
- **Class**: Blueprint for creating objects; it encapsulates data and methods.
- **Instance Variables**: Attributes of the class that define the state of an object.
- **Constructor**: Initializes an object’s state upon creation.
- **Methods**: Define the behavior of the objects created from the class.
- **Access Modifiers**: Control the visibility of class members.
- **Main Method**: The entry point for Java programs.

This structure provides a modular approach to building software, allowing developers to create
reusable, maintainable, and scalable code.

BREAK AND CONTINUE

public class BreakContinueExample {


public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
// Continue to the next iteration if the number is odd
if (i % 2 != 0) {
continue; // Skip odd numbers
}

// Break the loop if the number is greater than 16


if (i > 16) {
break; // Stop the loop when i is greater than 16
}

// Print the even number


System.out.println(i);
}
}
}

Checks whether the number a = 105 is prime.


Checks whether the number is even or odd.
Determines the factorial of the number.

public class NumberOperations {


public static void main(String[] args) {
int a = 105;
// Check if the number is prime
if (isPrime(a)) {
System.out.println(a + " is a prime number.");
} else {
System.out.println(a + " is not a prime number.");
}

// Check if the number is even or odd


if (a % 2 == 0) {
System.out.println(a + " is an even number.");
} else {
System.out.println(a + " is an odd number.");
}

// Calculate and print the factorial of the number


long factorial = calculateFactorial(a);
System.out.println("The factorial of " + a + " is " + factorial);
}

// Method to check if a number is prime


public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

// Method to calculate the factorial of a number


public static long calculateFactorial(int num) {
long factorial = 1;
for (int i = 2; i <= num; i++) {
factorial *= i;
}
return factorial;
}
}

Palindrome
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam"; // You can change this to test other strings

if (isPalindrome(str)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}

// Method to check if a string is a palindrome


public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false; // Characters don't match, not a palindrome
}
left++;
right--;
}

return true; // All characters matched, it's a palindrome


}
}

Matrix multiplication

public class MatrixMultiplication {


public static void main(String[] args) {
// Define the matrices
int[][] matrixA = {
{1, 2, 3},
{4, 5, 6}
};

int[][] matrixB = {
{7, 8},
{9, 10},
{11, 12}
};
// Perform matrix multiplication
int[][] resultMatrix = multiplyMatrices(matrixA, matrixB);

// Print the result matrix


System.out.println("Result of Matrix Multiplication:");
printMatrix(resultMatrix);
}

// Method to multiply two matrices


public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB) {
int rowsA = matrixA.length;
int colsA = matrixA[0].length;
int rowsB = matrixB.length;
int colsB = matrixB[0].length;

// Check if multiplication is possible


if (colsA != rowsB) {
throw new IllegalArgumentException("Number of columns in Matrix A must be equal to
the number of rows in Matrix B.");
}

// Initialize the result matrix


int[][] resultMatrix = new int[rowsA][colsB];

// Perform multiplication
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
resultMatrix[i][j] = 0;
for (int k = 0; k < colsA; k++) {
resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}

return resultMatrix;
}

// Method to print a matrix


public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

ARRAY

import java.util.Arrays;

public class ArrayOperations {


public static void main(String[] args) {
// Initialize an array
int[] numbers = {5, 2, 9, 1, 5, 6};

// Print all values of the array


System.out.println("Array values:");
printArray(numbers);

// Print value at a specific index (e.g., index 2)


int index = 2;
if (index >= 0 && index < numbers.length) {
System.out.println("Value at index " + index + ": " + numbers[index]);
} else {
System.out.println("Index " + index + " is out of bounds.");
}

// Sort the array


Arrays.sort(numbers);

// Print sorted array


System.out.println("Sorted array:");
printArray(numbers);
}

// Method to print array values


public static void printArray(int[] array) {
for (int value : array) {
System.out.print(value + " ");
}
System.out.println();
}
}

CALCULATE AGE
Import java.time.LocalDate;
import java.time.Period;

// Driver Class
public class GfGAgeCalculator {
// Main Function
public static void main(String[] args) {
// Birthdate
LocalDate birthdate = LocalDate.of(1997, 10, 03);

// Current Date
LocalDate currentDate = LocalDate.now();

// Calculate Age
int age = calculateAge(birthdate, currentDate);

// Print Age
System.out.println("Age: " + age + " years");
}

public static int calculateAge(LocalDate birthdate, LocalDate


currentDate) {
// Calculate period between birthdate and current date
Period period = Period.between(birthdate, currentDate);

return period.getYears();
}
}

MATH CLASS

public class MathOperationsExample {


public static void main(String[] args) {
// Example number
double number = 16.0;

// Square of a number
double square = Math.pow(number, 2);
System.out.println("Square of " + number + " is: " + square);

// Square root of a number


double sqrt = Math.sqrt(number);
System.out.println("Square root of " + number + " is: " + sqrt);
// Cube root of a number
double cubeRoot = Math.cbrt(number);
System.out.println("Cube root of " + number + " is: " + cubeRoot);

// Inverse of a number
double inverse = 1 / number;
System.out.println("Inverse of " + number + " is: " + inverse);

// Trigonometric functions (using radians)


double angleInRadians = Math.toRadians(45); // Convert degrees to radians

double sinValue = Math.sin(angleInRadians);


double cosValue = Math.cos(angleInRadians);
double tanValue = Math.tan(angleInRadians);

System.out.println("Sin(45 degrees) is: " + sinValue);


System.out.println("Cos(45 degrees) is: " + cosValue);
System.out.println("Tan(45 degrees) is: " + tanValue);

// Area of a circle
double radius = 5.0;
double area = Math.PI * Math.pow(radius, 2);
System.out.println("Area of a circle with radius " + radius + " is: " + area);

// Volume of a sphere
double volume = (4 / 3.0) * Math.PI * Math.pow(radius, 3);
System.out.println("Volume of a sphere with radius " + radius + " is: " + volume);
}
}

ACCESS MODIFIER

In Java, trying to access a private variable from outside its class will result in a **compile-time
error**. This error occurs because private variables are accessible only within the class where
they are declared. This encapsulation is a core principle of object-oriented programming that
helps to protect the internal state of an object from unintended modifications.

### **Example Program:**

Here’s a simple example to demonstrate this:

```java
class MyClass {
// Private variable
private int privateVar = 10;

// Public method to access privateVar


public int getPrivateVar() {
return privateVar;
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();

// Accessing private variable directly (This will cause a compile-time error)


// System.out.println("Private variable: " + obj.privateVar);

// Accessing private variable through public method


System.out.println("Private variable accessed via method: " + obj.getPrivateVar());
}
}
```

### **Explanation:**

1. **Private Variable:**
- `private int privateVar = 10;` is a private variable in `MyClass`. It is only accessible within
`MyClass`.

2. **Accessing Private Variable Directly:**


- The line `System.out.println("Private variable: " + obj.privateVar);` is commented out because
it will cause a compile-time error. This error occurs because `privateVar` is private to `MyClass`,
and direct access from the `Main` class is not allowed.

3. **Accessing Through Public Method:**


- The line `System.out.println("Private variable accessed via method: " + obj.getPrivateVar());`
correctly accesses the private variable through a public getter method (`getPrivateVar()`), which
is allowed.

### **Compile-Time Error Message:**

When attempting to access a private variable directly from outside its class, you’ll encounter an
error similar to:

```
Main.java:10: error: privateVar has private access in MyClass
System.out.println("Private variable: " + obj.privateVar);
```

### **Conclusion:**

- **Private Access Modifier:** Variables declared with the `private` access modifier are not
accessible outside their class.
- **Encapsulation:** Use getter and setter methods to access private variables from outside the
class. This approach maintains the integrity of the object's state while providing controlled
access to its data.

You might also like