Core Java
03:17What is core java ?
Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Micro systems Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them. Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another. Java is as of 2012 one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users.The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.-
History
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.
Why do I need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere! -
Features of java
Java technology is a high-level programming and a platform independent language. Java is designed to work in the distributed environment on the Internet. Java has a GUI features that provides you better "look and feel" over the C++ language, moreover it is easier to use than C++ and works on the concept of object-oriented programming model. Java enable us to play online games, video, audio, chat with people around the world, Banking Application, view 3D image and Shopping Cart. Java find its extensive use in the intranet applications and other e-business solutions that are the grassroots of corporate computing. Java , regarded as the most well described and planned language to develop an applications for the Web. Java is a well known technology which allows you for software designed and written only once for an "virtual machine" to run on a different computers, supports various Operating System like Windows PCs, Macintoshes, and Unix computers. On the web aspect, Java is popular on web servers, used by many of the largest interactive websites. Java is used to create standalone applications which may run on a single computer or in distributed network. It is also be used to create a small application program based on applet, which is further used for Web page. Applets make easy and possible to interact with the Web page.
Data Types
The Java language contains the following primitive data types:
That these are primitive data types means that they are not objects. Classes and objects are explained
later. The primitive types also come in versions that are objects, meaning you can call methods on
them, like on any other object in Java.
Java also contains a few core data types which are objects. Here is a list of those types, including the object versions of the primitive types.
Notice how object types are spelled with a capital letter in the beginning of their name.
There are of course many other components you can use in the Java API, but the above mentioned data types are the core Java types.
You can also create your own more complex data types by creating custom classes. I will get back to how in a later text.
Next : Java Variables
Description | |
byte | 8 bit signed value, values from -128 to 127 |
short | 16 bit signed value, values from -32.768 to 32.767 |
char | 16 bit Unicode character |
int | 32 bit signed value, values from -2.147.483.648 to 2.147.483.647 |
long | 64 bit signed value, values from -9.223.372.036.854.775.808 to 9.223.372.036.854.775.808 |
float | 32 bit floating point value |
double | 64 bit floating point value |
Java also contains a few core data types which are objects. Here is a list of those types, including the object versions of the primitive types.
Description | |
Byte | 8 bit signed value, values from -128 to 127 |
Short | 16 bit signed value, values from -32.768 to 32.767 |
Character | 16 bit Unicode character |
Integer | 32 bit signed value, values from -2.147.483.648 to 2.147.483.647 |
Long | 64 bit signed value, values from -9.223.372.036.854.775.808 to 9.223.372.036.854.775.808 |
Float | 32 bit floating point value |
Double | 64 bit floating point value |
String | N byte Unicode string of textual data. Immutable |
There are of course many other components you can use in the Java API, but the above mentioned data types are the core Java types.
You can also create your own more complex data types by creating custom classes. I will get back to how in a later text.

Operators
Basic Operators in Java
Operators are special characters within the Java language that perform operations on arguments to return a specific result. Some of the types of basic operators are given below :- Arithmetic Operators
- Relational Operators
- Bitwise Operators
- Boolean Logical Operators
In java, arithmetic operators have the same use as in algebra. Given below table consist of list of arithmetic operators :
Operator | Result |
+ | Addition |
- | Subtraction (also unary minus) |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
+= | Addition assignment |
-= | Subtraction assignment |
*= | Multiplication assignment |
/= | Division assignment |
%= | Modulus assignment |
-- | Decrement |
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. They are summarized in the following :
Operator | Result |
~ | Bitwise unary NOT |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise exclusive OR |
>> | Shift Right |
>>> | Shift Right zero fill |
<< | Shift left |
&= | Bitwise AND assignment |
\= | Bitwise OR assignment |
^= | Bitwise exclusive OR assignment |
>>= | Shift Right assignment |
>>>= | Shift Right zero fill assignment |
<<= | Shift left assignment |
The relational operator determine the relationship that one operand has to other. Specifically, they determine equality and ordering . The relational operators are shown here :
Operator | Result |
= = | Equal to |
!= | Not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
The Boolean logical operators shown here operates only on Boolean operands. All of the binary logical operators combine two Boolean values to form a resultant Boolean value.
Operator | Results |
& | Logical AND |
\ | Logical OR |
^ | Logical XOR(exclusive OR) |
|| | Short-circuit OR |
&& | Short-circuit AND |
! | Logical Unary not |
&= | AND assignment |
\= | OR assignment |
^= | XOR assignment |
= = | Equal to |
!= | Not equal to |
? : | Ternary if-then-else |
Given below table shows the order of precedence for java operators, from highest to lowest :
Highest | |||
( ) | [] | . | |
++ | -- | ~ | ! |
* | / | % | |
+ | - | ||
>> | >>> | << | |
> | >= | < | <= |
= = | != | ||
& | |||
^ | |||
| | |||
&& | |||
|| | |||
? : | |||
= | |||
Lowest |
Control Statements
Java Control Statements
In this section, we are going to discuss the control statements. 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).Control Statements
The control statement are used to controll the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic. Java contains the following types of control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
Selection statements:
- If Statement:
This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is executed. Hence "This is even number" is printed on the screen.
int n = 10;
if(n%2 = = 0){
System.out.println("This is even number");
}
- If-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
System.out.println("This is even number");
}
else{
System.out.println("This is not even number");
}
- Switch Statement:
This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed.
Syntax:
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:
<statement>;
default:
<statement>;
}//end switch
Example: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thrusday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid entry");
break;
}
- while loop statements:
This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop.
Syntax:
while(expression){
<statement>;
...;
...;
}
Example: Here expression i<=10 is the condition which is checked before entering into the loop statements. When i is greater than value 10 control comes out of loop and next statement is executed. So here i contains value "1" which is less than number "10" so control goes inside of the loop and prints current value of i and increments value of i. Now again control comes back to the loop and condition is checked. This procedure continues until i becomes greater than value "10". So this loop prints values 1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10){
System.out.println("Num " + i);
i++;
}
- do-while loop statements:
This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement. First the do block statements are executed then the condition given in while statement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once.
Syntax:
do{
<statement>;
...;
...;
}while (expression);
Example: Here first do block of code is executed and current value "1" is printed then the condition i<=10 is checked. Here "1" is less than number "10" so the control comes back to do block. This process continues till value of i becomes greater than 10.
int i = 1;
do{
System.out.println("Num: " + i);
i++;
}while(i <= 10); - for loop statements:
This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true .
Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
}
initialization: The loop is started with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.
increment or decrement: After each iteration, value increments or decrements.
Example: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then control goes into the loop and current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into the loop. This process continues till num>10. It prints values 1 to10 on the screen.
for (int num = 1; num <= 10; num++){
System.out.println("Num: " + num);
}
- Break statements:
The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Example: When if statement evaluates to true it prints "data is found" and comes out of the loop and executes the statements just following the loop.
- Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration .
Syntax:
continue;
Example:
- Return statements:
It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method.
Syntax:
return;
return values;
return; //This returns nothing. So this can be used when method is declared with void return type.
return expression; //It returns the value evaluated from the expression.
Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.
Classes and Methods
Class : Whatever we can see in this world all the things are a object. And all the objects are categorized in a special group. That group is termed as a class. All the objects are direct interacted with its class that mean almost all the properties of the object should be matched with it's own class. Object is the feature of a class which is used for the working on the particular properties of the class or its group. We can understand about the class and object like this : we are all the body are different - different objects of the human being class. That means all the properties of a proper person relates to the human being. Class has many other features like creation and implementation of the object, Inheritance etc.
In this Program you will see how to use the class, object and it's methods. This program uses the several values of several defined variables for getting the Area and Perimeter of the Square and Rectangle by calling the different functions from the different classes through the several objects created for the several class. In this program there are two classes has been used except the main class in which the main function is declared. First class is square which is using for getting the Area and Perimeter of the square and another class is rectangle which is using for getting the Area and Perimeter of the Rectangle. All the functions in the square and rectangle class are calling with different - different arguments two times for getting the Area and Perimeter of square and rectangle for two different sides. This program gives us the Area and Perimeter for the different sided Square and Rectangle separately.
Object :
Objects are the basic run time entity or in other words object is a instance of a class . An object is a software bundle of variables and related methods of the special class. In the above example the sq is the object of square class and rect is the object of the rectangle class. In real-world objects share two characteristics: They have all state and behavior. For example, The squares have state such as : sides and behaviors such as its areas and perimeters. Rectangles have state such as: length, breadth and behavior such as its areas and perimeters. A object implements its behavior with methods of it's classes. A method is a function (subroutine) associated with an object.
In this Program you will see how to use the class, object and it's methods. This program uses the several values of several defined variables for getting the Area and Perimeter of the Square and Rectangle by calling the different functions from the different classes through the several objects created for the several class. In this program there are two classes has been used except the main class in which the main function is declared. First class is square which is using for getting the Area and Perimeter of the square and another class is rectangle which is using for getting the Area and Perimeter of the Rectangle. All the functions in the square and rectangle class are calling with different - different arguments two times for getting the Area and Perimeter of square and rectangle for two different sides. This program gives us the Area and Perimeter for the different sided Square and Rectangle separately.
Object :
Objects are the basic run time entity or in other words object is a instance of a class . An object is a software bundle of variables and related methods of the special class. In the above example the sq is the object of square class and rect is the object of the rectangle class. In real-world objects share two characteristics: They have all state and behavior. For example, The squares have state such as : sides and behaviors such as its areas and perimeters. Rectangles have state such as: length, breadth and behavior such as its areas and perimeters. A object implements its behavior with methods of it's classes. A method is a function (subroutine) associated with an object.
What are Methods?
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value.
Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Good programmers write in a modular fashion which allows for several programmers to work independently on separate concepts which can be assembled at a later date to create the entire project. The use of methods will be our first step in the direction of modular programming.
Methods are time savers, in that they allow for the repetition of sections of code without retyping the code. In addition, methods can be saved and utilized again and again in newly developed programs.
You are using methods when you use System.out.print( ) and System.out.println( ).
There are two basic types of methods:
Built-in:
Build-in
methods are part of the compiler package, such as System.out.println( )
and System.exit(0). |
User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign to them and perform tasks that you create. |
How to invoke (call) a method (method invocation):
When a method is
invoked (called), a request is made to perform some action, such as
setting a value, printing statements, returning an answer, etc.
The code to invoke the method contains the name of the method to be
executed and any needed data that the receiving method requires.
The required data for a method are specified in the method's parameter
list.
Consider this method that we have already been using from Breezy;
int
number = Console.readInt("Enter a number"); //returns a value
The method name is "readInt"
which is defined in the class "Console".
Since the method is defined in the class
Console, the word
Console
becomes the calling object. This particular method returns an integer
value which is assigned to an integer variable named
number.
You invoke (call) a
method by writing down the calling object followed by a dot, then the name of
the method, and finally a set of parentheses that may (or may not) have
information for the method.
Inheritance
In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects, or to establish a subtype from an existing object, or both, depending upon programming language support. In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes called base classes, superclasses, parent classes or ancestor classes. The resulting classes are known as derived classes, subclasses or child classes. The relationships of classes through inheritance gives rise to a hierarchy. In prototype-based programming, objects can be defined directly from other objects without the need to define any classes, in which case this feature is called differential inheritance.
Subclasses and superclasses
A subclass, heir class, or child class is a modular, derivative class that inherits one or more properties from another class (called the superclass, base class, or parent class). The properties in question vary from language to language, but commonly include class data variables, properties, and methods or functions. Some languages support the inheritance of other properties as well. For example, in Eiffel, contracts which define the specification of a class are also inherited by heirs. The superclass establishes a common interface and foundational functionality, which specialized subclasses can inherit, modify, and supplement. The software inherited by a subclass is considered reused in the subclass. In some cases, a subclass may customize or redefine a method inherited from the superclass. A superclass method which can be redefined in this way is called a virtual method.
Applications
Inheritance is used to co-relate two or more classes to each other.
Inheritance vs subtyping
Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A, and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).
In programming languages that do not support inheritance as a subtyping mechanism, the relationship between a base class and a derived class is only a relationship between implementations (a mechanism for code reuse), as compared to a relationship between types. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail behavioral subtyping. It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected; see the Liskov substitution principle. [3] (Compare connotation/denotation.) In some OOP languages, the notions of code reuse and subtyping coincide because the only way to declare a subtype is to define a new class that inherits the implementation of another.
Subclasses and superclasses
A subclass, heir class, or child class is a modular, derivative class that inherits one or more properties from another class (called the superclass, base class, or parent class). The properties in question vary from language to language, but commonly include class data variables, properties, and methods or functions. Some languages support the inheritance of other properties as well. For example, in Eiffel, contracts which define the specification of a class are also inherited by heirs. The superclass establishes a common interface and foundational functionality, which specialized subclasses can inherit, modify, and supplement. The software inherited by a subclass is considered reused in the subclass. In some cases, a subclass may customize or redefine a method inherited from the superclass. A superclass method which can be redefined in this way is called a virtual method.
Applications
Inheritance is used to co-relate two or more classes to each other.
Overriding :
Many object-oriented programming languages permit a class or object to replace the implementation of an aspect-typically a behavior-that it has inherited. This process is usually called overriding. Overriding introduces a complication: which version of the behavior does an instance of the inherited class use-the one that is part of its own class, or the one from the parent (base) class? The answer varies between programming languages, and some languages provide the ability to indicate that a particular behavior is not to be overridden and should behave as defined by the base class. For instance, in C#, the overriding of a method should be specified by the program.[citation needed] An alternative to overriding is hiding the inherited code.Code reuse :
Implementation inheritance is the mechanism whereby a subclass re-uses code in a base class. By default the subclass retains all of the operations of the base class, but the subclass may override some or all operations, replacing the base-class implementation with its own. In the following Python example, the subclass CubeSumComputer overrides the transform() method of the base class SquareSumComputer. The base class comprises operations to compute the sum of the squares between two integers. The subclass re-uses all of the functionality of the base class with the exception of the operation that transforms a number into its square, replacing it with an operation that transforms a number into its cube. The subclass therefore computes the sum of the cubes between two integers.Inheritance vs subtyping
Subtyping enables a given type to be substituted for another type or abstraction. Subtyping is said to establish an is-a relationship between the subtype and some existing abstraction, either implicitly or explicitly, depending on language support. The relationship can be expressed explicitly via inheritance in languages that support inheritance as a subtyping mechanism. For example, the following C++ code establishes an explicit inheritance relationship between classes B and A, where B is both a subclass and a subtype of A, and can be used as an A wherever a B is specified (via a reference, a pointer or the object itself).
In programming languages that do not support inheritance as a subtyping mechanism, the relationship between a base class and a derived class is only a relationship between implementations (a mechanism for code reuse), as compared to a relationship between types. Inheritance, even in programming languages that support inheritance as a subtyping mechanism, does not necessarily entail behavioral subtyping. It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected; see the Liskov substitution principle. [3] (Compare connotation/denotation.) In some OOP languages, the notions of code reuse and subtyping coincide because the only way to declare a subtype is to define a new class that inherits the implementation of another.
Interfaces
An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.
Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface. One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed.
Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface. For instance, if one were annoyed by a whistling noise, one may not know whether it is a human or a parrot, because all that could be determined is that a whistler is whistling. In a more practical example, a sorting algorithm may expect an object of type
For example:
Interfaces are defined with the following syntax (compare to Java's class definition):
Thus, a simple interface may be
The member type declarations in an interface are implicitly static, final and public, but otherwise they can be any type of class or interface.[1]
The syntax for implementing an interface uses this formula:
If a class implements an interface and does not implement all its methods, it must be marked as
Classes can implement multiple interfaces
Interfaces are commonly used in the Java language for callbacks.[2] Java does not allow the passing of methods (procedures) as arguments. Therefore, the practice is to define an interface and use it as the argument and use the method signature knowing that the signature will be later implemented.
is legal and defines a subinterface. Note how it allows multiple inheritance, unlike classes. Note also that
Some common Java interfaces are:
Comparable has the method compareTo, which is used to describe two objects as equal, or to indicate one is greater than the other. Generics allow implementing classes to specify which class instances can be compared to them.
Serializable is a marker interface with no methods or fields - it has an empty body. It is used to indicate that a class can be serialized. Its Javadoc describes how it should function, although nothing is programmatically enforced.
Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either be null, or be bound to an object that implements the interface. One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed.
Overview
Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. For instance, a human and a parrot can both whistle; however, it would not make sense to representHuman
s and Parrot
s as subclasses of a Whistler
class. Rather they would most likely be subclasses of an Animal
class (likely with intermediate classes), but both would implement the Whistler
interface.Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface. For instance, if one were annoyed by a whistling noise, one may not know whether it is a human or a parrot, because all that could be determined is that a whistler is whistling. In a more practical example, a sorting algorithm may expect an object of type
Comparable
. Thus, it knows that the object's type can somehow be sorted, but it is irrelevant what the type of the object is. The call whistler.whistle()
will call the implemented method whistle
of object whistler
no matter what class it has, provided it implements Whistler
.For example:
interface Bounceable { void setBounce(); // Note the semicolon // Interface methods are public, abstract and never final. // Think of them as prototypes only; no implementations are allowed. }
Usage
Defining an interface
Interfaces are defined with the following syntax (compare to Java's class definition):
[visibility] interface InterfaceName [extends other interfaces] { constant declarations abstract method declarations }The body of the interface contains abstract methods, but since all methods in an interface are, by definition, abstract, the
abstract
keyword is not required. Since the interface specifies a set of exposed behaviors, all methods are implicitly public
.Thus, a simple interface may be
public interface Predator { boolean chasePrey(Prey p); void eatPrey(Prey p); }
The syntax for implementing an interface uses this formula:
... implements InterfaceName[, another interface, another, ...] ...Classes may implement an interface. For example,
public class Lion implements Predator { public boolean chasePrey(Prey p) { // programming to chase prey p (specifically for a lion) } public void eatPrey (Prey p) { // programming to eat prey p (specifically for a lion) } }
abstract
. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods. Although if any of the abstract class' subclasses does not implement all interface methods, the subclass itself must be marked again as abstract
.Classes can implement multiple interfaces
public class Frog implements Predator, Prey { ... }
Subinterfaces
Interfaces can extend several other interfaces, using the same formula as described below. For examplepublic interface VenomousPredator extends Predator, Venomous { //interface body }
Predator
and Venomous
may possibly define or inherit methods with the same signature, say kill(Prey prey)
. When a class implements VenomousPredator
it will implement both methods simultaneously.Some common Java interfaces are:
Comparable has the method compareTo, which is used to describe two objects as equal, or to indicate one is greater than the other. Generics allow implementing classes to specify which class instances can be compared to them.
Serializable is a marker interface with no methods or fields - it has an empty body. It is used to indicate that a class can be serialized. Its Javadoc describes how it should function, although nothing is programmatically enforced.
Packages
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.
In a Java source file, the package that this file's class or classes belong to is specified with the package keyword. This keyword is usually the first keyword in the source file.[1] package java.awt.event;
To use a package's classes inside a Java source file, it is convenient to import the classes from the package with an import declaration. The following declaration import java.awt.event.*;
imports all classes from the java.awt.event package, while the next declaration import java.awt.event.ActionEvent;
imports only the ActionEvent class from the package. After either of these import declarations, the ActionEvent class can be referenced using its simple class name: ActionEvent myEvent = new ActionEvent();
Classes can also be used directly without an import declaration by using the fully qualified name of the class. For example, java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent(); does not require a preceding import declaration.
Note that if you do not use a package declaration, your class ends up in an unnamed package.[2][3] Classes in an unnamed package cannot be imported from classes in any other package.[4]
Package naming conventions
Packages are usually defined using a hierarchical naming pattern, with levels in the hierarchy separated by periods (.) (pronounced "dot"). Although packages lower in the naming hierarchy are often referred to as "subpackages" of the corresponding packages higher in the hierarchy, there is almost no semantic relationship between packages. The Java Language Specification establishes package naming conventions to avoid the possibility of two published packages having the same name. The naming conventions describe how to create unique package names, so that packages that are widely distributed will have unique namespaces. This allows packages to be separately, easily and automatically installed and catalogued.
In general, a package name begins with the top level domain name of the organization and then the organization's domain and then any subdomains, listed in reverse order. The organization can then choose a specific name for its package. Package names should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with fractions, naming the package ca.mysoft.fractions distinguishes the fractions package from another similar package created by another company. If a German company named MySoft also creates a fractions package, but names it de.mysoft.fractions, then the classes in these two packages are defined in a unique and separate namespace.
Complete conventions for disambiguating package names and rules for naming packages when the Internet domain name cannot be directly used as a package name are described in section 7.7 of the Java Language Specification.
- A package provides a unique namespace for the types it contains.
- Classes in the same package can access each other's package-access members.
In a Java source file, the package that this file's class or classes belong to is specified with the package keyword. This keyword is usually the first keyword in the source file.[1] package java.awt.event;
To use a package's classes inside a Java source file, it is convenient to import the classes from the package with an import declaration. The following declaration import java.awt.event.*;
imports all classes from the java.awt.event package, while the next declaration import java.awt.event.ActionEvent;
imports only the ActionEvent class from the package. After either of these import declarations, the ActionEvent class can be referenced using its simple class name: ActionEvent myEvent = new ActionEvent();
Classes can also be used directly without an import declaration by using the fully qualified name of the class. For example, java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent(); does not require a preceding import declaration.
Note that if you do not use a package declaration, your class ends up in an unnamed package.[2][3] Classes in an unnamed package cannot be imported from classes in any other package.[4]
Package naming conventions
Packages are usually defined using a hierarchical naming pattern, with levels in the hierarchy separated by periods (.) (pronounced "dot"). Although packages lower in the naming hierarchy are often referred to as "subpackages" of the corresponding packages higher in the hierarchy, there is almost no semantic relationship between packages. The Java Language Specification establishes package naming conventions to avoid the possibility of two published packages having the same name. The naming conventions describe how to create unique package names, so that packages that are widely distributed will have unique namespaces. This allows packages to be separately, easily and automatically installed and catalogued.
In general, a package name begins with the top level domain name of the organization and then the organization's domain and then any subdomains, listed in reverse order. The organization can then choose a specific name for its package. Package names should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with fractions, naming the package ca.mysoft.fractions distinguishes the fractions package from another similar package created by another company. If a German company named MySoft also creates a fractions package, but names it de.mysoft.fractions, then the classes in these two packages are defined in a unique and separate namespace.
Complete conventions for disambiguating package names and rules for naming packages when the Internet domain name cannot be directly used as a package name are described in section 7.7 of the Java Language Specification.
Exception Handling
Programs has two types of times
1) Compile time –Time taken to compile the program and
2) Run time—Time taken to run the program.
Exceptions are run time errors, not compile time errors.
Exception is an inbuilt class in the java.lang package. There are many sub classes of exception like ArithmeticExcepiton, NullpointerException etc.
Depending upon the nature of the problem occuring during run time, java creates the appropriate Exception object and throws it. For example: - int i = 1/0; [Java will throw ArithmeticException type of object] Suppose java is a captain who throws the ball and the default exception handlers are fielders who catch that ball and return it back to the captain. But the problem is those fielders aren’t work properly so, we have to put our own fielders or handlers in the field to handle those exceptions properly. It means our exception handlers will not stop the execution of the program abruptly and give the customized message to the user so that the user can understand. Java has its own default exception handlers who handle the exception object thrown by java. But, they don’t do the work properly they stop the program execution abruptly and give the weird output to the user. However as programmer it is clearly understandable but users don’t know the technical terms and language. This is the reason why we have to do the Exception handling by using our handlers. To handle we have to put try catch block. The lines of code that may throw some exception should be put in the try block and whatever we want our exception handlers to do should be put in to the catch block. public class Exception_Demo { public static void main(String[] args) { int i = 1/0; System.out.println("After division by 0"); } Here, by doing 1/0, our program will stop abruptly. And it will give a weird error massage. Like, Exception in thread "main" java.lang.ArithmeticException: / by zero at Exception_Demo.main(Exception_Demo.java:6) But once it handles by our own handlers like, public class Try_Catch { public static void main(String[] args) { try { int i = 1/0; System.out.println("After division and inside try"); } catch (Exception e)//we can also write ArithmaticException { // TODO: handle exception System.out.println("Division by 0"); System.out.println("1 is not divide by 0,try different number"); //System.out.println(""+e); e.printStackTrace(); } System.out.println("After try catch"); } } It will not stop program abruptly and give customize message like Division by 0 1 is not divide by 0,try different number java.lang.ArithmeticException: / by zero at Try_Catch.main(Try_Catch.java:8) After try catch We used e.printStackTrace, this is will let you know the exact number of line where it found the error. Multiple catch blocks Different types of exception are subclasses of the main exception class. Depending upon the user’s input if different type of exception is occurring we need various type of catch block to handle them individually. public class Multi_Catch { public static void main(String[] args) { try { int len=args.length;//will be no of commandline arguments if(len==0) { int i=1/0; } if(len==1) { int j[]=new int[3]; j[10]=4343; } } catch (ArithmeticException e) { System.out.println("you have not enter any argument"); } catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception } catch (Exception e) { // TODO: handle exception } } In this example, if length is 0 than it will catch by ArithmeticException. Moreover, there are only 3 array are define in intj[ ]= new int[3] as soon as you try to use J[10], it will throws ArryIndexOutOfBoundException. So, program has many reasons where exception will occur and each and every exception has their own different catch block to handle it. In this example third catch block is for general used it means any type of exception can handle by this catch block because Exception is main class and it knows how to handle any type of subclass exception. So, the rule is you shouldn’t put the super class above the sub class. General thing will come at last otherwise it became a compile time error. Making customize (your own) exceptionThere are few situations that is not exception for java but it is exception for our programming purpose. For example if you want to run your program only when user gives commandline input (this is your program need which is not an exception for java itself.) so, this is the time when we manually create our own exception. When we make this kind of exception it always extends the exception class.Throw Throw keyword is used for manually throwing exception object. public class Throw_Demo { //throw keyword is used for manually throw exception object public static void main(String[] args) { No_Commandline_Exception obj = new No_Commandline_Exception(); try { throw obj; } catch (No_Commandline_Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } So, when we create our own exception and throw it, we have to create an object and then when we throw it, it should be cover with try and catch block. Throws When we define function and we don’t want to put try and catch block than we can use throws keyword. static void fun() throws No_Commandline_Exception,ArithmeticException If in a function definition checked exception is thrown and we don’t want to handle it using try and catch block than we can delegate the exception handling mechanism to the caller of the caller of the function who has to put the try and catch block. Checked and unchecked exception Unchecked exceptions are those exceptions that can be handling by java's default exception handlers. If we try to throw unchecked exception inside a function we don't need to put try and catch block nor the throws. Checked exceptions are those exceptions that can’t handle by java’s default exception handlers. When a checked exception is thrown from inside a function we are bound to put the try and catch block or the throws declaration. The difference between throw and throws:- Throw is used to manually throw exception. If the definer don’t want to handle the exception using try and catch block than definer use throws keyword to indicate the caller that you must need to put try and catch block when you call the function. In this case definer delegates the work to the caller to put try and catch. So, if definer used more than 1 exceptions after throws keyword than caller suppose to use corresponding catch block when function being called. All the custom exceptions are checked exception but there are inbuilt exception classes that are also checked. List of checked exception
List of unchecked exception
|
0 comments: