Java Program to Add Two Numbers.

In this article, we are going to learn addition of two integer number in Java programming,  we will discuss two different approach of doing this one assigning value to variable and another by taking input value from the user. 


Java Program to Add Two Integer Number.

Step by steps approach:
  • Define a class called AddTwoNumbers.
  • Declare two integer variables num1 and num2 and initialize them to 5 and 7.
  • Calculate the sum of num1 and num2 and store it in an integer variable called sum.
  • Print out the sum using System.out.println().
  • The output should be "The sum of 5 and 7 is 12".
Java Code:
//Java code to add two int number
public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;
        int sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
    }
}
Output:
The sum of 5 and 7 is 12

Java Program to Add Two Numbers Taking Input from User.

Here is the another approach of doing the same program in which we are taking two integer value as an input from the user and then printing the sum of those two value as an output.

Java Code:
//Java program to add two number from user
import java.util.Scanner;

public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();
        int sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
        scanner.close();
    }
}
Output:
Enter the first number: 5
Enter the second number: 10
The sum of 5 and 10 is 15

Hello World Program in Java.

"Hello World" program is the most basic program that is used to introduce any new Programming Language to a newbie. This program basically prints a "Hello World" message on your console screen.

In this article, we are going to understand the working of the "Hello World" program in Java. 

Java Program:
// Java First Program

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

In the above code, the first line of code defined a new class called HelloWorld because in Java all code must be contained within classes, so this is the starting point of our program.

The next line public static void main(String[] args) defines a main method within the HelloWorld class. The main method is the entry point for the program and is the first method that is called when the program is run. It takes an array of String objects called args as a parameter.

The next line System.out.println("Hello, world!"); to print the message "Hello, world!" to the console. The println method adds a new line character after the message, so the next line of output will start on a new line.

How To Take Input from User in Java?

Java programming has various I/O packages to perform Input-Output operations. Unlike other programming languages, taking input from users is a little difficult in Java. 


There are multiple ways to take all different kinds of input from the user or from a file. These are:

  • Scanner Class.
  • BufferedReader Class.
  • Console Class.

1. Scanner Class.
We use the Scanner class to take input from the user through the command line. It has predefined functions to take different data types as input like integer, character, float, double, etc. 

Syntax:
We need to import the Scanner class to use the Scanner function.
  • import java.util.Scanner;
We need to create a new Scanner object called Scanner.
  • Scanner scan = new Scanner(System.in);

Example Code Implementation:

//Java program to take input from user using Scanner class
import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
Output:
Enter your name: Probin
Enter your age: 24
Hello, Probin. You are 24 years old.

In this example, we first import the Scanner class and create a new Scanner object called a scanner. We then use the System.out.print method to prompt the user to enter their name, and then use the nextLine method of the Scanner class to read in the input as a string.

We then do the same thing for the user's age, using the nextInt method to read in the input as an integer.

Java Scanner Class Methods List.

Method Description
next() It is used to read the next token (word) from the input as a String.
nextLine() It is used to read the next line of input as a String.
nextInt() It is used to read the next token (integer) from the input as an int.
nextDouble() It is used to read the next token (a floating-point number) from the input as a double.
nextFloat() It is used to read the next token of the input as a float.
nextByte() It is used to read the next token of the input as a byte.
hasNext() It returns true if there is another token in the input (i.e. the end of the input has not been reached).
hasNextLine() It returns true if there is another line of input (i.e. the end of the input has not been reached).
useDelimiter(String pattern) It Sets the delimiter for the input to the specified regular expression pattern.

Note: The Scanner class can also be used to read input from files or other sources, not just from the command line.

2. BufferedReader Class.

The BufferedReader class is a simple class that is used to read a sequence of characters. It is used to read the data line by line using the readLine() method. The BufferedReader class is faster and more efficient for reading a large amount of input. 

Example Code Implementation.
//Java code to take input from user using BufferedReader class
import java.io.*;

public class InputExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter your name: ");
        String name = reader.readLine();

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(reader.readLine());

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
Output:
Enter your name: Kumar
Enter your age: 24
Hello, Kumar. You are 24 years old.

In the above example, we are using the InputStreamReader() method that converts the input stream of bytes into a stream of characters.

3. Console class

Console class in Java is a built-in method for reading and writing text from the console. It is more secure for reading sensitive data like passwords without echoing them to the console.

List of some commonly used methods of console class:
Method Description
readLine() Reads a line of text from the console and returns it as a string.
readPassword() Reads a line of text from the console, but doesn't echo the characters to the screen.
printf(string format, Object... args) Writes formatted text to the console, similar to System.out.printf().
writer() Returns a PrintWriter object that can be used to write text to the console.

Example Code Implementation.
//Java code for taking user input using console class
import java.io.Console;

public class InputExample {
    public static void main(String[] args) {
        Console console = System.console();

        System.out.print("Enter your name: ");
        String name = console.readLine();

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(console.readLine());

        System.out.println("Hello, " + name + ". You are " + age + " years old.");
    }
}
Output:
Enter your name: Jhon
Enter your age: 18
Hello, Jhon. You are 18 years old.

Note: Consoles class is not available in all IDEs and web applications so in that case you can use either Sanner or BufferedReader class for reading input from the user.

Difference Between List and Tuple in Python with Example.

Difference Between List and Tuple

List and Tuple are the two most commonly used data structures in Python programming. They are used for storing objects of any type in python. In this article, we are going to discuss the difference between List and Tuple and their use cases with examples. 


What is a List in Python?

In Python, a list is a built-in data structure that represents an ordered collection of items or elements. It is a mutable sequence, which means you can change its content, and it can contain any type of data such as numbers, strings, or other objects. 

Example:

fruits = ['apple', 'banana', 'orange', 'kiwi']


What is a Tuple in Python?

A tuple is a built-in data structure that represents an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, which means that once a tuple is created, you cannot add, remove, or modify its elements.

Example:

my_tuple = (1, 'hello', 3.14)


Here is the important difference between List and Tuple:


1. Mutability: The list is mutable, which means you can add, remove or modify items after the list is created. On the other hand, tuples are immutable, which means that once the tuple is created, its content cannot be changed.

Example to show mutability of List and Tuple.

#creating a list and a tuple
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

#changing the first element of the list
my_list[0] = 4

#trying to change the first element of the tuple will result in an error
my_tuple[0] = 4

print(my_list) #output: [4, 2, 3]
print(my_tuple) #output: TypeError: 'tuple' object does not support item assignment
Output:

2. Speed: The list is dynamic in nature, whereas the tuple is static in nature, and because of this tuple is faster than the list.


3. Syntax: A list is defined using square brackets [] while a tuple is defined using parentheses ().


4. UsageLists are typically used for storing collections of items that can be changed throughout the program. Tuples, on the other hand, are generally used for storing collections of items that should not be changed during the program's execution, such as a set of coordinates or a date.

Example Code:

#creating a list of days in a week
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

#creating a tuple of coordinates
coordinates = (10.0, 20.0)

#trying to change an item in weekdays will work
weekdays[2] = 'Woden-day'

#trying to change an item in coordinates will result in an error
coordinates[0] = 20.0

print(weekdays) #output: ['Monday', 'Tuesday', 'Woden-day', 'Thursday', 'Friday']
print(coordinates) #output: TypeError: 'tuple' object does not support item assignment

In this example, we can see that we changed an item in the weekday list successfully but trying to change an item in the coordinates tuple resulted in a TypeError.

Difference Between List and Tuple.

Python List Python Tuple
Lists are Mutable in nature. Tuples are immutable in nature.
Square brackets [] are used to define the List Parentheses () are used to define Tuples.
Iteration over a List is time-consuming. Iteration over Tuple is faster.
Insertion and Deletion operations are performed better on List. Accessing an element of Tuple is more appropriate.
List Consume more memory. Tuple Consumes less memory.
The list has many built-in functions. Tuple has very few built-in functions.

Lists are typically used for collections of items that can be changed, while tuples are used for collections of items that should not be changed.

Function Overloading in C++ with Example.

Function Overloading in C++

Function Overloading is a feature of Object Oriented Programming in C++ that allows us to create multiple functions with the same name but different parameters. When the same function name is overloaded with different work in the same scope then it is called function overloading.


Function overloading is based on the concept of polymorphism, which allows a function to take on different forms based on its input or context. 

Example:

//example of function overloading
int fun(){}
int fun(int a, int b){}
float fun(double num){}

Function overloading is an important concept to understand because we use function overloading many times in real-life programming. There are a few important points that we need to keep in mind, let's discuss each of them with examples.

Overloading Function with Different Parameter Types.

Function overloading is used to provide different implementations of a function for different types of inputs. A function can be overloaded based on the number or types of parameters. The return type of a function cannot be used to differentiate between overloaded functions.

C++ Example code:
//Overloading Function with different types of parameters.
#include<iostream>
using namespace std;

//function with integer type parameter
int sum(int a, int b) {
   return a + b;
}
//function with float type parameter
float sum(float a, float b) {
   return a + b;
}

int main(){
   //function call
   cout << "Sum of two integers: " << sum(5, 10) << endl;
   cout << "Sum of two floats: " << sum(3.4f, 4.6f) << endl;
}
Output:
Sum of two integers: 15
Sum of two floats: 8

In the above code, we have used the same function name 'sum()' with the same number of parameters but in one function we have passed float type and in another, we have passed integer type parameters.  

Overloading Function with Different Number of Parameters.

The overloaded functions must have different parameter lists, either in terms of the number of parameters or their types. Function overloading is determined at compile-time based on the number and type of arguments passed to the function.

C++ Example code:
//Overloading Function with different number of parameters.
#include<iostream>
using namespace std;

//function with three integer parameters
int sum(int a, int b, int c) {
   return a + b + c;
}
//function with two integer parameters
int sum(int a, int b) {
   return a + b;
}
//function with two float parameters
float sum(float a, float b) {
   return a + b;
}

int main(){
   //function call
   cout << "Sum of three integers: " << sum(5, 10, 5) << endl;
   cout << "Sum of two integers: " << sum(12, 5) << endl;
   cout << "Sum of two floats: " << sum(3.5f, 4.5f) << endl;
}
Output:
Sum of three integers: 20
Sum of two integers: 17
Sum of two floats: 8

In the above code, we have used the same function name sum() with the same return type but passing a different number of parameters.

Conclusion:
Function overloading improves readability and reduces code duplication by providing a common function name to related functionality. It is also used to provide default values for parameters.

Read More:

100 Indian Company to Work as a Software Engineer.

Company to Work as a Software Engineer.

Software engineering is a popular field due to its high demand in the tech industry. Software engineers design, develop, and maintain software systems for various applications and platforms. The demand for software engineers has increased due to the rise of technology and digital transformation in almost every industry. They work with different programming languages, frameworks, and tools to create software that meets specific user requirements.


Moreover, software engineering is a field that offers various career paths and opportunities for growth, including web development, mobile app development, software testing, data science, and more. With the increasing demand for technology-based solutions, software engineers are in high demand, and the demand is expected to grow in the future. Additionally, software engineering also offers competitive salaries, job flexibility, and a dynamic work environment, which makes it a popular career choice for many individuals.


Here I am sharing the list of 100 India-based companies where you can work as a Software Developer.


Company Name
Tata Consultancy Services
Infosys
Wipro
HCL Technologies
Tech Mahindra
Cognizant Technology Solutions
L&T Infotech
Capgemini
Accenture
IBM India
Hike Messenger
Zoho Corporation
Mindtree
Mphasis
Persistent Systems
Cybage Software
Kony Labs
InMobi
Sapient
CGI
Geometric
Hexaware Technologies
Tally Solutions
Yodlee Infotech
KPMG
Deloitte India
PwC India
EY India
Techjini
NetApp
McAfee
Novell Software Development
Akamai Technologies
Intel India
Google India
Microsoft India
Adobe India
Oracle India
Amazon India
Apple India
Uber India
Ola Cabs
Swiggy
Flipkart
Myntra
MakeMyTrip
Cleartrip
RedBus
Goibibo
Practo
HealthifyMe
Portea Medical
Medlife
1mg Technologies
Citrus Pay
Paytm
FreeCharge
PhonePe
Razorpay
Quick Heal Technologies
NASSCOM
NSE IT
Bombay Stock Exchange
National Informatics Centre
Centre for Development of Advanced Computing
Indian Space Research Organisation
Bharat Heavy Electricals
Hindustan Aeronautics
Bharat Electronics
National Thermal Power Corporation
Indian Oil Corporation
Oil and Natural Gas Corporation
Tata Motors
Mahindra & Mahindra
Maruti Suzuki India
Bajaj Auto
Hero MotoCorp
TVS Motor Company
Hindustan Unilever
Nestle India
Pepsico India
Coca-Cola India
ITC Limited
Tata Steel
Steel Authority of India
Larsen & Toubro
Aditya Birla Group
Reliance Industries
Bharat Petroleum
Hindustan Petroleum
GAIL
Coal India
NTPC Limited
Power Grid Corporation of India
Indian Railways
Delhi Metro Rail Corporation
Mumbai Metro Rail Corporation
Bangalore Metro Rail Corporation
GMR Group
Adani Group


There are many more companies in which you can work as a software engineer, if you have more suggestions you can share them in the comment section below.

Python Program to Find nth Fibonacci Number.

Given an integer 'n', write a Python program to print the nth Fibonacci number. 

The nth Fibonacci number is defined as the sum of the (n-1)th and (n-2)th Fibonacci numbers, where the 0th and 1st Fibonacci numbers are 0 and 1, respectively.(alert-success)

Example:

Example 1:
Input: n = 6
Output: 8
Explanation: 0, 1, 1, 2, 5, 8
0+1 = 1
1+1 = 2
2+3 = 5
3+5 = 8

Example 2:
Input: 10
Output: 55

We can solve this problem using multiple approaches, let's discuss each of them one by one and understand which approach is best for us.

Find Fibonacci Number using Recursion.

Python code:
# function to print nth Fibonacci number
def fibonacci_recursive(n):
    if n == 0 or n == 1:
        return n
    return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# print value
print(fibonacci_recursive(10))
Output:
55
  • Time Complexity: O(2^n) - Exponential
  • Space Complexity: O(n) - Space required by the call stack of recursive calls


Find Fibonacci Number using Dynamic Programming.

In this approach, we use a list to store the Fibonacci numbers from 0 to n. We initialize the first two Fibonacci numbers (0 and 1) in the list, and then iterate over the remaining numbers from 2 to n, computing each Fibonacci number as the sum of the previous two numbers. Finally, we return the nth Fibonacci number from the list.

Python Code:
# Find Fibonacci number using Dynamic Programming
def fibonacci_dp(n):
    if n == 0 or n == 1:
        return n
    fib = [0, 1]
    for i in range(2, n+1):
        fib.append(fib[i-1] + fib[i-2])
    return fib[n]
# print output
print(fibonacci_dp(8))
Output:
21
  • Time Complexity: O(n) - Linear
  • Space Complexity: O(n) - Space required to store the list of Fibonacci numbers.


Fibonacci Number using Space-Optimized Dynamic Programming.

In this approach, we optimize the space complexity of the above dynamic programming approach by using only two variables to store the last two Fibonacci numbers. 

We initialize variables to 0 and 1, and then iterate over the remaining numbers from 2 to n, computing each Fibonacci number as the sum of the previous two numbers. After each iteration, we update the two variables to store the last two Fibonacci numbers. Finally, we return the last value of the second variable, which is the nth Fibonacci number.

Python Code:
# find fibonacci num space-optimized DP solution
def fibonacci_optimized(n):
    if n == 0 or n == 1:
        return n
    a, b = 0, 1
    for i in range(2, n+1):
        c = a + b
        a, b = b, c
    return b
#print output
print(fibonacci_optimized(10))
Output:
55
  • Time Complexity: O(n) - Linear
  • Space Complexity: O(1) - Constant space required to store only two variables (a and b)

Read More:

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson