Normal view

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

String class methods java

15 August 2024 at 02:30
Java provides a variety of methods for manipulating and working with strings through the String class. Here’s a rundown of some of the most commonly used methods: Basic Methods Case Conversion Trimming and Padding Searching and Replacing Splitting and Joining Comparison Utility Methods These methods cover a wide range of string manipulation needs in Java. […]

ArrayList

14 August 2024 at 02:30
ArrayList is a part of Java’s java.util package and provides a dynamic array capable of growing as needed. Here are some commonly used methods in ArrayList: Adding Elements Accessing Elements Removing Elements Size and Capacity Searching and Checking Other Operations Iteration These methods provide a comprehensive set of operations for manipulating and accessing elements in […]

Interface types in Java

12 August 2024 at 02:49
java programming language an interface is a reference type, similar to a class, that can contain only constants, method declaration(method signature, nobody), default methods, static methods and nested types inside its body. Nested type simply means it can contain another interface or class inside it. variables declared in an interface are public, static & final […]

Collections Introduction in Java

8 August 2024 at 11:33
A Collection represents a single unit of objects What is a framework in Java What Is a Collections Framework? A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following: About Collection Benefits of the Java Collections Framework Hierarchy of Collection Framework Reference : https://docs.oracle.com/javase/tutorial/collections/intro/index.html Reference : https://www.javatpoint.com/collections-in-java

Tasks – Indexing & Slicing

22 July 2024 at 10:37
  1. Write a function that takes a string and returns a new string consisting of its first and last character.
  2. Write a function that reverses a given string.
  3. Given a string, extract and return a substring from the 3rd to the 8th character (inclusive).
  4. Write a function that returns every second character from a given string.
  5. Write a function that replaces the middle third of a string with asterisks. If the length of the string is not divisible by 3, adjust the middle third accordingly.
  6. Write a function that checks if a given string is a palindrome (reads the same backward as forward).
  7. Given an email address, extract and return the domain.
  8. Write a function that returns every third character from a given string.
  9. Write a function that extracts and returns characters at even indices from a given string.
  10. Write a function that skips every second character and then reverses the resulting string.

Read XML and Json File using JAVA Program

15 July 2024 at 02:54
open EclipseGo to File -> New -> Other….In the Select maven project and click next. On the New Maven Project page, you can leave the default options and click next On the Select an Archetype page, choose maven-archetype-quickstart from the list and click Next Enter the Group Id and Artifact Id for your project. For […]

My Alphabet & Numeric Pattern Programs in java

7 July 2024 at 10:25
My Name Pattern Numeric Patterns Numeric – 0 Output : Numeric – 1 Output : Numeric – 2 Output : Numeric – 3 Output : Numeric – 4 Output : Numeric – 5 Output : Numeric – 6 Output : Numeric – 7 Output : Numeric – 8 Output : Numeric – 9 Output : […]

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

❌
❌