Blogs  

What are Comments in Java– Know its Types

Introduction

Comments in Java are statements used to explain a piece of code and are non-executable. They help improve the readability of the code and assist developers in understanding its functionality. Properly commented code enhances maintainability and makes collaboration easier. Java supports three types of comments: Single-line comments, Multi-line comments, and Documentation comments.

Types of Comments in Java

1. Single-Line Comments

Single-line comments begin with // and are used to describe a specific line of code. The text following // until the end of the line is ignored by the compiler.

Example:

import java.util.*; // Importing Scanner class

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to Java Programming");
        Scanner s = new Scanner(System.in); // Creating Scanner object for input
        int a = s.nextInt(); // Accepting integer input from user
        s.close(); // Closing Scanner object
    }
}

2. Multi-Line Comments

Multi-line comments start with /* and end with */. They are used to explain a section of code or a complex snippet that requires detailed explanations.

Example:

import java.util.*; // Importing Scanner class

public class Main {
    public static void main(String[] args) {
        System.out.println("Welcome to Java Programming");
        Scanner s = new Scanner(System.in);
        /*
         * Accepting an integer input from the user
         * and storing it in variable 'a'.
         */
        int a = s.nextInt();
        s.close(); // Closing Scanner object
    }
}

3. Documentation Comments

Documentation comments start with /** and end with */. They are used to generate API documentation using the javadoc tool. These comments describe methods, classes, and variables in detail, making them useful for large-scale applications.

Example:

/**
 * This program demonstrates the Hello World output.
 * @author  Java Developer
 * @version 1.0
 * @since   2024-02-28
 */
public class Main {
    
    /**
     * Main method to print "Hello World".
     * @param args Command-line arguments
     */
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Printing Hello World message
    }
}

Conclusion

Comments are essential in Java programming as they enhance code readability, provide explanations, and help in debugging. Using single-line, multi-line, and documentation comments effectively ensures that the code is understandable and maintainable over time.

Naresh I Technologies is the number one computer training institute in Hyderabad and among the top five computer training institutes in India. Contact us anytime for your Java training. You can also opt for Java online training, and from any part of the world. And a big package is waiting for you. And all is yours for a nominal fee affordable for all with any range of budget. Let us have a look at what you will get with this Java training package:

  • You need to pay a nominal fee.

  • You can choose any Java certification, as per your skills and interest.

  • You have the option to select from online and classroom training.

  • A chance to study at one of the best Java training institutes in India 

  • We provide Java training in Hyderabad and USA, and no matter in which part of the world you are, you can contact us.

  • Naresh I technologies cater to one of the best Java training in India.

  • And a lot more is waiting for you.

Contact us anytime for your complete Java online training.

What is Polymorphism in OOPs programming?

Polymorphism in OOPs Programming

Introduction: Polymorphism is an important concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different types, allowing flexibility and code reusability. With polymorphism, an object can exhibit different behaviors depending on the context in which it is used. Python, being a powerful and versatile language, supports polymorphism effortlessly through various mechanisms.

What is Polymorphism?

Polymorphism allows objects to be processed in multiple ways depending on their class. It can be defined as the ability of a function, object, or method to take multiple forms. In Python, polymorphism is implemented through function overloading, function overriding, and virtual functions.

Polymorphism in Python

Python, being an OOP-supported language, provides various ways to implement polymorphism. Some of the key techniques include:

  • Function Overloading

  • Method Overriding

  • Using Polymorphic Functions and Objects

  • Class Methods

  • Inheritance-based Polymorphism

Built-in Polymorphic Functions in Python

Python includes several built-in functions that exhibit polymorphism. For example, the len() function works on different data types:

# Using len() for a string
print(len("Hello Python"))  # Output: 12

# Using len() for a list
print(len([10, 20, 30]))  # Output: 3

User-defined Polymorphic Functions

Polymorphism can also be achieved using user-defined functions.

# Function demonstrating Polymorphism
def add(x, y, z=0):  
    return x + y + z  

# Driver code  
print(add(2, 3))  # Output: 5
print(add(2, 3, 4))  # Output: 9

Polymorphism with Functions and Objects

Polymorphism can be implemented by defining a function that can take any object as an argument.

class Tomato:
    def type(self):
        print("Vegetable")
    def color(self):
        print("Red")

class Apple:
    def type(self):
        print("Fruit")
    def color(self):
        print("Red")
      
def func(obj):
    obj.type()
    obj.color()

obj_tomato = Tomato()
obj_apple = Apple()
func(obj_tomato)  # Output: Vegetable, Red
func(obj_apple)   # Output: Fruit, Red

Polymorphism with Class Methods

Polymorphism can be achieved in Python by defining class methods that share the same name but belong to different classes.

class India:
    def capital(self):
        print("New Delhi is the capital of India.")
    def language(self):
        print("Hindi is the most widely spoken language of India.")
    def type(self):
        print("India is a developing country.")

obj_ind = India()
obj_ind.capital()  # Output: New Delhi is the capital of India.
obj_ind.language() # Output: Hindi is the most widely spoken language of India.
obj_ind.type()     # Output: India is a developing country.

Polymorphism with Inheritance

Inheritance-based polymorphism occurs when a child class overrides a method from its parent class.

class Bird:
    def intro(self):
        print("There are many types of birds.")
    def flight(self):
        print("Most birds can fly, but some cannot.")
    
class Sparrow(Bird):
    def flight(self):
        print("Sparrows can fly.")
    
class Ostrich(Bird):
    def flight(self):
        print("Ostriches cannot fly.")
    
obj_bird = Bird()
obj_spr = Sparrow()
obj_ost = Ostrich()

obj_bird.intro()
obj_bird.flight()  # Output: Most birds can fly, but some cannot.

obj_spr.intro()
obj_spr.flight()   # Output: Sparrows can fly.

obj_ost.intro()
obj_ost.flight()   # Output: Ostriches cannot fly.

Conclusion

Polymorphism is a key concept in object-oriented programming that allows for flexibility, scalability, and code reusability. Python provides built-in polymorphic functions and allows users to implement polymorphism using function overloading, method overriding, and inheritance. Understanding and effectively using polymorphism can enhance the structure and efficiency of your Python programs.

Scope @ NareshIT

At NareshIT’s Python Application Development program, you will receive extensive hands-on training in front-end, middleware, and back-end technologies. Our curriculum includes real-world projects, industry insights, and expert-led training to ensure relevance and job readiness.

How To Implement Round Function In Python

Introduction :

Python is a powerful programming language that offers excellent tools for data processing, scientific analysis, and complex modeling. One of the built-in functions in Python is round(), which returns a rounded float number. If no decimal places are specified, the function rounds the number to the nearest integer.

Python round() Function As mentioned earlier, the round() function in Python is used to round decimal values to a specified number of decimal places. If the number of decimal places is not provided, the function rounds the number to the nearest integer.

Syntax:

round(x, n)

Example:

print(round(7.6 + 8.7, 1))

Output:

16.3

Similarly, for another case:

print(round(6.543231, 2))

Output:

6.54

Practical Applications The round() function is often used to limit the number of decimal places in a given floating-point number. For example:

b = 2/6
print(b)
print(round(b, 2))

Output:

0.3333333333333333
0.33

Rounding NumPy Arrays NumPy provides additional rounding functions for handling large datasets. If you are using Python 3, NumPy is usually pre-installed. However, in Python 2, you need to install it manually:

pip install numpy

To round all values in a NumPy array, use np.around(). Example:

import numpy as np
np.random.seed(444)
data = np.random.randn(3, 4)
print(data)

Output:

[[ 0.35743992  0.3775384   1.38233789  1.17554883]
 [-0.9392757  -1.14315015 -0.54243951 -0.54870808]
 [ 0.20851975  0.21268956  1.26802054 -0.80730293]]

Other commonly used rounding functions in NumPy include:

print(np.ceil(data))  # Rounds up to the nearest integer
print(np.floor(data)) # Rounds down to the nearest integer
print(np.trunc(data)) # Truncates values to integer components
print(np.rint(data))  # Rounds to the nearest integer usin

Rounding Pandas Series and DataFrames Pandas is a widely used library for data analysis and manipulation. If you haven't installed it yet, use:

pip install pandas

Example using Pandas Series:

import pandas as pd
import numpy as np
np.random.seed(444)
series = pd.Series(np.random.randn(4))
print(series)
print(series.round(2))

Output:

0    0.357440
1    0.377538
2    1.382338
3    1.175549
dtype: float64

0    0.36
1    0.38
2    1.38
3    1.18
dtype: float64

A Pandas DataFrame is similar to a table in a database. You can round specific columns with different precisions using:

df.round({"Column 1": 1, "Column 2": 2, "Column 3": 3})

Example:

import pandas as pd
import numpy as np
np.random.seed(444)
df = pd.DataFrame(np.random.randn(3, 3), columns=["Column 1", "Column 2", "Column 3"])
print(df)
print(df.round(3))

Output:

   Column 1  Column 2  Column 3
0     0.4     0.38     1.382
1     1.2    -0.94    -1.143
2    -0.5    -0.55     0.209

Scope @ NareshIT At NareshIT’s Python Application Development Program, you will receive extensive hands-on training in front-end, middleware, and back-end technologies. The program includes phase-end and capstone projects based on real business scenarios.

Key benefits include:

  • Learning from industry experts with structured content ensuring industrial relevance.

  • Working on end-to-end applications with exciting features.

  • Gaining skills in NumPy, Pandas, and other essential Python libraries.

  • Training available for various Python certifications.

For more information, contact NareshIT for Python training through classroom or online sessions.