History of Java: At first glance, it may appear that Java was developed specifically for the World Wide Web. However, interestingly enough, Java was developed independently of the web, and went through several stages of metamorphosis before reaching its current status of programming language for the World Wide Web. Below is a brief history of Java. [Read more…] about History of Java
What are the causes of exceptions in java
A java exception can be thrown only in the following three scenarios: [Read more…] about What are the causes of exceptions in java
What is an Applet?
We Know that java provides us the facility for both creating CUI and GUI Programs All the Previous Topics are Related with the CUI But Applets Provides the ability to user for creating Graphical Programs Like Creating Buttons, Creating Events such that Executing the Code when a user Clicks on Button Etc. There are two type of Applets Like Stand Alone or either Local Applets. [Read more…] about What is an Applet?
Exception Handling in Java with Examples
Exception handling in Java is a technique of processing problems that occur during the execution of the program. Using exception handling, we can test the code and avoid it from exiting abruptly.
Exception handling in Java is accomplished using five keywords: try, catch, throw, throws and finally.
To understand what exceptions are and how to handle them, let us consider a program that displays two integers’ quotient. [Read more…] about Exception Handling in Java with Examples
Exceptions – What is Exceptions? Type of Exceptions
Exceptions:- Exception is a condition Which is Responsible for Occurrence of Error Like Divide by Zero is an condition that never be possible So we can call it an Exception which halts or stops the Execution of Program In java there is an Exception Class Which is Responsible for producing an Error Message when an Error has occurred. [Read more…] about Exceptions – What is Exceptions? Type of Exceptions
Error – What is Error? Type of Error.
Many Times a Program has to face some errors An Error is an Situation when a Compiler either doesn’t Execute statements or either Compiler will Produce Wrong Result .Various types of Errors are there like :- [Read more…] about Error – What is Error? Type of Error.
Differences Between Applications and Applets
Java is a general-purpose, object-oriented programming language. We can develop two types of Java programs : [Read more…] about Differences Between Applications and Applets
Method Overloading in Java with Example
Method Overloading: When multiple methods in the same class with same name, having different functions or types of parameters, it is known as Method Overloading. When an overloaded method is invoked, it is the responsibility of the compiler to select the appropriate overloaded method based on the number of argument(s) passed and if the numbers of argument(s) are same then depending upon the type of argument(s) passed to the method. Thus, the key to method overloading is a method’s parameter list. A method’s return type is not enough to distinguish between two overloaded methods. If the compiler detects two methods declarations with the same name and parameter list but different return types then it will generate an error. [Read more…] about Method Overloading in Java with Example
Difference Between Call by Value and Call By reference in Java
In Java, there is no such thing as a call by reference, only a call by value. If a method that passes value called, we are calling by value and any change in the method called do not get affected in the method used to call. Where a call by value is used, there is no change to the original value. Have a look at the Example below:
class Operation {
int data = 50;
void change(int data) {
data = data+100;//changes will only be made in the local variable
}
public static void main(String args[]){
Operation op = newOperation();
System.out.println(“before change “+op.data);
op.change(500);
System.out.println(“after change “+op.data);
}
}
The output of this will be:
before change 50
after change 50
This method copies the value of an argument into the formal parameter of the method. Therefore, changes made to the parameter of the method are limited to that method only and there is no impact of changes on the argument. That is, when control returns to the caller method, earlier values of the arguments seen.
And here’s another example:
In call by reference method, a reference to an argument (not the value of the argument) passed to the parameter. Inside the method, this reference is used to access the actual argument specified in the call. It means that changes made to the parameter affect the actual argument also. When the control returns to the caller method, the changes made in the method can be seen in the arguments in the caller method too.
In Java, when we pass a simple type to a method, it is passed by value. When we create a variable of a class, we are only creating a reference to an object. Thus, when we pass this reference method, the parameter that receives it refers to the same object as that referred by the argument. It means that objects are passed to methods by reference.
class Operation2 {
int data=50;
void change(Operation2 op){
op.data = op.data+100;//changes will be made in the instance variable
}
public static void main(String args[]){
Operation2 op = new Operation2();
System.out.println(“before change ” +op.data);
op.change(op);//passing object
System.out.println(“after change ” +op.data);
}
}
The output of this:
before change 50
after change 150
Dynamic Binding
In java, base class reference can be assigned objects of sub class. When methods of sub class object are called through base class’s reference.
The mapping / binding or function calls to respective function takes place after running the program, at least possible moment. This kind of binding is known as “late binding” or “dynamic binding” or “runtime polymorphism”.
Eg.
class A
{
public void display()
{ }
}
class B extends A
{
public void display()
{ }
}
class C extends A
{
public void display()
{ }
}
class DispatchDemo
{
psvm (String args[])
{
A ob1= new A();
B ob2 = new B();
C ob3 = new C();
A r;
r=ob1;
r.display();
r=ob2;
r.display();
r=ob3;
r.display();
}
}
In the above programs, the statement r.display( ), calls the display() method and based on the object. That has been assigned to base class reference. i.e. r. But the mapping / binding as to which method is to be invoked is done only at run time.
Difference between abstract class and interface in java
Interfaces and abstract classes both implements polymorphic behaviour and seem to be similar but they are different in the following ways:
1. An interface is purely abstract i.e. methods in an interface only have declarations no implementations. On the other hand, abstract class methods may or may not have an implementation.
2. A class implementing an interface must implement all of the methods declared in the interface while a class extending an abstract class need not implement any of the methods defined in the abstract class.
3. Abstract classes are used only when there is a IS-A relationship between the classes. However, interfaces can be implemented by unrelated classes.
4. You can implement more that one interface but you cannot extend more than one abstract class,
5. User-defined exception can be defined within an interface itself which is not the case with the abstract class.
6. Members of an abstract class may have any access specifier modifier but members of an interface are public by default and cannot have any other access specifier.
7. Abstract class definition begins with the keyword abstract followed by class definition. On the other hand, interface definition begins with a keyword interface.
8. All variables in an interface are public, static and final by default whereas an abstract class can have instance variables.
9. Abstract class does not support multiple inheritance whereas interface support multiple inheritance.
10. If you define an interface and then later add a new method to an interface then you must implement that method in all of the classes which implement that interface. However, in the case of an abstract class, you can safely add non-abstract methods to that class without requiring any modification to existing classes that extend the abstract class.
11. Interface are slow as compared to abstract class as they find the actual method in the corresponding classes.
12. Interface can extend another interface, whereas abstract class can extend another class and implement multiple interfaces.
13. An abstract class can have constructors but interface cannot have constructor.
14. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
15. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
16. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
17. A Java class can implement multiple interfaces but it can extend only one abstract class.
18. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
19. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.
Difference Between Abstraction and Encapsulation
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
What is Overloading or Compile Time Polymorphism
Compile Time Polymorphism in Java is when you have the several methods with same name and different parameters and compiler has to decide how to select which method has to run based on the arguments hence the name Compile time polymorphism or method overloading.
Overloaded methods may or may not have different return types. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.
However, this match need not always be exact. In some cases java’s automatic type conversions can play a role in overload resolution. Java will employ its automatic type conversion only if no exact match is found.
The important points to note:
A difference in return type only is not sufficient to constitute an overload and is illegal.
You should restrict your use of overloaded method names to situations where the methods really are performing the same basic function with different data.
The language treats methods with overloaded names as totally different methods and as such they can have different return types. However, since overloaded methods perform the same job with different data sets, they should produce same return type normally. There is one particular condition, however, under which it is sensible to define different return types. This is the situation where the return type is derived from the argument type and is exactly parallel with the arithmetic operators.
Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list.
Overriding in Java
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version in the superclass will be hidden. If you wish to access the superclass’ version of an overridden method, you can do so by using ‘super’.
In order for any particular method to override another correctly :
- The return type, method name, type and order of arguments must be identical to those of a method in a parent class.
- The accessibility must not be more restrictive than original method.
The method must not throw checked exceptions of classes that are not possible for the original method.
Control statements in java
Different types of control statements: the decision making statements (if-then, if-then-else and switch), looping statements (while, do-while and for) and branching statements (break, continue and return). [Read more…] about Control statements in java
Differences between Final, Finally and Finalize in Java
final: Variables are useful when you need to store information that can change as the program runs. However, there may be certain situations in the program in which the value of the variable should not be allowed to modify. It is accomplished using a particular type of variable known as the final variable. The final variable also called constant variable. It is a variable with a value that cannot modify during the execution of the program.
The Final keyword used when we want restrictions applied to a method, class, and variable. We can’t override the Final method, inherit the Final class or change the Final variable. To declare a final variable, use the final keyword before the variable declaration and initialize it with a value. Its syntax is
final datatype varName = value;
For example:
final double PI = 3.141592;
This statement declares a variable PI of type double which initialized to 3.141592, that cannot be modified. If an attempt is made to modify a final variable after it initialized, the compiler issues an error message “cannot assign a value to final variable PI.”
You can also defer the initialization of the final variable, such a final variable known as a blank final. However, it must be initialized before it used.
Final variables are beneficial when one need to prevent accidental change to method parameters and with variables accessed by anonymous class.
Now consider a program to calculate the area of the circle,
//Area of the circle
public class AreaCircle {
public static void main(String[] args){
int r =10;//initializing radius
final double PI =3.141592;//final variable
double area;
//PI = 3.142; will generate an error
area = PI * r * r;
System.out.println(“Area of circle is –>”+area);
}
}
Output: Area of the circle is — >314.1592
NOTE: It is recommended to declare a final variable in uppercase
finally: The finally block always executes when the try block exits, except System.exit(0) call. If an exception occurs inside a try block and there is no matching catch block, the method terminates without further executing any lines of code from that method. For example, suppose you may want to close a file that has opened even if your program could not read from the file for some reason. In other words, you want to close the file irrespective whether the read is successful or not. If you want that some lines of code must be executed regardless of whether or not there is matching catch block, put those lines inside the finally block.
The finally block is used to release system resources and perform any cleanup required by the code in the try block. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
The finally block consist of finally keyword followed by the code enclosed in curly braces. Just like a catch block, a finally block is associated with a particular try block and must appear after the last catch block. If there are no catch blocks, then you can place the finally block immediately after the try block.
The general form of a try statement with finally block is
try {
//statement that can throw exceptions
}
catch(exception_type identifier) {
//statements executed after exception is thrown
}
finally {
//statements which executed regardless of whether or not
//exceptions are thrown
}
Let us consider three cases when the try-catch block executes only with the finally block.
Case A: If the try block succeeds (i.e., no exception is thrown), the flow of control reaches the end of the try block and proceeds to the finally block by skipping over the catch blocks. When the finally block completes, the rest of the method continues.
Case B: If a try block fails (i.e., an exception is thrown), the flow control immediately move to the appropriate catch block. When the catch block completes, the finally block runs. When the finally block completes, the rest of the method continues.
Case C: If the try or catch block has a return statement, the finally block still get executed before control transfers to its new destination. Now let us consider a program that demonstrates the use of finally block,
Output: divide by zero
Inside finally block
End of main method
NOTE: The finally block always executed except when the try or catch invokes a System.Exit() method, which causes the Java interpreter to stop running.
finalize(): Garbage collection automatically frees us the memory resources used by objects, but objects can hold other kinds of resources, such as open files and network collections. The garbage collector cannot free these resources for you. For this, we need to write a finalize() method for any object that needs to perform such tasks as closing files, terminating network connections and so on. The finalize() method declared in the java.lang.Object class.
A finalize() method is an instance method that takes no arguments and returns no value. There can be only one finalize() method per class. A finalize() method can throw an exception or error, but when the garbage collector automatically invokes it, any exception or error it throws is ignored and serves only to cause the method to return.
Before an object gets garbage collected, the garbage collector gives the object an opportunity to clean up itself through a call to the object’s finalize() method. This method is called automatically by Java before an object finally destroyed, and space it occupies in memory is released. The finalize() method takes the following form,
protected void finalize() {
//clean up code by you
}
Here, the keyword protected is an access specifier that prevents access to the finalize method by code defined outside the class. This code will explain it better:
class FinalizeExample {
public void finalize() {
System.out.println(“Finalize is called”);
}
public static void main(String args[]) {
FinalizeExample f1 = new FinalizeExample();
FinalizeExample f2 = new FinalizeExample();
f1 = null;
f2 = null;
System.gc();
}
}
This method is useful when
• Your class object use resources that are not within the Java environment and are not guaranteed to be released by the object itself.· For example Graphics resources, fonts, etc. that are supplied by the host operating system.
• To record the fact that the object destroyed. For example: To count the numbers of objects that were in memory rather than created. Writing Java classes that interface to native platform code with native methods. In such a case, the native implementation can allocate memory or other resources that are not under the control of the garbage collector and need to reclaimed explicitly.
A problem with the finalize() method is that you never know when or if the finalize() method called. It is because the garbage collector is not guaranteed to execute at a specified time. So one should avoid using the finalize() method and when you do so you should write it with great care.
What is the use of ‘Exit’ statement
The Exit statement allows you to exit prematurely from a block of statements in a control structure from a loop, or even from a procedure. Suppose you have a For…….Next loop that calculates the square root of negative numbers can’t be calculated ( the Sqr() function generates a runtime error,)
you might want to halt the operation if the array contains a invalid value. To exit the loop prematurely, use the Exit For statement as follows :
For i=0 to UBound(nArray())
If nArray(i)<0 then Exit For
nArray(i)=Sqr(nArray(i))
Next
If a negative element is found in this loop, the program exits the loop and continues with the statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), as well as for functions and subroutines (Exit Function and Exit Subroutine).
Automatic Memory Management
Automatic memory management, also known as automatic garbage collection, is the practice of allowing the language implementation to keep track of used and unused memory, freeing the programmer from this burden.
In languages without automatic memory management, the programmer must reserve memory when it is required and mark it as free once its contents no longer have effect in the running program. For example, in the C programming language (probably the most commonly used of those without automatic memory management) this is achieved by using the functions malloc, calloc, realloc, alloc and free.
On the other hand, languages (or implementations) with automatic memory management automatically reserve memory when it is required for storing new values and reclaim it (free it) when their contents can no longer affect future computations
(1) Java automatically does the Garbage collecting and probably does a better job than most developers on the down side.
(2) By auto Garbage collecting it takes away an opportunity for developers to optimise garbage collecting and auto Garbage collecting can be seen as a constraint not a benefit.
In the most part it is a benefit because it simplifies programming in Java and is probably more efficient at garbage collecting than self regulated Garbage collecting, unless people spent time researching the best way to garbage collect.
Garbage collection concerns objects with dynamic extent (allocated with a new statement in these languages). Java uses various techniques to automaticallydiscover when these objects are no longer referred to, and to reclaim them. Incontrast, C++ programmers manually specify where an object with dynamicextent is to be reclaimed by coding a delete statement.
_ Java classes can have a finalize function.
_ Java uses run-time processing to discover dead objects (which are eligible for reclamation).
Command Line Arguments in Java
Command Line Arguments are parameters supplied to the application program at the time of invoking it for execution. We can write Java programs that can receive and use the arguments provided in the command line.
e.g. public static void main (String args[]). Args declared as an array of strings and arguments provided in the command line passed to the array args as its elements.
A Java application can accept any number of arguments from the command line. It allows the user to specify configuration information when the application launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to run. For example, suppose a Java application called Sort.java sorts lines in a file. To sort the data in a file named friends.txt, a user would enter :
java Sort friends.txt
When an application launched, the runtime system passes the command-line arguments to the application’s main method via an array of Strings. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String: “friends.txt”.
The Echo example displays each of its command-line arguments on a line by itself:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
The following example shows how a user might run Echo. User input is in italics.
java Echo Drink Hot Java
Drink
Hot
Java
Note that the application displays each word — Drink, Hot, and Java — on a line by itself. It is because the space character separates command-line arguments.
To have Drink, Hot and Java interpreted as a single argument; the user would join them by enclosing them within quotation marks.
java Echo “Drink Hot Java”
Drink Hot Java
Scope of Java Variables
A variable is a place in memory where we can store a value. The Java programming language defines the following kinds of variables : [Read more…] about Scope of Java Variables
Data Types in Java
A variable in a program occupies some space in computer’s memory where some value is stored. A value to be stored may be an integer, floating point number, a character or a string. However, now the question arises that how much memory is allocated to these values and what is the range of values that can be stored in it as different types of values don’t occupy same space in memory. So to store these values, we require different data types depending on the needs of the application. The data type determines how much memory is allocated to store data and what operations can be performed on it. The Data type also defines the values that a variable can takes.
Java has statically typed language (do type checking at compile-time instead of at run-time).In Java, some of the predefined (already defined) data types are part of the programming language and constants (or an identifier), and variables are defined as certain data types before you can use it.
In Java, the data types can be classified into two broad categories:
Primitive type (or built-in type or value type) and
Reference type (non-primitive or derived type).
Difference between primitive and reference data type in java
The main difference between the primitive type and reference type is that the memory location associated with the primitive type variable contains the actual value of the variable. On the other hand, the memory location associated with the reference type variable contains an address that indicates the memory location of the actual object.
In Java, there are eight primitive data types. Out of the eight primitive types, six are for numbers, one for character and one is for boolean values. Of the six number types, four are types of integers, and two are types of floating-point numbers.
The reference type includes array, interface and class.
Primitive Data Types
Primitive data types definition: That are non grouped pieces of data which can have only one value at a time. They are the simplest built in forms of data in Java. Other data types are made up of combination of primitive data types. Java initializes all primitive data types to default values if an initial value is not explicitly specified by the programmer. Integer and floating-point variables are initialized to 0. The char data type is initialized to null and Boolean data types are set to false. The example of primitive data type
The 8 primitive data types byte, short, int, long, float, double, boolean and char are called primitive data types , as they are built into the Java language at low level .
Reference Data Types
Reference data types are made by the logical grouping of primitive data types. These are called reference data types because they contain the address of a value rather than the value itself. Arrays, objects, interfaces, enum etc. are examples of reference data types.
Intergral Types
The integral types consists of integer types and character types.
Integer Data Types
Integer types are used to store whole numbers without a fractional part. In Java, there are four integer types: byte, short, int and long. These four types differ only in the number of bits and therefore in the range of values. Each data type can store both positive as well as negative values. However, unlike C/C++, Java does not support unsigned integers.
The following table enlists the four integer types, their size (i.e. number of bits it occupies in memory) and their minimum and maximum values.
Size of primitive data types in java
Type |
Length |
Minimum Value |
Maximum Value |
byte |
8 bits |
-128 |
127 |
short |
16bits |
-32768 |
32767 |
int |
32 bits |
-2,147,483,648 |
2,147,483,647 |
long |
64bits |
-9,223,372,036,854,775,808 |
9,223,372,036,854,775,80 |
float |
-3.4Е+38 |
+3.4Е+38 |
|
double |
-1.7Е+308 |
+1.7Е+308 |
|
boolean |
Possible values are two – true or false |
||
char |
|||
Object |
null |
||
String |
null |
The range of integer types lie in the range -2x-1to +2x-1-1 where x is the total number of bits used to store the data type. One has been subtracted from x as one bit is reserved for the sign bit and the remaining for the magnitude. Also, we have subtracted 1 from the upper limit of the range because 0 is included.
• byte: In certain applications, you may not need integers as large as the standard int type provides. In such cases, Java provides two smaller integer types byte and short. The byte data type is an 8-bit (1 byte) signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
• short: The short data type is a 16-bit (2 byte) signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
The byte and short types are mainly intended for specialized applications, such as low-level file handling, or for large arrays where saving the memory space is important. We could have used this instead of int, but you can only use the short variable if you know 100% that your values will not exceed that range.
int: The int data type is a 4-bytes(32 bits) signed two’s complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else.
A variable length of int type can be declared as follows.
int length;
long: The long data type is a 8 bytes (64-bits) signed two’s complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036, 854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
A variable distance of long integer type can be declared as follows.
long distance;
Each integer type has a corresponding wrapper class Byte, Short, Integer and Long.
In Java, the size of integer types is specified by the language and is always the same regardless of what kind of computer a program runs on. This make the Java programs to produce the same results on all the computer. This is a huge improvement over the C/C++ language which let the compilers for different platforms determine the optimum size for integer data types. As a result, C/C++ program written or tested on one type of computer might not produce the same result on another computer. This is also true for other primitive types.
char Data Types
Type char is basically a 16-bit unsigned integer that represents a Unicode value. This means that a total of 216 or 65536 different unicode characters can be represented corresponding to the integer values 0 to 65535. Each printable and nonprintable character has a Unicode value. Because Java stores all characters as Unicode, it can be used with virtually any written language in the world.
A character variable choice of char type can be declared as follows,
char choice;
Floating-Point Data Types
The integer types do not provide the facility to represent decimal number so whenever you want to represent a number with a decimal such as 3.142, use a floating-point data type. If you try to use an integer type to store a number with fractional part, the fractional part will simply be discarded. So, Java provides two primitive floating point types: float and double to store numbers with fractional parts. Out of the two, double is most commonly used because all the math functions in Java class library use double values.
NOTE: Both float and double follow the IEEE-754 format.
• float: The float data type requires 4 bytes (32-bits) for their storage. Their digits of precision (numbers of digits after decimals point) are 7 and range lies between -3.4 E38 (-3.4×1038) to +3.4E38 (+3.4×1038). This data type is normally used to represent quantities which inheritally cannot be represented by integers. For example : height of a person, average of number of
values etc.
A variable average of float data type can be declared as follows,
float average;
• Double: Double variables are used when we want to store much larger or smaller values than the maximum and minimum allowable in a standard variable. The double data type uses 8 bytes (M-bits) for their storage. Their digits of precision are 15 and range lies between -1.7E308 to +1.7E308. A variable sunDistance of double type can be declared as follows,
double sunDistance;
NOTE: Since the double type is twice as big as the float type, so double is known as double precision and float is known as single precision.
boolean Data Types
Boolean type is used to represent true/false values. For example: whether light is on, container is empty etc. It got its name from George Boole, an English Mathematician who invented the concept of Boolean Algebra. In Java, boolean type is represented using boolean keyword. The boolean data type can only hold two values: true and false. The values true and false are literals. Booleans are typically used for design making and for controlling the order of execution of a program.
You can declare a variable flag of type boolean as follows.
boolean flag;
NOTE: A boolean is not an integral type as in C++ and integer values cannot be used in place of boolean.
double Data Types
The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class.
How Reading input from reader
It is in two types. Those are,
1. Command line arguments
2. By using readLine() method
Through Command line arguments : (used rarely) Arguments can be passed to a java prg at the time of running it. Such arguments are known as command line arguments. Those arguments are stored in the string array which is a parameter of main().
By using readLine() method:
Integer : It is a class belongs to java.lang package.
parseInt(): It is a method. It is supported by the class Integer. It is used to convert a number from string format to integer format.
readLine():
The method readLine() is used to take input from user at runtime. This method is defined in the class DataInputStream. This class is available in java.io package. By default this method reads any kind of input in String format. That should be converted to the required types. readLine() methods throws an IOException should be handled or throwsclass has to be used.
java.io :
It is a package. It contains various classes required for input and output
opertions.
DataInputStream,
DataOutputStream,
FileInputStream
IOException:
It is an Exception class. It is a part of java.io packages. It is required to be caught in every method when readLine() is used. Else throws class is used to mention IOException.
System.in:
It is parameter of the constructor(new) of DataInputStream. It indicates standard input.i.e. Key board. ‘in’ is an object of DataInputStream class. It is required in order to call readLine() method.
Vector in Java
Vectors:- We know that Arrays are very useful when there is a need to use number of variables But There is a problem with Array they use only single data type or The Elements of array are always Same type For Avoiding this Problem Vectors are used.
These are also Collection of elements those are object data type For Using Vectors we have to import java.util package These are also Called as dynamic Array of object data type .
But Always Remember vectors doesn’t support primitives data types like int, float, char etc. For Creating a Vector, Vector Class will be used which is reside in java’s utility package
Various Methods those are used with vectors:-
1.addElement:- For Inserting an element into Vector
2.elementAt:- Gives the name of Char at position
3.size:- Give us Size of Number of Elements in Vector
4.copyInto:- For Copying All Elemnts insto an Array
5.insertElementAt(ele,n):- For Inserting an Element ele into the nth Position
Static keyword in Java (With Examples)
We use the static keyword mostly for memory management, and the keyword goes with the class itself, not with a class instance. It may be:
[Read more…] about Static keyword in Java (With Examples)
Difference between Procedural and Object Oriented Programming
The different languages reflect the different styles of programming. OOP or object-oriented programming is a style of programming with a firm basis in several concepts. Those concepts revolve around objects and classes and include Polymorphism, Encapsulation, Inheritance, Abstraction and more. Java is one of the most popular of all the object-oriented programming languages, as well as one of the easiest to learn and use.
Any application built on objects in Java is an object-oriented application and is based on the declaration of one or more classes, with an object created from those classes and the interaction between the objects. [Read more…] about Difference between Procedural and Object Oriented Programming
Access Modifiers In Java
Modifiers are keywords used to define the scope and behaviour of classes, methods and variables in Java. Access modifiers specified who can access them. Java has a wide variety of modifiers that can be categorized as shown below: [Read more…] about Access Modifiers In Java
Java this keyword with example
The this keyword in Java is used when a method has to refer to an object that has invoked it. It can be used inside any method to refer to the current object. This means that this is always used as a reference to the object on which the method was invoked. We can use this anywhere as reference to an object of the current class type is permitted. [Read more…] about Java this keyword with example
Garbage Collection in Java
When you create an object by instantiating a class, the object uses some memory. After an object in memory has been used and is no longer needed, it is sensible to free memory from that object. Unlike some object-oriented languages where you have to explicitly destroy the objects that are no more references to that object. References that held in a variable naturally dropped when the variable goes out of scope. Alternatively, we can explicitly drop an object reference by setting the variable to null. which is a tedious and error-prone task, Java follows a different approach. [Read more…] about Garbage Collection in Java
Interface in java with Example Programs
Java interface use for achieving 100% abstraction because the interface only contains methods without any implementation or body. However, it has only abstract methods and constants (final fields). Any field declared inside the interface is public, static, and final by default, and any method is an abstract public method. It specifies what must do but not how. Once an interface is defined, the class implements an interface by implementing each method declared by the interface. Also, one class can implement any number of interfaces. [Read more…] about Interface in java with Example Programs
Java Classes and Objects (With Example) – Definition
Objects and classes are the essential concepts in OOP as they are what we use for writing our programs. Java objects may be both physical and logical entities, but classes are only logical entities. [Read more…] about Java Classes and Objects (With Example) – Definition