MST 1
MST 1
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.
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
- 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.
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
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.
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
---
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;
}
}
---
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.
---
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);
}
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]");
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Output
Person Information:
Name: Alice Johnson
Age: 30
Email: [email protected]
Person Information:
Name: Alice Smith
Age: 31
Email: [email protected]
---
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.
java
public String getName() {
return name;
}
java
public int getAge() {
return age;
}
java
public String getEmail() {
return email;
}
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]");
// Updating information
person.setName("Alice Smith");
person.setAge(31);
person.setEmail("[email protected]");
} 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.
---
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:
---
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:
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.
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
Output:
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.
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
Output:
Explanation:
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 : 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
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;
Output:
Explanation:
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);
Output:
Explanation:
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
```java
public class Student {
// Instance variables
private String name;
private int age;
// Default constructor
public Student() {
name = "Unknown";
age = 18;
}
**Output:**
```
Name: Unknown
Age: 18
```
```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;
}
**Output:**
```
Name: Alice
Age: 22
```
**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.
```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";
}
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:**
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.
```java
public class Singleton {
private static Singleton instance = null;
// Private constructor
private Singleton() {
System.out.println("Singleton instance created");
}
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.
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.
```java
public class StaticBlockExample {
private static int counter;
// Static block
static {
counter = 10;
System.out.println("Static block executed. Counter initialized to " + counter);
}
```
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
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:
Java syntax defines the set of rules and structure for writing valid Java programs.
**Example:**
```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
**Explanation:**
Primitive data types are the most basic data types available in Java. There are 8 primitive data
types:
**Example:**
```java
public class DataTypesExample {
public static void main(String[] args) {
int age = 25;
double salary = 50000.50;
char grade =
'A';
boolean isEmployed = true;
- `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
```
Reference data types are constructed from primitive data types and other objects. They include:
**Example:**
```java
public class ReferenceDataTypesExample {
public static void main(String[] args) {
String name = "John Doe";
int[] numbers = {1, 2, 3, 4, 5};
**Output:**
```
Name: John Doe
Numbers:
12345
```
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**
```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.");
}
```
```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.");
}
```
```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;
}
```
```java
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
```
```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);
```
```java
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("Count: " + i);
}
```
```java
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Count: " + i);
}
```
Operators are special symbols used to perform operations on variables and values. Java
provides several types of operators:
**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 (`+`).
A class in Java is a blueprint for creating objects. It encapsulates data (instance variables) and
behavior (methods) into a single unit.
- **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);
}
**Output:**
```
Model: Tesla Model S
Year: 2022
```
Strings in Java are objects that represent sequences of characters. The `String` class provides
a wide range of methods for string manipulation.
- **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!");
```
```java
String str = "Hello";
System.out.println("Length: " + str.length());
```
```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.
1. **Class Declaration**
2. **Instance Variables (Fields)**
3. **Constructors**
4. **Methods**
5. **Access Modifiers**
6. **Main Method (if applicable)**
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.
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;
}
```
```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.
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 void displayDetails()`: Method to print out the details of the car.
Access modifiers control the visibility of classes, methods, and variables. The main access
modifiers are:
```java
public class Car {
private String model;
private String color;
private int year;
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 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.
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;
}
### **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.
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.");
}
}
Matrix multiplication
int[][] matrixB = {
{7, 8},
{9, 10},
{11, 12}
};
// Perform matrix multiplication
int[][] resultMatrix = multiplyMatrices(matrixA, matrixB);
// 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;
}
ARRAY
import java.util.Arrays;
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");
}
return period.getYears();
}
}
MATH CLASS
// Square of a number
double square = Math.pow(number, 2);
System.out.println("Square of " + number + " is: " + square);
// Inverse of a number
double inverse = 1 / number;
System.out.println("Inverse of " + number + " is: " + inverse);
// 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.
```java
class MyClass {
// Private variable
private int privateVar = 10;
### **Explanation:**
1. **Private Variable:**
- `private int privateVar = 10;` is a private variable in `MyClass`. It is only accessible within
`MyClass`.
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.