In this tutorial, we will write a program for method overriding and method overloading. Before that, you should have knowledge on the following topic in Java.
class Dog
{
public void display()
{
System.out.println("I am A Dog");
}
}
class breed extends Dog
{
public void display()
{
System.out.println("Breed: German Shepard");
}
}
public class Main
{
public static void main(String args[])
{
Dog d = new Dog(); // Animal reference and object
Dog b = new breed(); // Animal reference but Dog object
d.display(); // runs the method in Animal class
b.display(); // runs the method in Dog class
}
}
Outputmethod overriding:
I am A Dog Breed: German Shepard
Explanation: In the above example, we can see that ‘b‘ is a type of dog but still executes the display method in the breed class. In the runtime, JVM first looks at the object type and runs the method that belongs to that particular object.
Since the class Dog has the method display, the compiler will have no problem in compiling, and during runtime, the method specific for that particular object will run.
1. Method overloading by changing the data type of Arguments
class MethOverloadingTest
{
void add (int x, int y)
{
System.out.println("sum is "+(x+y)) ;
}
void add (double x, double y)
{
System.out.println("sum is "+(x+y));
}
}
public class Main
{
public static void main (String[] args)
{
MethOverloadingTest sum = new MethOverloadingTest();
sum.add (5,5); // method with int parameter is called.
sum.add (5.5, 5.5); //method with float parameter is called.
}
}
Output:
sum is 10 sum is 11.0
2. Method overloading by changing the number of the argument
class MethOverloadingTest2
{
void Info()
{
System.out.println("Argument List is empty") ;
}
void Info (String c, int id)
{
System.out.println("\nName:"+c+" Id:"+id);
}
void Info (String c, int id, int age)
{
System.out.println("\nName:"+c+" Id:"+id+" Age:"+age);
}
}
public class Main
{
public static void main (String[] args)
{
MethOverloadingTest2 sum = new MethOverloadingTest2();
sum.Info(); //method with empty parameter is called.
sum.Info ("Karan",1101); // method with two parameter is called.
sum.Info ("Prashant",1102,23); //method with three parameter is called.
}
}
C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of the .Net Framework. It is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.
This language is also used to develop Web Applications, apps, and also in game development.
The below points are the reason why C# is widely used in various platform:
It is a modern, general-purpose programming language.
It is easy to learn and easily understandable.
It is an object-oriented language.
It is a component-oriented and structured language.
It can be compiled on a variety of computer platforms.
It is a part of .Net Framework through which memory management becomes easy.
C# is used in almost all the developer fields such as developing applications, games and more.
Following is the list of few important features of C#:
Variables are like a storage unit that stores the values of various data-types present in a C# programming language. The types are different in C# and accordingly, the memory sizes are allocated to those types to store data values.
Consider an example where you have declared a variable of type int that means that the int variable will be allocated to a memory where it will integer values and some specific operation can be performed.
And for operation, consider the variable int that you described and since it is an integer the operation like addition and subtraction, multiplication, or modulus is performed on those integer operands.
C# consists of various types variables provided by its data-types:
int: It stores integers values such as 65 or -65.
double: It stores floating-point numbers such as 15.34 or -15.34.
char: It stores the character in a single-quotes such as ‘s‘.
string: It is for storing the string in double quotes such as “simple code“
bool: It states two values: true and false.
Like variables in C, C++, java or any other programming language, the variable is declared before use and can be modified at runtime within any section of the code depending upon its types.
Syntax:
data-type variable_name = value;
or
data-type variable_name;
How to declare variable in C#?
It is simple to declare a variable and it must be declared before the use of that variable. You need to specify the data-type for the variable and also give it a unique name.
//syntax
<data-types> <variable_name>;
As mentioned above data-types can be of any type: int, float, double, char, string or bool, according to the need.
Let us see an example how you can declare it in a program.
int number;
char ch;
double d;
float flt;
How to initialize a variable in C#?
Initialization means giving the variable an initial value to start with. We can initialize the variable at the declaration part such as: int number = 45;.
The syntax is simple, first, start with the data-types and unique name the same as a declaration and then assign it a value with equal sign ‘=’.
The data value is always assigned at the right-hand sign of the assignment operator ‘=‘. Let us see some valid examples of how you can initialize a variable.
int num1 = 45, num2 = 67;
double pi = 3.14159;
char ch = 's';
In the above example as you can see the first line contains two initialization which is possible considering you ant the two variable n you program to be an integer type.
User Inputs
Sometimes in a program you need to the value from the user and store it in a variable and use those variable at run time in a programs.
To accept the inputs from the user, C# provides a particular function named as ReadLine() that take the inputs and store it in a variable. It is present in the console class in the System.
How to use it in a program:
int number;
number = Convert.ToInt32(Console.ReadLine());
The above example specifies that the variable is declared and it takes the user input and places it in a number variable. Conversion of inputs to integer data-type is done by Convert.ToInt32 and acceptance of input is completed by Console.ReadLine() in the program.
C# defines two kinds of expressions:
lvalue: The expression may appear on either on the right-hand side or the left-hand side of the assignment operator.
rvalue: The expression can only appear on the right-hand side but not on the left-hand side of the assignment operator.
Variables are lvalue expression as it can appear on the right-hand side as well as on the left-hand side of an equal sign’=’ in a program. However numeric values are rvalues as it can only be assigned to the right-hand side of the ‘=’ value.
This is because the assignment operator(=) always assigns the right-hand side value to the left-hand side and we cannot assign something to a numeric value that is why they are the rvalue.
Look at the below example that shows which are valid and which are not.
There are few rules you need to follow which naming the variables such as it must be unique, it has to be letters, digits, or the underscore _. Variables are case sensitive that is Number and number are considered different variables.
As we know the variables holds the data and the type of data that it holds refers to the data-types. Theses types are: integer, float, double, boolean, etc. and each of this data-types has a specific size such as integer has the memory size of 4 byte and so on.
Now, C# has categorized its data-types in three different parts:
Value types: int, float, short, char, etc.
Reference types: String, Class, Object and Interface
Pointer types: simply Pointers
C# contains two general categories of built-in data types: value types and reference types.
The difference between the two types is what a variable contains.
For a value type, a variable holds an actual value, such 3.1416 or 212.
For a reference type, a variable holds a reference to the value.
Let us discuss each of them:
1. Value types
Value types are derived from the class System.ValueType. They refer to the direct value used in the program such as integers, float, double and more. These data-types are both integer-based and floating-point types. Memory allocates for the memory space whenever some value type is assigned.
Value types are of two types, Predefined Data Types (Integer, Boolean, etc) and User-defined Data Types (Structure, Enumerations, etc).
Follow the table below for the value type list in C#:
Data Types
Memory Size
Range
int
4 byte
-2,147,483,648 to -2,147,483,647
float
4 byte
1.5 * 10-45 – 3.4 * 1038, 7-digit precision
short
2 byte
-32,768 to 32,767
char
1 byte
-128 to 127
long
8 byte
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
double
8 byte
5.0 * 10-324 – 1.7 * 10308, 15-digit precision
signed short
2 byte
-32,768 to 32,767
unsigned short
2 byte
0 to 65,535
signed int
4 byte
-2,147,483,648 to -2,147,483,647
unsigned int
4 byte
0 to 4,294,967,295
signed long
8 byte
?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long
8 byte
0 – 18,446,744,073,709,551,615
decimal
16 byte
at least -7.9 * 10?28 – 7.9 * 1028, with at least 28-digit precision
Memory size changes according to the Operating System.
2. Reference Types
Reference types are a bit different than Value Types, this kind of data-types do not contain the actual data stored in a variable, but they contain a reference to the variables.
Reference types specify to the memory location and if the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value.
They are also of two types, Predefined Data Types (Objects, String and Dynamic) and User-defined Data Types (Classes, Interface).
3. Pointer Type
It is also known as the indicator as it points to the address of a value. Pointer type variables store the memory address of another type. The abilities to do the task is same as the pointers that we use in C or C++.
Literals refer to fixed values that are represented in their human-readable form. For the most part, literals and their usage are so intuitive that they have been used in one form or another by all the preceding sample programs.
For example, the number 100 is a literal.
C# literals can be of any simple type. The way each literal is represented depends upon its type.
To specify a float literal, append an F or f to the constant. For example, 10.19F is of type float.
To specify a decimal literal, follow its value with an m or M. For example, 9.95M is a decimal literal.
Literals can be any of the following types that can be used in a program:
Integer Literals
Floating-point Literals
Character Literals
String Literals
Null Literals
Boolean Literals
Integer Literals
An integer literal can be decimal(base 10) or hexadecimal(base 16) constant or Octal(base 8). A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
For unsigned and signed, the suffix U and L are used. And the only rule is you can represent these suffix either in uppercase or the lower case and in any order you may prefer.
Example of integer literals:
20 // simply int
30u // u for unsigned int
30L // l for long
Floating-Point Literals
Literals is called the floating-point literals if it has the following part:
an integer part
a decimal point
a fractional part
an exponent part
We can constitute them in decimal or exponential form. Representation of decimal form required the decimal point or the exponent or the both while the exponential form required the integer part or the fractional part or both.
By default, the floating-point literals are of double type and assigning it directly to a float variable is not possible. Instead, we can use the suffix for a float that is I or F.
Some example to show how can it be used and how it can’t be used in a program:
Character literals are those literals that are enclosed within the single quote(‘ ‘) such as ‘S’ is stored as a character. we can represent the character literals in several ways:
Single quote: These are the plain character enclosed within a single quote. Eg: char c = 'S';
Unicode Representation: These are the universal character denoted in Unicode such as char c = '\u0061'; //this Unicode value represents a character.
Escape Sequence: This is also a character literal that can be used as a character such as char c = '\t';
The following table shows some escape sequence that are used in a program with their meaning. Go through them carefully.
Escape sequence
Meaning
\\
\ character
\’
‘ character
\”
” character
\?
? character
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\xhh . . .
Hexadecimal number of one or more digits
String Literals
This type of literals is enclosed within double-quotes (“”) or with @””. A string also enclosed the same character as the character literal does such as plain character, universal characters and more.
The below example show how the string literals are represented in a program.
This literal has only two values that show the result and they are true and false. You can assign the value at the beginning while declaring the boo as shown in an example below.
In this article, we learn all about JVM and its architecture and also we will compare JDK, JRE, and JVM with important points required.
What is JVM?
JVM stands for Java Virtual Machine, which is an abstract machine that provides a run-time environment to run Java programs. It converts Java byte-code into machine language, so not only Java but it also enables the computer to run other programs that are compiled to byte-code.
JVM is a part of the JRE(Java Run Environment). However, the reason for the Java program is executed by the JVM helps to solve the major problems related to web-based programs and also to make it secure.
JVM working process can be explained in the following manner:
It first loads byte-code.
then verifies the byte-code.
Then executes byte-code providing runtime environment.
JVM Architecture:
1. ClassLoader subsystem:
This subsystem is used for loading class files. It performs three major functions :
Loading, Linking, and Initialization.
There are three built-in classloaders in Java.
Bootstrap ClassLoader: It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes.
Extension ClassLoader: It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System ClassLoader: It loads the class files from the classpath. Also known as Application classloader.
2. JVM Memory:
Method Area: In the method area, structures like the run-time constant pool, field and method data, variables information, static variables, etc. are stored.
Heap: It is a shared resource among all the threads and created during run-time. All the Objects, metadata, and arrays are stored in the heap.
JVM language Stacks: Java language Stacks stores parameters, local variables, and return addresses during method calls. It is not a shared resource. One JVM stack is created simultaneously for each thread that is each thread contains its own JVM stack.
PC Registers: PC(Program Counter) Register contains/stores the address of JVM(Java Virtual Machine) instruction that is being currently executed. Each thread in Java has its own PC register.
Native Method Stacks: Every thread has its own separate native stack hold the native method information.
3. Execution Engine:
The execution engine executes the bytecode, reading it line by line.
It contains three parts:
Interpreter: The work of the interpreter is to read the byte-code line by line and then execute it.
Just-In-Time Compiler(JIT): It is used to increase the performance of the compiler by taking the block of similar byte-code that is the repeated method calls. Hence reducing the compilation time and making it more efficient.
Garbage Collector: It is used to destroy the useless objects or objects that are no longer required.
4. Java Native Interface (JNI):
It provides the native libraries required for the execution of a program. It allows the JVM to call other Libraries like C, C++, Assembly, etc., providing the interface to interact with other Native Application.
5. Native Method Libraries:
This is a collection of the Native Libraries(C, C++) which are required by the Execution Engine. These are the “native” codes, that is, the code that is compiled for a specific hardware architecture or operating systems such as X86 or windows.
In this tutorial, we will write a C# program to find the length of an array entered by the user, we have used while loop and try–catch block for the exception
Question: Write a C# program to find the length of an Array.
Solution: Here first we take the arrays from the user and to exit from an array user need to enter –999 at last. -999 is an exit value that is defined at the beginning of the program.
To take the user input, while loop is used inside which try-and catch blocks are executed. lastly array.Length is used to get how many elements the user entered.
C# Program to find the length of an Array.
It can also be done without the use of try-catch block
Source Code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] arg)
{
//CONSTANT VALUE TO EXIT
const int EXIT_VALUE = -999;
List<int> numbers = new List<int> ();
Console.WriteLine("Enter the number and press -999 at the end:");
while (true)
{
try
{
var input = Console.ReadLine();
int i = int.Parse(input);
if (i == EXIT_VALUE) break;
numbers.Add(i);
}
catch (System.Exception ex)
{
Console.WriteLine("Invalid Input!!");
}
}
int[] array = numbers.ToArray();
Console.WriteLine("Length of an Array is:{0}", array.Length);
}
}
This post shows, How to remove all vowels from a string in java? with the help of replaceAll() method.
Remove vowels from a string in java:
Explanation: Removing vowels in java is easy, we will take the user input with the help of a Scanner class. we will use replaceAll() which takes in two parameters, one is the string to be replaced and another one is the string to be replaced with.
Also, the vowels are “aeiou” so we replace those vowel letters by an empty string (“”) for both uppercase and lowercase vowel letters. Then print the result string without vowels.
Java Program to Remove all the Vowels from a String.
import java.util.Scanner;
public class RemoveVowel
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//user input
System.out.println("Enter the string:");
String inputStr = sc.nextLine();
String resultStr = inputStr.replaceAll("[AEIOUaeiou]", "");
System.out.println("Result String without vowels:");
System.out.println(resultStr);
sc.close();
}
}
The output of removing vowels from a string in java: