❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayJava

Mastering Java Packages: Organize Your Code Effectively

12 March 2024 at 13:40

Introduction: In Java programming, packages play a crucial role in organizing and managing code efficiently. Understanding how to create, use, and leverage packages can significantly improve code maintainability and reusability. In this comprehensive guide, we’ll delve into the intricacies of Java packages, covering everything from basics to advanced techniques, along with real-life examples.


Absolutely! Let’s expand on each section with more nuanced explanations and real-life examples.


1. Understanding Java Packages:

In Java programming, a package is a mechanism to encapsulate a group of classes, interfaces, and sub-packages. This encapsulation helps in organizing code logically and hierarchically. Think of packages as folders on your computer, where you group related files together for better organization.

// File: Simple.java  
package mypack;  

public class Simple {  
    public static void main(String args[]) {  
        System.out.println("Welcome to package");  
    }  
}

Real-life Example: Imagine you’re developing a web application that includes modules for authentication, user management, and payment processing. You can create separate packages for each module (authentication, usermanagement, payment) to organize the related classes and interfaces.

2. Advantages of Java Packages:

Packages offer several benefits, including:

  • Categorization and Organization: Packages help in organizing classes and interfaces into meaningful groups, making it easier to manage large codebases.
  • Access Protection: By using access modifiers like public, private, and protected, packages allow you to control access to classes and members, enhancing encapsulation and security.
  • Prevention of Naming Collisions: Since classes within a package share a common namespace, packages help avoid naming conflicts, especially when integrating third-party libraries.

Real-life Example: Consider a software development company working on multiple projects simultaneously. By organizing each project’s codebase into separate packages, they can avoid confusion and ensure that classes and interfaces are unique within each project.

3. Creating and Compiling Java Packages:

To create a package in Java, you use the package keyword followed by the package name. When compiling packages, you specify the destination directory using the -d option with the javac command.

Real-life Example: Suppose you’re developing a Java application for a financial institution. You can create a package named com.financial.app to contain all classes and interfaces related to the application. When compiling, you can use the -d option to specify the directory structure for the compiled classes.

4. Running Java Packages:

To run Java packages, you use fully qualified names to specify the package and class names. This ensures that the Java Virtual Machine (JVM) can locate and execute the desired class.

Real-life Example: Imagine you’re deploying a Java web application on a server. To run the application, you provide the fully qualified name of the main class, along with any necessary configuration parameters, to the server’s startup script.

5. Accessing Packages from Another Package:

Java provides various ways to access classes and interfaces from external packages, including using wildcards, specific class names, or fully qualified names.

Real-life Example: In a software project with multiple modules, you may need to access utility classes from a shared package. By importing the package using a wildcard (import com.company.utils.*), you can easily access all utility classes within your module.

6. Subpackages in Java:

Subpackages are packages nested within other packages, allowing for further categorization and organization of code.

Real-life Example: Consider a gaming company developing a multiplayer online game. They can create separate packages for game mechanics (com.company.gameplay), user interface (com.company.ui), and networking (com.company.network). Within the networking package, they can further categorize classes related to client-server communication by creating subpackages like com.company.network.client and com.company.network.server.

7. Managing Class Files:

Java class files can be compiled and stored in different directories or drives. You can specify the classpath to load classes dynamically during runtime.

Real-life Example: When deploying a Java application to a production server, you may store compiled class files in a separate directory for better organization and maintenance. By setting the classpath appropriately, the JVM can locate and load the required classes at runtime.

8. Best Practices and Considerations:

When working with Java packages, it’s essential to follow best practices and naming conventions to ensure consistency and readability across projects.

Real-life Example: In a collaborative software development environment, adhering to standardized package naming conventions (e.g., using reverse domain naming for packages) ensures that team members can easily understand and navigate the codebase, leading to faster development cycles and fewer errors.

// MainApplication.java
package com.webapp;

import com.webapp.authentication.Authenticator;
import com.webapp.usermanagement.UserManager;
import com.webapp.payment.PaymentProcessor;

public class MainApplication {
    public static void main(String[] args) {
        Authenticator authenticator = new Authenticator();
        UserManager userManager = new UserManager();
        PaymentProcessor paymentProcessor = new PaymentProcessor();
        
        // Use the classes to perform application tasks
        // For example: authenticator.authenticate(), userManager.createUser(), etc.
    }
}

// Application code
import com.shared.utils.StringUtil;

public class MyApp {
    public static void main(String[] args) {
        String str = "Hello, world!";
        if (StringUtil.isEmpty(str)) {
            System.out.println("String is empty.");
        } else {
            System.out.println("String is not empty.");
        }
    }
}

// GameEngine.java
package com.game.engine;

public class GameEngine {
    // Game engine logic
}
// Authentication package
package com.webapp.authentication;

public class Authenticator {
    public boolean authenticate(String username, String password) {
        // Authentication logic
        return true;
    }
}



// Game mechanics package
package com.game.engine;

public class GameEngine {
    // Game engine logic
}

// User management package
package com.webapp.usermanagement;

public class UserManager {
    public void createUser(String username, String email) {
        // User creation logic
    }
}

// Shared utilities package
package com.shared.utils;

public class StringUtil {
    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
}

Conclusion: Mastering Java packages is essential for any Java developer striving to write clean, maintainable code. By effectively organizing code into packages and subpackages, developers can streamline development processes and enhance code readability. With the knowledge gained from this guide, you’ll be well-equipped to leverage Java packages efficiently in your projects, leading to better software design and development practices.


Understanding Wrapper Classes in Java

8 March 2024 at 04:54

Wrapper classes in Java provide a versatile toolset for developers to work with both primitive data types and objects seamlessly. In this post, we’ll delve deeper into wrapper classes, exploring their features, applications, and real-life use cases.

What are Wrapper Classes?

Wrapper classes in Java encapsulate primitive data types, allowing them to be treated as objects. They provide a bridge between the world of primitives and the world of objects. The eight wrapper classes provided in Java are:

  • Boolean
  • Character
  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double

Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive data types into their corresponding wrapper classes. For instance, converting int to Integer, double to Double, etc.

public class Autoboxing {
    public static void main(String args[]) {
        int a = 20;
        Integer i = Integer.valueOf(a); // Converting int into Integer explicitly
        Integer j = a; // Autoboxing

        System.out.println(a + " " + i + " " + j);
    }
}

output:

Unboxing: The reverse process of autoboxing, where wrapper objects are automatically converted back into their corresponding primitive types.

public class Unboxing{
    public static void main(String args[]) {
        Integer a = new Integer(3);
        int i = a.intValue(); // Converting Integer to int explicitly
        int j = a; // Unboxing

        System.out.println(a + " " + i + " " + j);
    }
}

output:

Use Cases of Wrapper Classes

  1. Change the value in Method: Wrapper classes facilitate passing parameters to methods. They allow the method to modify the original value, as opposed to primitives.
  2. Serialization: Wrapper classes are pivotal in serialization, where objects need to be converted into streams for transmission or storage.
  3. Synchronization: Java synchronization, often used in multithreading scenarios, works with objects. Wrapper classes enable synchronization when dealing with primitives.
  4. Collection Framework: Java’s collection framework operates solely on objects. Wrapper classes enable the use of primitives in collections such as ArrayList, LinkedList, etc.

Real-Life Examples

  1. Banking System: Consider a banking application where customer data needs to be stored and processed. The customer’s age, represented as an int, can be wrapped in an Integer object to facilitate storage and manipulation within the application.
import java.util.HashMap;

public class BankingSystem {
    // Simulating customer data storage using HashMap
    private HashMap<Integer, Integer> customerAges;

    public BankingSystem() {
        customerAges = new HashMap<>();
    }

    // Method to add customer age to the system
    public void addCustomerAge(int customerId, int age) {
        customerAges.put(customerId, age);
    }

    // Method to retrieve customer age from the system
    public Integer getCustomerAge(int customerId) {
        return customerAges.get(customerId);
    }

    public static void main(String[] args) {
        BankingSystem bankingSystem = new BankingSystem();
        bankingSystem.addCustomerAge(1001, 35);
        bankingSystem.addCustomerAge(1002, 42);

        int customerId = 1001;
        Integer customerAge = bankingSystem.getCustomerAge(customerId);
        System.out.println("Customer ID: " + customerId + ", Age: " + customerAge);
    }
}

output:

2.Student Records: In an educational institution’s database system, student grades, represented as int values, can be encapsulated in Integer objects. This allows for easy retrieval, comparison, and manipulation of grade data.

import java.util.ArrayList;

public class StudentRecords {
    // Storing student grades using ArrayList
    private ArrayList<Integer> studentGrades;

    public StudentRecords() {
        studentGrades = new ArrayList<>();
    }

    // Method to add student grades to the records
    public void addStudentGrade(int grade) {
        studentGrades.add(grade);
    }

    // Method to calculate average grade
    public double calculateAverageGrade() {
        int sum = 0;
        for (int grade : studentGrades) {
            sum += grade;
        }
        return (double) sum / studentGrades.size();
    }

    public static void main(String[] args) {
        StudentRecords studentRecords = new StudentRecords();
        studentRecords.addStudentGrade(85);
        studentRecords.addStudentGrade(90);
        studentRecords.addStudentGrade(75);

        double averageGrade = studentRecords.calculateAverageGrade();
        System.out.println("Average Grade: " + averageGrade);
    }
}

  • Temperature Monitoring: In a weather monitoring system, temperatures measured as double values can be wrapped in Double objects. This allows for additional functionalities such as conversion between Celsius and Fahrenheit, statistical analysis, etc.
public class TemperatureMonitoring {
    // Storing temperature readings using Double wrapper class
    private Double currentTemperature;

    // Method to set current temperature
    public void setCurrentTemperature(double temperature) {
        currentTemperature = temperature;
    }

    // Method to convert temperature from Celsius to Fahrenheit
    public double convertToCelsius() {
        return (currentTemperature - 32) * 5 / 9;
    }

    public static void main(String[] args) {
        TemperatureMonitoring temperatureMonitoring = new TemperatureMonitoring();
        temperatureMonitoring.setCurrentTemperature(98.6);

        double currentCelsiusTemperature = temperatureMonitoring.convertToCelsius();
        System.out.println("Current Temperature (Celsius): " + currentCelsiusTemperature);
    }
}

output:

Conclusion

Wrapper classes play a crucial role in Java programming by providing a seamless interface between primitive data types and objects. Understanding wrapper classes and their applications is essential for building robust and scalable Java applications.

By leveraging wrapper classes effectively, developers can streamline their code, enhance readability, and unlock a wide range of functionalities offered by the Java platform.

references:

https://www.javatpoint.com/object-and-class-in-java

Change the channel in my Tv: Practice for passing the object as argument to method

8 March 2024 at 04:15
  1. Create a class β€˜TV’.
  2. Create a method as below.
    public void watch(Channel channel)
    {
    System.out.println(channel.channelName);
    System.out.println(channel.program); }
  3. Create a class called β€˜Consumer’.
    3.1. Have channelName, program as non-static String variables.
  4. Create main method in it.
  5. Create an instance called tv_watcher.
    5.1. Initialize channelName, program
    eg. tv_watcher.channelName = β€œvijay tv”;
  6. Create an instance of TV, called β€˜samsung’.
  7. Using β€˜samsung’ instance, call watch method.
  8. Pass tv_watcher as argument.
  9. Confirm output gets changed for different values given by tv_watcher.
public class Consumer{
String channelName;
String program;
public static void main(String[] args){
Consumer tv_watcher = new Consumer();
tv_watcher.channelName = "vijay tv";
tv_watcher.program ="kalakapovathu yaaru";

TV samsung = new TV();
samsung.watch(tv_watcher);
}
}

public class TV{


public void watch(Consumer channel)
    {
    System.out.println(channel.channelName);
    System.out.println(channel.program);

    }

}


In above program we have class called Consumer and it have properties channelName; and program inglobal scope. Inside the main method of Cosumer we are initiating the object of Consumer class as tv_watcher. After that we are assigning values for each properties.

In next step we are initializing instance of TV class as samsung and then we are calling watch method in it with passing tv_watcher object as parameter.

Tv class is reciveing that object as parameter so if we pass any data then we can use data type (Ex: int 5)in function definition but here we are passing an object then how to mention it in method definition?.so here is the Answer we need to use the class name of object before the value(object) that we are passing(Ex: Consumer channel).

Objects and Classes in Java

7 March 2024 at 21:09

In this blog we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

What is an object in Java

object in Java

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.

An object has three characteristics:

  • State:Β represents the data (value) of an object.
  • Behavior:Β represents the behavior (functionality) of an object such as deposit, withdraw, etc.
  • Identity:Β An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
Characteristics of Object in Java

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.

An object is an instance of a class.Β A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.

Object Definitions:

  • An object isΒ a real-world entity.
  • An object isΒ a runtime entity.
  • The object isΒ an entity which has state and behavior.
  • The object isΒ an instance of a class.

What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can’t be physical.

A class in Java can contain:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface
Class in Java

Syntax to declare a class:

  1. classΒ <class_name>{Β Β 
  2. Β Β Β Β field;Β Β 
  3. Β Β Β Β method;Β Β 
  4. }Β Β 

Instance variable in Java

A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn’t get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.


Method in Java

In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method

  • Code Reusability
  • Code Optimization

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.


Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object’s value.

Here, we are creating a main() method inside the class.

File: Student.java

//Java Program to illustrate how to define a class and fields  
//Defining a Student class.  
class Student{  
 //defining fields  
 int id;//field or data member or instance variable  
 String name;  
 //creating main method inside the Student class  
 public static void main(String args[]){  
  //Creating an object or instance  
  Student s1=new Student();//creating an object of Student  
  //Printing values of the object  
  System.out.println(s1.id);//accessing member through reference variable  
  System.out.println(s1.name);  
 }  
}  

Output:

0 
null

Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better approach than previous one. Let’s see a simple example, where we are having main() method in another class.

We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.

//Java Program to demonstrate having the main method in   
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

Output:

0 
null

3 Ways to initialize object

There are 3 ways to initialize object in Java.

  1. By reference variable
  2. By method
  3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let’s see a simple example where we are going to initialize the object through a reference variable.

class Student{  
 int id;  
 String name;  
}  
class TestStudent2{  
 public static void main(String args[]){  
  Student s1=new Student();  
  s1.id=101;  
  s1.name="Sonoo";  
  System.out.println(s1.id+" "+s1.name);//printing members with a white space  
 }  
}  

Output:

101 Sonoo


We can also create multiple objects and store information in it through reference variable.

Output:
class Student{  
 int id;  
 String name;  
}  
class TestStudent3{  
 public static void main(String args[]){  
  //Creating objects  
  Student s1=new Student();  
  Student s2=new Student();  
  //Initializing objects  
  s1.id=101;  
  s1.name="Sonoo";  
  s2.id=102;  
  s2.name="Amit";  
  //Printing data  
  System.out.println(s1.id+" "+s1.name);  
  System.out.println(s2.id+" "+s2.name);  
 }  
}  
101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.

class Student{  
 int rollno;  
 String name;  
 void insertRecord(int r, String n){  
  rollno=r;  
  name=n;  
 }  
 void displayInformation(){System.out.println(rollno+" "+name);}  
}  
class TestStudent4{  
 public static void main(String args[]){  
  Student s1=new Student();  
  Student s2=new Student();  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  s1.displayInformation();  
  s2.displayInformation();  
 }  
} 

Output:

111 Karan
222 Aryan
Object in Java with values

As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.


3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later .https://vikiviews.wordpress.com/2024/03/07/all-about-java-constructors/


Object and Class Example: Employee

Let’s see an example where we are maintaining records of employees.

class Employee{  
    int id;  
    String name;  
    float salary;  
    void insert(int i, String n, float s) {  
        id=i;  
        name=n;  
        salary=s;  
    }  
    void display(){System.out.println(id+" "+name+" "+salary);}  
}  
public class TestEmployee {  
public static void main(String[] args) {  
    Employee e1=new Employee();  
    Employee e2=new Employee();  
    Employee e3=new Employee();  
    e1.insert(101,"ajeet",45000);  
    e2.insert(102,"irfan",25000);  
    e3.insert(103,"nakul",55000);  
    e1.display();  
    e2.display();  
    e3.display();  
}  
}

Output:

101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

class Rectangle{  
 int length;  
 int width;  
 void insert(int l, int w){  
  length=l;  
  width=w;  
 }  
 void calculateArea(){System.out.println(length*width);}  
}  
class TestRectangle1{  
 public static void main(String args[]){  
  Rectangle r1=new Rectangle();  
  Rectangle r2=new Rectangle();  
  r1.insert(11,5);  
  r2.insert(3,15);  
  r1.calculateArea();  
  r2.calculateArea();  
}  
}  

Output:

55 
45

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

  • By new keyword
  • By newInstance() method
  • By clone() method
  • By deserialization
  • By factory method etc.

We will learn these ways to create object later.

Different Ways to create an Object in Java

Anonymous object

Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.

ADVERTISEMENT

If you have to use an object only once, an anonymous object is a good approach. For example:

  1. newΒ Calculation();//anonymousΒ objectΒ Β 

Calling method through a reference:

  1. CalculationΒ c=newΒ Calculation();Β Β 
  2. c.fact(5);Β Β 

Calling method through an anonymous object

  1. newΒ Calculation().fact(5);Β Β 

Let’s see the full example of an anonymous object in Java.

class Calculation{  
 void fact(int  n){  
  int fact=1;  
  for(int i=1;i<=n;i++){  
   fact=fact*i;  
  }  
 System.out.println("factorial is "+fact);  
}  
public static void main(String args[]){  
 new Calculation().fact(5);//calling method with anonymous object  
}  
}  

Output:

Factorial is 120

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

  1. intΒ a=10,Β b=20;Β Β 

Initialization of refernce variables:

  1. RectangleΒ r1=newΒ Rectangle(),Β r2=newΒ Rectangle();//creatingΒ twoΒ objectsΒ Β 

Let’s see the example:Β 

//Java Program to illustrate the use of Rectangle class which  
//has length and width data members  
class Rectangle{  
 int length;  
 int width;  
 void insert(int l,int w){  
  length=l;  
  width=w;  
 }  
 void calculateArea(){System.out.println(length*width);}  
}  
class TestRectangle2{  
 public static void main(String args[]){  
  Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
  r1.insert(11,5);  
  r2.insert(3,15);  
  r1.calculateArea();  
  r2.calculateArea();  
}  
} 

Output:

55 
45     

Real World Example: Account

//Java Program to demonstrate the working of a banking-system  
//where we deposit and withdraw amount from our account.  
//Creating an Account class which has deposit() and withdraw() methods  
class Account{  
int acc_no;  
String name;  
float amount;  
//Method to initialize object  
void insert(int a,String n,float amt){  
acc_no=a;  
name=n;  
amount=amt;  
}  
//deposit method  
void deposit(float amt){  
amount=amount+amt;  
System.out.println(amt+" deposited");  
}  
//withdraw method  
void withdraw(float amt){  
if(amount<amt){  
System.out.println("Insufficient Balance");  
}else{  
amount=amount-amt;  
System.out.println(amt+" withdrawn");  
}  
}  
//method to check the balance of the account  
void checkBalance(){System.out.println("Balance is: "+amount);}  
//method to display the values of an object  
void display(){System.out.println(acc_no+" "+name+" "+amount);}  
}  
//Creating a test class to deposit and withdraw amount  
class TestAccount{  
public static void main(String[] args){  
Account a1=new Account();  
a1.insert(832345,"Ankit",1000);  
a1.display();  
a1.checkBalance();  
a1.deposit(40000);  
a1.checkBalance();  
a1.withdraw(15000);  
a1.checkBalance();  
}}   

Output:

832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

All about Java constructors

7 March 2024 at 07:26

InΒ Java, a constructor is a block of codes similar to the method. It is called when an instance of theΒ classΒ is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.PauseNextUnmute

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note:Β It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type
  3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can useΒ access modifiersΒ while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default constructor in Java.

Types of Java constructors

There are two types of constructors in Java:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
Java Constructors

Java Default Constructor

A constructor is called β€œDefault Constructor” when it doesn’t have any parameter.

Syntax of default constructor:

  1. <class_name>(){}Β Β 

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.




public class Students
{
public Students(){System.out.println("student object was created")}
public static void main(String[] args)
{
Students student1 = new Students();
}
}

output:

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Java default constructor

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.

Example of default constructor that displays the default values

public class Students
{
int id;
String name;
public void display(){
System.out.println(name + id);
}

public static void main(String[] args)
{
Students student1 = new Students();
student1.display();

}
}

Output:

Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor. Default constructer are invisible.


Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.


public class Students
{
int mark1, mark2, mark3, mark4,mark5, mark6;
public Students(int mark1, int mark2, int mark3, int mark4, int mark5)
{ //Useful for initializing object specific values
this.mark1 = mark1;
}

public Students(int mark1, int mark2, int mark3, int mark4)
{ //Useful for initializing object specific values
this.mark1 = mark1;
}
public static void main(String[] args)
{
Students student1 = new Students(90,80,67,56,36);
System.out.println(student1.mark1);
Students student2 = new Students(60,80,67,56,36);
System.out.println(student2.mark1);

}
}

Output:


Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.

ConstructorΒ overloading in JavaΒ is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading

public class Customer
{
String custName;
int mobileNo1, mobileNo2;
String emailId1, emailId2; //null
String address1, address2;
int proof;

public Customer(String custName, int mobileNo1,int mobileNo2,String emailId1,String emailId2,int proof){

this.custName = custName;
this.mobileNo1 = mobileNo1;
this.mobileNo2 = mobileNo2;
this.emailId1 = emailId1;
this.emailId2 = emailId2;
this.proof =proof;

}


public Customer(String custName, int mobileNo1,String emailId1,int proof){

this.custName = custName;
this.mobileNo1 = mobileNo1;
this.mobileNo2 = mobileNo2;
this.emailId1 = emailId1;
this.emailId2 = emailId2;
this.proof =proof;

}

public static void main(String[] args)
{
Customer customer1 = new Customer("Rajesh",1234,"rajesh@rajesh.com",2344);


Customer customer2 = new Customer("Suresh",2233,3459,"suresh@suresh.com","suresh2@suresh.com",3456);


Bank clerk = new Bank();
clerk.open_Account(customer1);

clerk.open_Account(customer2);

}

}


public class Bank
{


public void open_Account(Customer cust1)
{
System.out.println(cust1.custName);
System.out.println(cust1.mobileNo1);

}


}

Output:


Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.

Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behavior of an object.
A constructor must not have a return type.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
The Java compiler provides a default constructor if you don’t have any constructor in a class.The method is not provided by the compiler in any case.
The constructor name must be same as the class name.The method name may or may not be same as the class name.
Java Constructors vs. Methods

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in Java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using Java constructor.

public class Customer
{
String custName;
int mobileNo1, mobileNo2;
String emailId1, emailId2; //null
String address1, address2;
int proof;

public Customer(String custName, int mobileNo1,int mobileNo2,String emailId1,String emailId2,int proof){

this.custName = custName;
this.mobileNo1 = mobileNo1;
this.mobileNo2 = mobileNo2;
this.emailId1 = emailId1;
this.emailId2 = emailId2;
this.proof =proof;

}


public Customer(Customer C1){

custName = C1.custName;
mobileNo1 = C1.mobileNo1;
mobileNo2 = C1.mobileNo2;
emailId1 = C1.emailId1;
emailId2 = C1.emailId2;
proof = C1.proof;

}

public static void main(String[] args)
{
Customer customer1 = new Customer("Suresh",2233,3459,"suresh@suresh.com","suresh2@suresh.com",3456);


Customer customer2 = new Customer(customer1);


Bank clerk = new Bank();
clerk.open_Account(customer1);

clerk.open_Account(customer2);

}

}

Output:


Copying values without constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

public class Customer
{
String custName;
int mobileNo1, mobileNo2;
String emailId1, emailId2; //null
String address1, address2;
int proof;

public Customer(String custName, int mobileNo1,int mobileNo2,String emailId1,String emailId2,int proof){

this.custName = custName;
this.mobileNo1 = mobileNo1;
this.mobileNo2 = mobileNo2;
this.emailId1 = emailId1;
this.emailId2 = emailId2;
this.proof =proof;

}


public Customer(){



}

public static void main(String[] args)
{
Customer customer1 = new Customer("Suresh",2233,3459,"suresh@suresh.com","suresh2@suresh.com",3456);


Customer customer2 = new Customer();

customer2.custName = customer1.custName;

customer2.mobileNo1 = customer1.mobileNo1;
customer2.mobileNo2 = customer1.mobileNo2;
customer2.emailId1 = customer1.emailId1;
customer2.emailId2 = customer1.emailId2;
customer2.proof = customer1.proof;



Bank clerk = new Bank();
clerk.open_Account(customer1);

clerk.open_Account(customer2);

}

}

Output:


Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use return type yet it returns a value).


Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.


Is there Constructor class in Java?

Yes.


What is the purpose of Constructor class?

Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect package.

References:

  1. https://www.javatpoint.com/java-constructor

EB_Bill calculator class: Practice for passing arguments to methods

7 March 2024 at 03:40

Above table represents Tamilnadu Electrivcity board bill chart. we can see they are fixing multiple limits and each limits have an associated value price for it. So our goal is to check all the condition and find the bill amount for the actual usage of electricity.

To approch this problem first let’s try to solve this problem step by step in simple english without using Java.

  1. we need to get the last reading and new reading from that we can electricity usage for a current period .(new_reading – last_reading).
  2. once we are able to calculate actual units for current time period then we need to calculate bill using above table.
    • There are two different way of calculation among them first one is when our consumed units is upto 500 units and second one is if out consumed units exceed the required 500 units.
    • if our consumed units are less then 500. we need to choose the first part of a chart where we need to check our consumed units falling under which section and calculate the respective bill with given price range.
    • if our consumed units are grater then 500. we need to choose the second part of a chart where we need to check our consumed units falling under which section and calculate the respective bill with given price range.

Now let’s see the implementation on code!

import java.util.Scanner;
public class EB_Reading
{
public static void main(String[] args)
{

EB_Reading assessor=new EB_Reading();
Scanner scan=new Scanner(System.in);

System.out.print("Enter New Reading  ");
int newReading=scan.nextInt();
System.out.print("Enter Old Reading  ");
int oldReading=scan.nextInt();

int consumed_units=assessor.reading(newReading,oldReading);
System.out.println("consumed units "+consumed_units);

assessor.calculate(consumed_units);

}
public int reading(int newReading,int oldReading)
{

return newReading-oldReading;

}
public void calculate(int units)
{
double result;
if (units<=500){
if (units<=100){
System.out.println("Payment value = 0");
  
}
else if(units>100 && units<=200){
result=(units-100)*2.25;
System.out.println("Payment value = "+ result);
}
else if(units>200 && units<=400){
result=100*2.25+(units-200)*4.50;
System.out.println("Payment value = "+ result);
}
else if(units>400 && units<=500){
result=100*2.25+200*4.50+(units-400)*6.00;
System.out.println("Payment value = "+ result);
}
}
if (units>500){
if (units<=100){
System.out.println("Payment value = 0");
}
else if(units>100 && units<=400){
result=(units-100)*4.50;
System.out.println("Payment value = "+ result);
}
else if(units>400 && units<=500){
result=300*4.50+(units-400)*6.00;
System.out.println("Payment value = "+ result);
}
else if(units>500 && units<=600){
result=300*4.50+100*6.00+(units-500)*8.00;
System.out.println("Payment value = "+ result);
}
else if(units>600 && units<=800){
result=300*4.50+100*6.00+100*8.00+(units-600)*9.00;
System.out.println("Payment value = "+ result);
}
else if(units>800 && units<=1000){
result=300*4.50+100*6.00+100*8.00+200*9.00+(units-800)*10.00;
System.out.println("Payment value = "+ result);
}
else if(units>=1000){
result=300*4.50+100*6.00+100*8.00+200*9.00+200*10.00+(units-1000)*11.00;
System.out.println("Payment value = "+ result);
}


}


}


}

I above code we have two methods called as reading and accessor respectively and they have their own responsibilty to do find the actaul reading for current elctricity bill calculate period and to calcula

to the bill respectively. so both of these method can be a part of same object. since reading method will returns units to calculate and we are passing that to calculate method.

In method if we are going to return something we need to mention the data type in method itself if we don’t want to return we can use void keyword in method definition.

React behind the scenes

4 March 2024 at 20:07

we write some code and we can see the results on our screen, have you ever think how these work behind the scenes?
This is also an important concept to understand from an interview perspective.

Before jumping into the explanation I would like to introduce some of the jargon that will be used to explain this topic and they are heavily used in both tutorials, docs, and interview

Jargon:-

  • Components
  • instance
  • react elements
  • DOM elements
  • virtual DOM
  • Reconciliation
  • Fiber tree
  • Diffing
  • Key Props
  • render phase
  • commit phase
  • Browser paint

To see what I am trying to explain you can always refer to the below diagram, which shows the different phases and their working

fig name: Main Diagram

Now, let’s deep dive into each of the phases to better understand the concepts :

Trigger & Render Phase:-

In React there are only two situations that trigger the render

  • Initial render of the application
  • The state is updated in one or more Component instances (re-render)

some key concept about render

  • The rendering process is triggered for the entire application.
  • it looks like React only re-renders the updated parts, but that’s not how React works behind it.
  • Render are not triggered immediately, they are scheduled for when the JS engine has some β€œfree time ” to execute them
  • There is also batching of multiple setState in event handlers (execute all in single bow by batching)

What after trigger?

There will be A new virtual DOM tree created.

component instances that triggered re-render β€” > React Elements β€” > New Virtual DOM tree

So now the question is What is a Virtual DOM tree?

Virtual DOM

The virtual DOM (VDOM) is a programming concept where an ideal, or β€œvirtual”, representation of a UI is kept in memory and synced with the β€œreal” DOM by a library such as ReactDOM.

  • It is also known as React element tree
  • Tree of all react elements created from all instances in the component tree
  • cheap and fast to create multiple trees, because at the end they are JS objects
  • Nothing to do with β€œShadow DOM ”

Key points:-
Rendering a component will cause all of its child components to be re-rendered as well ,NO matter if their prop changed or not. It is necessary because React doesn’t know whether children will be affected or not.

in the above picture, there is a state change in component , so all the children on the A will also re-render.

So creating new virtual dom always? always render all child components if parents state changes? does it sounds like what react is?

No, so here reconciliation comes into the picture.

Reconciliation

so there’s some question that comes to mind when we encounter the word Reconciliation

Q. what is reconciliation and why do we need it ?

ans: reconciliation is a process by which react decides which dom elements needed to be reflected in the latest state changes.

Q. why not update the entire DOM whenever the state changes somewhere in the app ?

ans: Because , that would be inefficient and wasteful

  • writting to the dom is (relatively ) slow.
  • usually only a small parts of the dom needs to be updated , so if we update whole it will be misuse of time & resources.

React reuses as much of the existing DOM as possible by using reconciliation.

There is something which comes handy when we talks about reconciliation i.e The Reconciler : Fiber

The Reconciler : Fiber tree

Fiber tree are interanal tree thats has a β€œfiber” for each component instance and DOM element

  • fiber are not re created on every Render , it simply mutate over and over in future reconciliation steps.
  • this makes fiber a perfect place for keeping track of things like
    – Current state of components
    – Props
    – Side Effects
    – used Hooks
    – Queue of Work , i.e
    1. updating states
    2. Performing side effects
    3. performing DOM updates and etc

Each first child of fiber tree has a link to its parent and all the other children then have a link to their previous siblings , i.e linked list type

fiber is also called units of work in react , and work can be done asynchronously like some of them are

  • Rendering process can be split into chunk , task can priorities , pause , throws away etc.
  • enables concurrence feater likes supense or transition
  • renders not block js engine

a diagram to show how it looks like

coming back to the reconciliation working , lets understand it through the diagram

here, modal , overlay ,h3 , button are in the current fiber tree but no longer in virtual dom then they are marked as DOM deletion.

but , the Vidoe component was re-rendered because it is a child of App, it actually didn’t change and so as a result of reconciliation the DOM will be updated in this call
once, this process is over all the dom mutation will be placed in a list called the list of effects which will be used in the commit phase to actually mutate the DOM .

So from the above, we understood how the updation of DOM happens

Now if you reference to the main diagram all the above of this post

there is two-phase more to cover

Commit phase and Browser Paint

in [2] render phase we get the list of DOM updates, React does not touch the DOM , React only renders. it doesn’t know where the render result will go .

keep in mind render never mean rendering the changes on screen .

In the commit phase there in one another library that is used to commit.

they are called renderers

for example :-

  • ReactDOM
  • react native
  • Remotion etc

Renderers do not render, they commit the result of the render phase …

  • React writes to the dom : insertion , deletion and updates (list of dom are flushed to the dom )
  • committing is Synchronous: DOM is updated in one go , it cant be interrupted. this is necessary so that the dom never shows partial results , ensuring a consistent UI (in sync with state at all times)
  • After the commit phase completes , the works-in-progress fiber tree becomes the current tree for the next render cycle.

after this, the browser paints the changes on the screen.
(painting to the screen is also itself a vast topic to deep dive , i will cover that later ).

hope you get some insight from this post, please follow and share this reading and suggest to me if I need to improve on any part.

understading scopes of the variable and static keyword

4 March 2024 at 06:47

To Demostrate the use of local and global scope variables let’s create Exam class as example. In that class I have one global variable for named mark. Also I have two methods write and publish results. write method will take one parameter known as mark. which will be in local scope of that method. so local scope means it will be generated and destroyed within particular scope(in certain action or method).

How to refer a variable in different places?

If I am going to use some variables inside of static methods I need to specify object name and then the variable name(Ex: Sweatha.marks). because static method will not aware about which objects memory we are refering to because of it’s class specific nature.

But Incase of non static methos we don’t need to specify the object name because those methods are always coupled with each individual objects . so no need to to explicitly mention the object name.

public class Exams{
int mark;
static int min_pass = 35;
static int max_pass = 100;
public static void main(String[] args){
Exams swetha = new Exams();
Exams sivasree = new Exams();

swetha.mark = 95;
sivasree.mark = 92;

System.out.println("global marks 1: " +swetha.mark);
swetha.write(87);
sivasree.write(89);
swetha.publish_result();
System.out.println("global marks 2: " +swetha.mark);
}

public void write(int mark ){
System.out.println("this " + this.mark);
System.out.println("writing Exams");
System.out.println(min_pass);
System.out.println(max_pass);
this.mark = mark;

}

public void publish_result()
{
System.out.println("Publishing "+mark);
}

}

Static vs Non-Static use cases

In above program we have two static varibles min_pass and max_pass. since passing marks are similar to all students(objects) we can make it as the static variable. so that variable will stored in class memory(only one copy). if we don’t make it as static variable it becomes specific to object and each object will store it in it’s own memory. By using static keyword for the variable common amoung all instances we can save some memory. same logic will applies to the static methods as well. so If I use any not static variables inside the static method we will get an error because static method don’t have idea about static avariables and methods.Inorder to use static methods and variables we need bring it out of object by using dot notaion(Ex.swetha.mark)

Manupulating Global variable inside the methods

In above program we have varable named Marks in two place one thing in global scope(out of methods) and another on is in local scope of the method. if I apply any operation on that variable inside method it will not affect gloable variables value in any way. Bacause Java will understand those two variables as different one and they both have different memory. Incase we need to manipulate the global scope variable from method we can use this method to achechive it.(Ex:this.mark = mark;). usually this method will used to refer the object name. since static method is not specifc to object we can’t use this method in static method.

public class Tourist{
int amount = 10000;

public static void main(String[] args){

Tourist vignesh = new Tourist();
vignesh.roam(200);
System.out.println(this.amount);


}
public void roam(int amount){
//amount = 200;
System.out.println("local field : "+amount);
System.out.println("this : " + this.amount);
}

}

In above example i used this method inside the static methods and while comiling that proram Java throws an error with a message `non-static variable this cannot be referenced a static context`.

public class Tourist{
int amount = 10000;
static String test = "test";

public static void main(String[] args){

Tourist vignesh = new Tourist();
vignesh.roam(200);
System.out.println(vignesh.amount);
System.out.println(test);



}
public void roam(int amount){
//amount = 200;
System.out.println("local field : "+amount);
System.out.println("this : " + this.amount);
}

}

In above example I just replaced this method(System.out.println(this.amount) ) with System.out.println(vignesh.amount) and added test variable in global scope (static String test = β€œtest”) in main method and printed it inside static main method using System.out.println(test); so output of that program is witnessing that static method is class specifc and If we want to use any non static variables inside it we need to create an object and from that object we can refer to it.in other case for test variable we don’t need to use any object name to use the value associated with test variable.

References:

Theater class – understanding objects

3 March 2024 at 18:50
  1. Create a class Called Theatre.
  2. Declare below global variables in it.
    2.1. String movieName
    2.2. int movie_time
  3. Add main method
  4. Inside main method, create two instances (objects),
    4.1 movie1
    4.2 movie2
  5. For instance movie1, add β€˜Jailer’ as movieName and 630 as movie_time
  6. For instance movie2, add β€˜Leo’ as movieName and 7 as movie_time
  7. Create and define a method as below.
    public void watch_movie()
    {
    System.out.println(β€œWatching ” + movieName);
    System.out.println(β€œShow Time is ” +movie_time);
    }
  8. Call above method using both the instances – movie1, movie2.
  9. Go through and record your observations.
public class Theatre {
String movieName;
int movie_time;

public static void main(String[] args) {
// Creating two instances of Theatre class
Theatre movie1 = new Theatre();
Theatre movie2 = new Theatre();

// Adding movie details for movie1
movie1.movieName = "Jailer";
movie1.movie_time = 630;

// Adding movie details for movie2
movie2.movieName = "Leo";
movie2.movie_time = 7;

// Calling watch_movie method for movie1
movie1.watch_movie();

// Calling watch_movie method for movie2
movie2.watch_movie();
}

// Method to watch the movie
public void watch_movie() {
System.out.println("Watching " + movieName);
System.out.println("Show Time is " + movie_time);
}
}
  1. public class Theatre {: This line starts the declaration of a new Java class named Theatre. Classes in Java are used to encapsulate data and methods.
  2. String movieName; and int movie_time;: These are instance variables of the class Theatre. They are declared without any initial values, which means they will be initialized to their default values (null for String and 0 for int).
  3. public static void main(String[] args) {: This line defines the entry point of the Java program, the main method. It is a static method, which means it belongs to the class itself rather than any specific instance of the class. It takes an array of strings (args) as input parameters.
  4. Theatre movie1 = new Theatre(); and Theatre movie2 = new Theatre();: These lines create two instances (objects) of the Theatre class named movie1 and movie2, respectively. The new keyword is used to allocate memory for these objects.
  5. movie1.movieName = "Jailer"; and movie1.movie_time = 630;: These lines assign values to the movieName and movie_time instance variables of the movie1 object.
  6. movie2.movieName = "Leo"; and movie2.movie_time = 7;: These lines assign values to the movieName and movie_time instance variables of the movie2 object.
  7. public void watch_movie() {: This line defines a method named watch_movie() inside the Theatre class. It is a non-static method (instance method) because it does not have the static keyword. It does not return any value (void) and does not take any parameters.
  8. System.out.println("Watching " + movieName);: This line prints the value of the movieName instance variable for the current object.
  9. System.out.println("Show Time is " + movie_time);: This line prints the value of the movie_time instance variable for the current object.
  10. movie1.watch_movie(); and movie2.watch_movie();: These lines call the watch_movie() method for the movie1 and movie2 objects, respectively. This will execute the code inside the watch_movie() method for each object, printing the movie details.

Concepts covered:

  • Class and object: The Theatre class represents a blueprint for creating objects that represent theaters. movie1 and movie2 are instances (objects) of this class.
  • Instance variables: movieName and movie_time are instance variables of the Theatre class, representing the name and show time of a movie, respectively.
  • Methods: The watch_movie() method is defined to display the movie details.
  • Object instantiation: The new keyword is used to create new instances of the Theatre class.
  • Accessing instance variables and methods: Instance variables and methods are accessed using the dot (.) operator on object references (movie1 and movie2).
  • Printing output: The System.out.println() method is used to print output to the console.

The Java Time Travellor -No more past tense

3 March 2024 at 13:05

So this is the Hypothetical program that allows a person to the travel to the year that he want to go in past.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.nio.charset.StandardCharsets;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.io.BufferedWriter;

public class TimeTraveler {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the desired year
System.out.println("Welcome, Time Traveler! Please enter the year you want to travel to:");
int desiredYear = scanner.nextInt();

// Create an instance of the TimeMachine class
TimeMachine timeMachine = new TimeMachine();

// Retrieve the event for the specified year
String event = timeMachine.getEventForDate(desiredYear);

// Check if the event is not empty
if (!event.isEmpty()) {
// Print a message indicating the year the user has arrived in
System.out.println("You've arrived in the year " + desiredYear + ".");
// Print a message indicating the significant event for the specified year
System.out.println("Here's a significant event that happened in " + desiredYear + ":");
// Print the retrieved event
System.out.println(event);

// Write the event to a file
writeToFile(event, "event_" + desiredYear + ".txt");
// Print a message indicating that the event details have been written to the file
System.out.println("Event details written to file.");
} else {
// If no event is found for the specified year, print a message indicating so
System.out.println("Sorry, no significant event found for the year " + desiredYear + ".");
}
}

// Method to write the content to a file
private static void writeToFile(String content, String filename) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename, StandardCharsets.UTF_8))) {
writer.write(content);
} catch (IOException e) {
// If an IOException occurs during file writing, print the stack trace
e.printStackTrace();
}
}
}

// Class for fetching event details for a given year
class TimeMachine {
public String getEventForDate(int year) {
// Construct the URL for the Wikipedia page for the specified year
String url = "https://en.wikipedia.org/wiki/"+ year +"_in_India";
StringBuilder event = new StringBuilder();

try {
// Connect to the Wikipedia page and retrieve its HTML document
Document doc = Jsoup.connect(url).get();
// Select the body element of the HTML document
Elements paragraphs = doc.select("body");
// Iterate over paragraphs in the body element
for (Element paragraph : paragraphs) {
// Consider the first non-empty paragraph as the event
String text = paragraph.text().trim();
if (!text.isEmpty()) {
event.append(text).append("\n\n");
break;
}
}
} catch (IOException e) {
// If an IOException occurs during web scraping, print the stack trace
e.printStackTrace();
}

// Return the retrieved event as a string
return event.toString().trim();
}
}

output:

  1. TimeTraveler: This class contains the main method, which serves as the entry point of the program. It prompts the user to enter a desired year, retrieves the significant event for that year using the TimeMachine class, prints the event to the console, and writes it to a file.
  2. TimeMachine: This class is responsible for fetching the significant event for a given year from the Wikipedia page. It utilizes Jsoup for web scraping to retrieve the HTML content of the Wikipedia page, selects the relevant text, and returns it as a string.

The writeToFile method in the TimeTraveler class is used to write the event details to a file with the specified filename. It utilizes a BufferedWriter to write the content to the file with UTF-8 encoding. If an IOException occurs during file writing, the stack trace is printed to the console.

❌
❌