Explore model answers categorized by subjects like Java, HTML, DBMS, and more.
A Reference variable is defined as
Its a type of identifier which is signifies primitive type or an object including an array.
Its points to a location in the computer\'s memory where the object is stored.
Its a variable declaration is used to assign a variable name to an object or primitive type.
It is used in Java to reference an instance of a class.
public Access is basically use for given a authority for the packages for accessing to a class .It is using of the public keyword.
A Runtime exception is basically a type of exception.Which is not handled in our program. Normally Its indicate a program bug. Its signifies as unchecked exceptions, since the Java compiler does not force the program to handle them.
An Abstract class is type of class which is like a normal class with the difference that it contains at least one abstract method or it extends another abstract class.
It is not allowed to be instantiated. That\'s the main reason it exists is to be extended.
Thus the two conditions under which a class is and must be declared as abstract are :
- It extends another abstract class
- It declares an abstract method.
The above implies that at some point the hierarchy of abstract classes, one class must have declares an abstract method. Its contains method and variables common to all.
An Abstract method is basically a method , which method is use :
- For the deceleration. It\'s not contain the functional codes.
- An abstract method is to ensure that subclasses of this class will include an implementation of this method.
- Any concert class must implement all abstract methods it has inherited.which is class that is not abstract and therefore capable of being instantiated.
Access Modifier is basically defined as :
- The only modifier that can be applied to local variables in final.
- A top level interface can have public and abstract as access modifier
- A top level class can have public, abstract and final as access modifiers. To make the class default do not specify any access modifier.
- The string class is a final class. Final classes can improve performance as the methods are expanded inline.
- All the methods of final class are also final.
- Transient keyword can only be applied to member variables and it makes those variable non-persistable while serializing the object.
- Java interfaces cannot have transient variables.
- Volatile variables maintain a master copy in addition to the local copy of each thread and each thread has to keep its copy in sync with the local copy. They are useful to avoid concurrency problem when synchronization is not an option. They are somewhat slower.
- The only modifier that can be applied to local variables in final.
Anonymous inner classes basically a use for the modifies in the classes. Its mainly changes in the visibility of the class methods or variables or nested class.
API stands for Application programmers interface. Its mainly signifies to A set of related classes and methods.
Its method work together and provide a particular capability. Its only described that the class that are exposed to code written by others.
Arrays are basically a type of data which data implemented in the homogenous data structures in Java . Its use in the java as objects. Arrays store one or more of a specific type and provide indexed access to the store.
Automatic Variables is a type of variable. Its also called method local or stack variables.
Its declaration within the body of a function is restricted to use inside that function. This is called its scope or visibility. Such a declaration with no static or external specifier defines an automatic variable.
These are created when a function is called and are lost when it finishes its execution.
Automatic variables are variables that are declared within a method and discarded when the method has completed.
A Base class is basically a class that has been extended. If class C extends class A, class A is the base class of class C.
blocked State is type of thread ,Blocked threads consume no processor resources. Its basically a waiting for a resource, such as a lock, to become available is said to be in a blocked state.
A primitive boolean value represents only the true or false.
A Call stack is basically a method it is the list of methods that have been called in the order in which they were called. The most recently called method the is thought of as being at the top of the call stack .
Casting is the basically a conversion which is b/w one type to another type. we would like to say mainly casting is used to convert an object reference to either a subtype for example, casting an Animal reference to a Horse, but casting can also be used on primitive types to convert a larger type to a smaller type, such as from a long to an int.
Instance variable is basically a member variables, its basically defined at the class level.We have a example for the primitive instance variable which is following as :public class BirthDate {
int year; // Instance variable
public static void main(String [] args) {
BirthDate bd = new BirthDate();
bd.showYear();
}
public void showYear() {
System.out.println(\"The year is \" + year);
}
}
In this example the integer year is signifies as a class member .When the code is execute,Its gives the variable year a value of zero, the default value for primitive number instance variable.Variable Type | Default Value
-------------------------------------------------
Object reference | null(not referencing any object
--------------------------------------------------
byte, short, int, long | 0
-------------------------------------------------
float, double | 0.0
--------------------------------------------------
boolean | false
--------------------------------------------------
char | u0000
Character literals are represented by a single character in single quotes.
A char is a basically a datatype its have a 16-bit unsigned primitive data type that holds a single Unicode character.
A Class method is similar like a static method, which may be accessed directly from a class, without instantiating the class first.
Class variable is basically similar as static variable .its all property as like as static variable
A Collection is an object used to store other objects. Collections are also commonly referred to as containers.
There are Two common examples of collections there are following as :
- HashMap
- ArrayList
The collection interface s basically a public interface which is defined as common to Set and List collection classes.
Map classes : such as HashMap and Hashtable do not implement Collection, but are still considered part of the collection framework.
Constructor is the basically type of method. Which is like block of code that is called when the object is created instantiated, Mainly constructors initialize data members and acquirewhatever resources the object may require. It is the code that runs before the object can be referenced.
The continue statement is basically is a reason for the current integrations .Its mainly a type of causes the current iteration of the innermost loop to cease and the next iteration of the same loop to start if the condition of the loop is met.
When we are using the Continue statement with the for loop , that time main important thing for us is the consider of effects that the continue has on the loop iterator.
Deadlock is basically a called deadly embrace. Threads sometimes block while waiting to get a lock. It is easy to get into a situation where one thread has a lock and wants another lock that is currently owned by another thread that wants the first lock.
Deadlock is basically a problem , Its one of those problem that are difficult to cure, especially because things just stop happening and there are no friendly exception stack traces to study. They might be difficult, or even impossible, to replicate because they always depend on what many threads may be doing at a particular moment in time.
Decision Statements is basically two types , that are commonly refereed as :
if -else
switch case
When we use decision statements in our program, we are asking the program to calculate a given expression to determine which course of action is required.
A Declaration is basically a type of statement, that declares a class, interface, method,package, or variable in a source file.
A declaration can also explicitly initialize avariable by giving it a value.
default Access is basically a type of class which is a Class with default access needs no modifier preceding it in the declaration.
Default access allows other classes within the same package to havevisibility to this class.
A Derived class is classically a similar as Basic Class . Both concepts are same .That a class which is a class that extends another class. If class D extends class B, then class D derives from class B and is a derived class.
The do-while loop is basically a loop which is slightly different from the while statement in that the program execution cycle will always enter the body of a do-while at least once.
It does adhere to the rule that we do not need brackets around the body if it contains only one statement.
Encapsulation is the basically a process of data hiding.In which process grouping methods and data together and hiding them behind a public interface.
A class demonstrates good encapsulation by protecting variables with private or protected access, while providing more publicly accessible setter and/or getter methods.
Exception has two common meanings in Java.
- An Exception is an object type.
- An exception is shorthand for exceptional condition,which is an occurrence that alters the normal flow of an application.
Exception handling basically for detecting the errors , It allows developers to easily detect errors without writing special code to test return values.
Better, it lets us handle these errors in code that is nicely separated from the code that generated them and handle an entire class of errors with the same code,
It allows us to let a method defer handling its errors to a previously called method. Exception handling works by transferring execution of a program to an exception handler when an error, or exception, occurs.
Extensibility is basically a type of condition. Its a term that describes a design or code that can easily be enhanced without being rewritten.
final class is a type of class which is use for the extent, The final keyword restricts a class from being extended by another class.
If we try to extend a final class, the Java compiler will give an error.
final method is basically a method.
The final keyword applied to a method prevents the method from being overridden by a subclass.
A final variable is basically a variable which is the final keyword applied to a variable makes it impossible to reinitialize a variable once it has been assigned a value.
For primitives, this means the value may not be altered once it is initialized.
For objects, the data within the object may be modified, but the reference variable may not be changed to reference
a different object or null.
finalizer is basically a class, that\'s defined as :
Every class has a special method, called a finalizer, which is called before an object is reclaimed by the Java VM garbage collector. The JVM calls the finalizer for us as appropriate; we never call a finalizer directly. Think of thefinalizer as a friendly warning from the virtual machine.
Our finalizer should perform two tasks :
- performing whatever cleanup is appropriate to the object,
- Calling the superclass finalizer.
Finalizers are not guaranteed to be called just because an object becomes eligible for garbage collection, or before a program shuts down, so we should not rely on them.
floating-point is basically a defined as a double by default. but if we want to specify in your code a number as float, we may attach the suffixF to the number.
floating-point numbers are basically a type of no. which are defined as a number, a decimal symbol, and more numbers representing the fraction. Unless a method or class is marked with the strictfp modifier, floating-point numbers adhere to the IEEE 754 specification.
A for loop is basically a loop, Its mainly used when a program needs to iterate a section of code a known number of times. There are three main parts to a for statement.
for(int i0;i<;i++)
They are
- the declaration
- initialization of variables
- The boolean test expression and the iteration expression.
Each of the sections are separated by a semicolon.
Garbage Collection is basically a type of process , Which process by which memory allocated to an object that is no longer reachable from a live thread is reclaimed by the Java VM.
Guarded Region is basically a type of Section area , Its allows access to protected code and data without intervention from a processor\'s operating system by redefining regions of an address space with reference to gates indicating points of entry for those regions.
Section of code within a try/catch that is watched for errors to be handled by a particular group of handlers.
The HashMap class is basically as similar of the hash table, Its a equivalent to Hashtable, but something is different in hash table and hash Map class ,
It is not synchronized and it permits null values and one null key to be stored.
Heap is basically a type of structure which is manages by java , It means that Java manages memory in a structure called a heap.
Each and Every object create by java and also allocated by java in the heap, which is created at the beginning of the application and managed automatically by Java.
Hexadecimal numbers are constructed using 16 distinct symbols.
The symbols used are
> 0,
> 1,
> 2,
> 3,
> 4,
> 5,
> 6,
> 7,
> 8,
> 9,
> A,
> B,
> C,
> D,
> E,
> F.
Identifiers are basically use for the assigning the values , Its names that we assign to classes, methods, and variables.
The example Java is the programing language and all are known as its case-sensitive, which means identifiers must have consistent capitalization throughout. Identifiers can have letters and numbers, but a number may not begin the identifier name.
Most symbols are not allowed, but the dollar sign ($) and underscore (_) symbols are valid.
An If statement is basically use for the tests an expression for a boolean result.
This is achieved by using one or more of Java\'s relational operators like :
* > ,* ==, etc.
Inside the parentheses of the statement to compare two or more variables.
import statements is basically allow us to refer to classes without having to use a fully qualified name for each class.
Its mainly defines as :
- import statements do not make classes accessible;
- all classes in the classpath are accessible.
They simply allow us to type the class name in our code rather than the fully qualified name.
Inheritance is a very important concepts, Which is Object-oriented concept that provides for the reuse and modification of an existing type in such a way that many types can be manipulated as a single type. In Java, inheritance is achieved with the extends keyword.
Inner classes are basically a type of class and its follow most of the same rules as a normal class.
The main difference is an inner class is declared within the curly braces of a class or even within a method. Inner classes are also classes defined at a scope smaller than a package.
Local inner classes Member inner classes. Static inner classes are not actually inner classes, but are considered top-level nested classes.
Instance is an type of the event , In this event following as :
Once the class is instantiated.It becomes an object. A single object is referred to as an instance of the class from which it was instantiated.
Instance Variables is basically defined as :
An Instance variable is belongs to an individual object. Instance variables may be accessed from other methods in the class, or from methods in other classes depending on the access control.
Instance variables may not be accessed from static methods, however, because a static method could be invoked when no instances of the class exist.
Logically, if no instances exist, then the instance variable will also not exist, and it would be impossible to access the instance variable.
The instanceof comparison operator is basically a type of operator which is available for object variables.
The purpose of this operator is deafined as :
- To determine whether an object is of a given class or interface type 8 Glossary :
- This comparison may not be made on primitive types and will result in a compile time error if it is attempted.
An Interface defines as :
- Group of methods, or a public interface.
- Its must be implemented by any class that implements the interface.
- An interface allows an object to be treated as a type declared by the interface implemented.
An iterator basically over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:-
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved. An Iterator provides the necessary behavior to get to each element in a collection without exposing the collection itself. In classes containing and manipulating collections, It is good practice to return an iterator instead of the collection containing the elements we want to iterate over. This shields clients from internal changes to the data structures used in our classes.
A File that contains computer instructions written in the Java programming language:
- A java source file must meet strict requirements.
- The java compiler will generate errors. Source files must end with a .java extension, and there may be only one public class per source code file.
Java Virtual machine is basically a Program , Its mainly a set of programs and data structures which is used as a virtual machine model , Its interprets and also its Executes Java byte code. Its practically described the instruction set of af an instruction set of the use format .
The Java VM provides a variety of resources to the applications it is executing, including
- memory management,
- network access,
- hardware abstraction, and so on.
Because it provides a consistent environment for Java applications to run in, the Java VM is the heart of the write once run anywhere strategy that has made Java so popular.
JAVAC basically stands for the java compiler program JAVAC.
This Java compiler processes the source file to produce a bytecode file.
Keywords are basically a type of special charterer , Keyword is basically defined as in programming Language (programming) .
A reserved word used to identify a specific command, function etc. A reserved word used to identify a specific command, function etc.Its mainly special reserved words in Java that cannot be used as identifiers for classes, methods, and variables.
Local inner classes is basically a Anonymous class , Its inner classes can also be created inside code blocks, typically inside the body of a method.
A local inner class cannot have an access specifier because it isn\'t part of the outer class, but it does have access to the final variables in the current code block and all the members of the enclosing class.
Its defined basically as :
Its cannot use local variables of the method unless those variables are marked final. We can define inner classes within the scope of a method, or even smaller blocks within a method.
A local variable is a variable that is given local scope. Such a variable is accessible only from the function or block in which it is declared.
Local variables are contrasted with global variables. local variable is basically a variable , which is use for the declaration , Its declared within a method. These are also known as automatic variables.
Local variables, including primitives, must be initialized before we attempt to use them though not necessarily on the same line of code.
Members are defined as :
- Elements of a class
- Including methods
- Variables
- Nested classes
A Method is the basically a type of the source code its mainly use :
- For the specific function has a name,
- May be passed parameters.
- Its also may return a result.
- Methods are found only with in classes.
A modifier is basically a type of keyword, It is basically a modifies a different type of elements :
- class
- method
- variable declaration
This Method is the basically a instance method and its also the wait method is using like this of an object. We can see that both are use in same way that :
Every object has a lock .The list of threads is in Every object that are waiting for a signal related to the object.
The wait() method of the object is executing on this list of threads. That time It does not execute any further instructions until some other thread calls the notify() method of the same object.
Object is basically blue print of a class at a runtime. It means Once the class is instantiated it becomes an object
Overloaded method is basically type of method which is overloaded when we have a multiple methods in the same class which classes names are same but with different parameter lists.
Overridden methods is basically a type of methods, Which is basically method in the parent and subclasses with the same name, parameter list, and return type are overridden.
package are the container for classes.Its defines a logical boundary, It is used to resolve the naming convention issues for classes. The name of the package must reflect the directory structure used to store the classes in our package.
A parent class is a class which is derived from the another class.
A primitive literal is basically represents a primitive data types , it is a type of source code.
private members are basically a members of a class , When its declared to the any class that time it cannot be accessed by any class other than the class.
primitives are basically as a fundamental concepts its mainly defined as a :
- Instruction
- Operation
- Statement
They must be initialized before we attempt to use them or Its not necessarily onthe same line of code.
The transient keyword is basically use for the indicating the object stream data , Its a type of variable,there is not be required to know anything about transient for the exam, other than that it is a keyword that can be applied only to variables.
public members basically a type of methods or variables.When its declared as a public then we can say its a public members . It means all classes or packages, those are belongs to this methods or variables have a authority to access the members .
shift operators is basically for the shifting the bits of a number, Which is shift to the right or left ans also producing a new number. Its used on integer types only.
<<
>>
A StoredMap Interface is very similar as a data structure.But its little bit different with DS , Its objects are stored in ascending order according to their keys.
That\'s are following as :
- Here no duplicate keys and
- The objects themselves may be duplicated.
- The key may not be a null value. That\'s the main difference.
A Source file is a type of document file or plaintext file.Its basically use for containing our Java code. Its only have one public class or interface and Its also have a unlimited number of default classes or interfaces defined within it, and source file have a very important thing is filename should be same as the public class name.
If we could print out the state of the call stack at any given time, We would reduce a stack trace.
Static nested classes is basically a very similar as a classes , Its simple form of inner classes. Its behavior as same as top-level classes but something is different :
- Its classes are defined as within the scope of another class, Which name is like enclosing class.
- Its have not any implicit references to instances of the enclosing class.
- It can access only static members and methods of the enclosing class.
- These classes are often used to implement small helper classes such as iterators.
Static methods are basically a method which declared by the method keywords.
Which is belonging a to an entire class and also opposed to belonging to an instances. but something is different in the class property and static method property.
A class method may be accessed directly from a class, without instantiating the class first.
static variable is a similar like a class variable. Its defined as :
- Its similar as static method.
- Its accessed from a class directly, even though the class has not been instantiated.
- Its value will be the same in every instance of the class.
A string literal is a source code representation of a value of a string.
String object basically defined as :
Its provides string manipulation capabilities.
- The String class is final.
- Its may not be subclassed.
A super class is basically a class which is use for the one or other class are derived. Now a days we can see that the what\'s says Object technology : A high-level class that passes attributes and methods or data and processing down the hierarchy to subclasses.
Switch statement is basically like a Expression Its mainly use for only evaluate to an integral primitive type that can be implicitly cast to an int. These types are following as :
- byte
- short
- char
- int
The switch can only check for an equality. That\'s the main means for other relational operators like the greater than sign are rendered unusable.
The Synchronized method is basically use a synchronized keyword , Its mainly use for the indicating that a method may be accessed by only one thread at a time.
Thread is basically defined as :
- Its an independent line of execution.
- Its a type of mini program .
- Multiple line of execution method is also used in multiple threads.
- Its executes instructions, any variables that are declares within the method, Its also called automatic variables.
- Its stored in a private area of memory, which area is protected area and other threads cannot access. This allows any other thread to execute the same method on the same object at the same time without having its automatic variables unexpectedly modified.
time slicing is basically a technique ,Its use for the thread execution, I this scheme for scheduling thread execution.
Variable access is basically a describe to the ability of one class to read or alter if it is not final, a variable in another class.
Visibility is basically a method which is use for the accessibility ,and Its instance variables to other classes and packages.
When we are using or implementing a class, We determine our methods and instance variables, Its basically a visibility keywords as :
- public
- protected
- package
- default
if statement is basically using for the true and false result .here we have a normal format :
if (booleanExpression) {
System.out.println(\"Inside if statement\");
}
In this expression we are checking True and false .The following code demonstrates a legal if
statement:if (x > 3) {
System.out.println(\"x is greater than 3\");
} else {
System.out.println(\"x is not greater than 3\");
}
else opton is not mandatory .that we also wrint in this term ..........
if (x > 3) {
y = 2;
}
z += 8;
a = y + x;
if statement only use for the boolean , any expressions that something explaining is down the boolean is fine .int y = 5;
int x = 2;
if ((((x > 3) && (y < 2)) | doStuff()))
System.out.print(\"true\");
}
Ouput
true
We can see in the above code .If both (x > 3) and (y < 2) are true, or if the result of doStuff() is true, then print true S.o basically, if just doStuff() alone is true, we\'ll still get true. If doStuff() is false, though, then both (x > 3)
and (y < 2) will have to be true in order to print true.
The above code is is even more complex if we leave off one set of parentheses
as follows,int y = 5;
int x = 2;
if (((x > 3) && (y < 2) | doStuff()))
System.out.print(\"true\");
}
Many of the ways are the simulate the values of the use of the multiple if statements is with the switch statement.int x = 3;
if(x == 1) {
System.out.println(\"x equals 1\");
}
else if(x == 2) {
System.out.println(\"x equals 2\");
}
else if(x == 3) {
System.out.println(\"x equals 3\");
}
else {
System.out.println(\"No idea what x is\");
}
--------------------------------------------------
Illegal Arguments to if | Legal Arguments to if--------------------------------------------------
int x = 1; | int x = 1;
if (x) { } if (x == 1) { }
--------------------------------------------------
if (0) { } | if (false)
--------------------------------------------------
if (x = 6) | if (x == 6)
--------------------------------------------------
Here same functionality represented in a switch construct :
int x = 3;
switch (x) {
case 1:
System.out.println(\"x is equal to 1\");
break;
case 2:
System.out.println(\"x is equal to 2\");
break;
case 3:
System.out.println(\"x is equal to 3\");
break;
default:
System.out.println(\"Still no idea what x is\");
}
switch case is only the type of case which can evaluate is the primitive int! that means only variables and valuables that can be automatically promoted , which is also called implicitly cast to an int are acceptable.
byte
short
char
int
The only argument a case can evaluate is one of the same type as switch can use, with one additional and big constraint: the case argument must be final! The case argument has to be resolved at compile time, so that means we can use only a literal or final variable.
String s = \"xyz\";
switch (s.length()) {
case 1:
System.out.println(\"length is one\");
break;
case 2:
System.out.println(\"length is two\");
break;
case 3:
System.out.println(\"length is three\");
break;
default:
System.out.println(\"no match\");
}
Above statement is uses final variable in a case statementfinal int one = 1;
final int two = 2;
int x = 1;
switch (x) {
case one: System.out.println(\"one\");
break;
case two: System.out.println(\"two\");
break;
}
When the program execute with the break statement, it will immediately move out of the switch block to the next statement after the switch. for the example we have a code :
int x = 1;
switch(x) {
case 1: System.out.println(\"x is one\");
case 2: System.out.println(\"x is two\");
case 3: System.out.println(\"x is three\");
}
System.out.println(\"out of the switch\");
The code will print the following:
x is one
x is two
x is three
out of the switch
We\'ll insert insert a break into each case as follows :int x = 1;
switch(x) {
case 1: {
System.out.println(\"x is one\");
break;
}
case 2: {
System.out.println(\"x is two\");
break;
}
case 3: {
System.out.println(\"x is two\");
break;
}
}
System.out.println(\"out of the switch\");
Running the preceding code, now that we\'ve added the break statements, will print :
x is one
out of the switch
Another way to think of this fall-through logic is shown in the following code:int x = xx;
switch (x) {
case 2:
case 4:
case 6:
case 8:
case 10: {
System.out.println(\"x is an even number\");
break;
}
}
If we would like to to no changes is there . we can see the default case ,which is the keyword whose use fr the completely diff purpose.
The only change we need to make is to add the default case to the preceding code:int x = someNumberBetweenOneAndTen;
switch (x) {
case 2:
case 4:
case 6:
case 8:
case 10: {
System.out.println(\"x is an even number\");
break;
}
default: System.out.println(\"x is an odd number\");
}
Variable keyword is basically a keyword, Which is special type of reference variable, That are following as :
Super It is an reference variable , Its referring to the immediate super class.
This It is an reference variable , Its referring to the current instance of an object.
The following are keywords used in error handling
Catch Declares the block of code used to handle an exception.
Finally Its a Block of code, Its usually following a try-catch statement, Its implemented no matter what program flow occurs when dealing with an exception.
Throw Its use to pass an exception up to the method that called this method.
Throws Its mainly indicates the method will pass an exception to the method that called it.
Try It is an Block of code that will be tried, but which may cause an exception.
Assert It is mainly using for the evaluates a conditional expression to verify the programmer assumption.
Package control is basically a keywords Its mainly use for package :
Import This statement basically use for the import packages or classes into code.
Package That packages use to which package all classes in a source file belong.
In the java primitives are many keywords, which are there following as :
boolean : Its value 1 or 0 which is indicates only true or false.
byte : Its signifies signed, its an 8-bit integer.
char : Its signifies 16-bit unsigned, A single Unicode character.
double : Its signifies signed, A 64-bit floating-point number.
float : Its signifies signed, A 32-bit floating-point number.
int : Its signifies signed, A 32-bit integer.
long : Its signifies signed , A 64-bit integer.
short : Its signifies signed, A 16-bit integer.
There are many modifiers are there , that\'s also are class , method and variable modifiers . which is following as :
abstract : It is used for declaration a class that cannot be instantiated.A Method : It should be implemented by a nonabstract subclass.
class : this keyword using for specify a class.
extends : its using for the indicating the superclass that a subclass is extending.
final : Makes it impossible to extend a class, override a method, or reinitialize a variable.
implements : Used to indicate the interfaces that a class will implement.
interface : Keyword used to specify an interface.
native : Indicates a method is written in a platform-dependent language,such as C.
new : Used to instantiate an object by invoking the constructor.
The following are keywords used to control the flow through a block of code :
break : Its use in the block of code .
case : Its implement in a block of code, dependent on what the switch tests for.
continue : When its working in the block code its Stops the rest of the code following this statement from executing in a loop and then begins the next iteration of the loop.
default : Its implemented this block of code if none of the switch-case statements match.
do : Its implement a block of code one time, then, in conjunction with the while statement, It is executing a test to determine whether the block should be executed again.
else : Its implement an alternate block of code if an if test is false.
for : Its using perform a conditional loop for a block of code.
if : Its executing logical test for true or false.
instanceof : It is use fr the determining an object is an instance of a class, superclass, or interface.
return : When its use in the programs its use for the returns from a method without executing any code that follows the statement can optionally return a variable.
The void keyword is basically used only in the return value place holder of a method declaration.
void Its mainly Indicates no return type for a method.
All primitive data types is basically have State the range and literal values for String are also declare and all primitive types using all permitted formats, bases, and representations.
As we know that the ranges of all primitive data types , It includes byte , short , int, long,float, double,boolean,and char.
Its basically long primitive have a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
All primitive data types and literals data types are effects to go fr the ranges and we can also know that the no types both integer and floating-point types are all signed data types.
All the primitive data types are signed, its means that in java programming language all are primitives can be negative or positive.
If the left most bit is used to represent a the sign significance, Where we use 1 or 0. 1 means negative, and 0 means positive.negative also shows the glass half empty and positive sign also shows the glass half full.in the primitive data types rest of bits represent the values, like two\'s complement notation.Its also shows the sizes and ranges.in primitive data types have a many ranges half of these are negative and half -1 are positive.
When we would like to calculate the negative range then we use formula -: -2^bits-1
When we would like to calculate the positive range then we use formula -: 2^(bits-1)-1
Here boolean types have a no ranges : A boolean type basically represents true or false only .|Type|Bits|Bytes|Minimum Range|Maximum Range
---------------------------------------------
|byte|8 |1 |-2^7 |2^7\'1
---------------------------------------------
|short|16 |2 |-2^15 |2^15\'1
---------------------------------------------
|int |32 |4 |-2^31 |2^31\'1
----------------------------------------------
|long |64 |8 |-2^63 |2^63\'1
----------------------------------------------
|float|32 |4 |Not needed |Not needed
-----------------------------------------------
|double|64|8 |Not needed |Not needed
primitive literal values is very similar as a source code representation of the primitive data types .In the other word we can say that an integer , floating point number , boolean , or character.We execute in the writing code .We have examples are there :
\'d\' // char literal
52 // int literal
false // boolean literal
2876678.543 // double literal
Integer Literals are basically we have three ways for representation :
- Decimal (base 10)
- Octal (base 8)
- Hexadecimal (base 16)
In many places integer literals use decimal representations but in case many places use octal or hexa decimal .We\'ll use in the real world we use octal.
Decimal integer s basically a very simple , Its have not any prefix or grade, and no use for hex check box. its represented without any prefix. that are following as :int length = 295;
Octal Integer is basically use for only 0 to 7. Its represented an integer in octal form by placing zero in front of the number in java language .
This is follows as :class Octal {
public static void main(String [] args) {
int five = 06; // Equal to decimal 6
int seven = 07; // Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011; // Equal to decimal 9
System.out.println(\"Octal 010 = \" + eight);
}
}
Hexa decimal number is basically stands for in short Hex. Its only constructed using 16 district symbols . because 10 to 15 numbers have a alphabetic characters to represent these digits.
Hexadecimal counting from 0 to 15 looks like0
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
All of the hexa decimal assignments are legal :
class HexTest {
public static void main (String [] args) {
int x = 0X0001;
int y = 0x7fffffff;
int z = 0xDeadCafe;
System.out.println(\"x = \" + x + \" y = \" + y + \" z = \" + z);
}
}
Running HexTest produces the following output :x = 1
y = 2147483647
z = -559035650
Floating point literals basically a use fr the floating point are defined as number , decimal symbol, and more number representing the fraction.
double d = 2.2;
In this example ,
The no. 2.2, That\'s the literal values.by default its defined as : double(64-bits)
and also variable of type : float (32 bits)
And its must be attach the suffix F or f to the number. F suffix is basically use for the compiler.float M = 4.5; // Compiler error, possible loss of precision
float n = 4.5F; // OK; has the suffix \"F\"
Boolean literals are the basically a similar as source code , its mainly use for the representation for boolean values and we also know as the boolean values are only signifies the true and false .
Its happy only in java language but in other language its not happening as such . java language is the different form other language .boolean t = true; // Legal
boolean f = 0; // Compiler error!
Character literals is basically use for the represent only the single Character for a single quotes.char a = \'a\';
char b = \'@\';
In the Character literals have a many facilities in the source code .We can also use to the Unicode with Character literals . but we must be mentioned the Unicode notation of prefix the values the u as follows :char letterN = \'u004E\'; // The letter \'N\'
We can also use in the new Character like :
linefeed,
Newline,
Horizontal tab,
Backspace, and
Double and
Single quotes.
char c = \'\"\'; // A double quote
char d = \'n\'; // A newline
String literal is basically a source code. Which is representation of the string object. We can defined in the two ways of string literals :String s = \"Serah Desuja\";
System.out.println(\"Serah\" + \" Desuja\");
We also know as the String are not the primitives , Its includes section, Because its mainly use to represent as a literals . And we can also says : \" typed directly into code \"
In the java language Array is basically a objects , Which object mainly use for the store the variables , who are the same type of variables.
Array also be a object on the heap , its can only handle primitive elements, also handle to the object references.for the array we must know three things these are following as :
- How to make an array reference variable (declare)
- How to make an array object (construct)
- How to populate the array with elements (initialize)
Array declaration is basically by stating the type of element the array with hold , which can be primitive or an object also .which is followed to be square bracket to the left or right of the identifiers,
Declaring an Array of Primitives :int[] key; // Square brackets before name (recommended)
int key []; // Square brackets after name (legal but less readable)
Declaring an Array of Object References :Thread[] threads; // Recommended
Thread threads []; // Legal but less readable
When we would like to declare a reference , We should have always in our mind, when our declaration is complete we should put the array bracket . and also put after identifier.because if we don\'t put the bracket then anyone reading the code .
for example : key is a reference to an int array object, and not an int primitive.
We can also declare multidimensional arrays , Which is in fact arrays on arrays , That are following as :String[][][] name;
String[] email[];
Construct an array is basically means the create if an array object , Which object create in the heap. We can also say like they \"doing a new on the array type\" when we construct the array we must mentioned the size of the array because java would like to know how much space to allocate on the heap, And also know that the array will hold how many size of the array is the number of elements. Array constructing in a two ways :
Constructing One-Dimensional Arrays
In the one-dimensional arrays is most straight forward way to constructing the array for using the new keyword .and in the one dimensional array bracket signifies array holding how many elements of that type. for the int type we have a example which is shown as :int[] testScores; // Declares the array of ints
testScores = new int[4]; //constructs an array and assigns it
//the testScores variable
We can also declare and construct an array in one statement , which is following as :int[] testScores = new int[18];
That single statement also given as a same result which is given by the upper two statements .Arrays of object type is also constructed in the same way :Thread[] threads = new Thread[6];
The main point or key point is that : Thread constructor is not being invoked . its not creating the thread instance . Its use for the single thread array object.
Constructing Multidimensional Arrays
Multidimentional arrays are basically a simply arrays of arrays . that\'s y we can use the two denominational arrays of type int , Its really object of type int array (INt[]). With its also holding the another array and each element also use the int array .and second dimension which holds the actual int primitives .
We have a example for the int type :int[][] ratings = new int[3][];
Initializing an array means that the something insert in the array . something means its a technical term in the array , its basically a array elements which is similar as a primitive values like :
2,a, false, etc.
Here array use the objects , which is signifies by the reference variables in the array. array never holds the objects , but instead holds a reference to the object. right now we are discussing about array so we have a one example for the array an array of five strings, we can also say an array of five references to String objects.
When we used to the individual elements in the array , it can be accessed with an index number. the index no is 0 to 9 only . we have a some example :
Here We have one array object on the heap, We have to create a array of three animals:Animal [] pets = new Animal[3];
We have a three null references of type animal , but most imp thing is we don\'t have any animal objects.now we can create a some animal object and assigned to the index position an the index by pets.
pets[0] = new Animal();
pets[1] = new Animal();
pets[2] = new Animal();
Now we have a three animal objects and its assigned in the index of pets .
Arrays objects are basically a single public variable length .which is gives us the no of elements in the array.The last index values always less than the length .
Its basic formula that :
Value of last index = length - 1 .
for the example if the length of an array is 4 then the index value are 0 to 3 .Animal[] myAnimal = new Animal[6]; // creates an array of 6 Animal references
for (int x = 0; x < myAnimal.length; x++)
{
myAnimals[x] = new Animal(); // assign a new Animal to the index position x
}
The Length variables signifies basically how many elements the array holds,but its not signifies those elements have been initialized.
We have a two diff array-specific syntax shortcuts:
- Initialize
- Construct
We can do the both steps in the single statements .Firstly use to declare,create,and initialize in one statement :
- int x = 9;
- int[] dots = {3,6,x,8};
Line 2 is preceding code , it does four things :
- Declares an int array reference variable named dots.
- Creates an int array with a length of four (four elements).
- Populates the elements with the values 3, 6, 9, and 8.
- Assigns the new array object to the reference variable dots.
The size of the length of the array is compute by the no of item b/w comma-separated curly braces. The code is functionally equivalent to the following longer code:int[] dots;
dots = new int[4];
int x = 9;
dots[0] = 3;
dots[1] = 6;
dots[2] = x;
dots[3] = 8;
Its the second short cut for the array specific syntax, that called as anonymous array creation. its used to construct ans initializing an anonymous array .Its use for the assigning to the array , which is already declared in the reference variable.int[] t;
t= new int[] {4,7,2};
Array type primitives is basically which array who accept any value , which can be promoted implicitly to the declare type of the array .that have that many rules of the promotions .int array can hold any value which is fit for the 32-bit int variable. and also its the code is legal .that are following as :int[] weightList = new int[5];
byte b = 4;
char c = \'c\';
short s = 7;
weightList[0] = b; // OK, byte is smaller than int
weightlist[1] = c; // OK, char is smaller than int
weightList[2] = s; // OK, short is smaller than int
If we are declare array type in a class the we can put that all objects in the any sub class of the declared type in t the array .for the example Honda is the sub class of the Car,we can put the both Honda object and car object in to the array as follows :class Animal {}
class Cat extends Animal {}
class Horse extends Animal {}
class Dog extends Animal {}
Car [] myAnimal = {new Cat(), new Horse(), new Dog()};
The element in the Animal array is nothing more than Animal reference variable .so we can assign to the anything to the Animal reference variable can be legally assigned to a Animal array element.
If We declare an array in the interface type. We have a code which is explain to the use of interface as an array type :interface Sporty {
void beSporty();
}class Ferrari extends Car implements Sporty {
public void beSporty() {
// implement cool sporty method in a Ferrari-specific way
}
}class RacingFlats extends AthleticShoe implements Sporty {
public void beSporty() {
..
// implement cool sporty method in a RacingShoe-specific way
}
}class GolfClub { }
class TestSportyThings {
public static void main (String [] args) {
Sporty[] sportyThings = new Sporty [3];
sportyThings[0] = new Ferrari(); // OK, Ferrari implements Sporty
sportyThings[1] = new RacingFlats();
// OK, RacingFlats implements Sporty
sportyThings[2] = new GolfClub();
// Not OK; GolfClub does not implement Sporty
// I don\'t care what anyone says
}
}
In the one dimensional array we assigns to the array references to recognize legal and illegal assignments for array reference variables.Here Its references to a array objects.
For the example: if we declare to the int array , in the reference variable we declared can we reassigned to any int array, but its also possible that we cant reassign which is not int array .and its also include an int array .here all arrays are object.that\'s why int array reference cant signifies to an int primitive ,Some codes are following here which is mentioned about legal and illegal assignments for primitive arrays :int[] splats;
int[] dats = new int[4];
char[] letters = new char[5];
splats = dats; // OK, dats refers to an int array
splats = letters; // NOT OK, letters refers to a char array
When we assigning an array to a array reference which is already previous declared in the index , The array we were assigning must be a same dimension as the reference we were assign it to .
Example : 2-dimensional array of int arrays cannot be assigned to a regular int array reference which is shows in this code :int[] blots;
int[][] squeegees = new int[3][];
blots = squeegees; // NOT OK, squeegees is a two-d array of int arrays
int[] blocks = new int[6];
blots = blocks; // OK, blocks is an int array
When we use to the assignment arrays using difference dimensions the we must pay particular attention as we see in this code :int[][] books = new int[3][];
int[] numbers = new int[6];
int aNumber = 7;
books[0] = aNumber; //NOT OK, expecting an int array instead of an int
books[0] = numbers; //OK, numbers is an int array
When we are using uninitialized variables or unassigned variables then we must know about what type of variable or what type of array we we are dealing with primitive or objects .because that time we can get diff behavior. but the java gives us a option of initializing a declared variable or leaving it uninitialized. And our behavior also depend on the variable or level at which we are declaring our variable.right now we have a two variable which are using right now .
- Instance variable
- Local variable
Instance variable is basically declared with in the class but outside any method or constructor. But in the case of Local variable its declared with in the method or in the argument list of the method.
In the Object Reference instance Variables are very difference , we can see in this code :public class Book {
private String title;
public String getTitle() {
return title;
}
public static void main(String [] args) {
Book b = new Book();
System.out.println(\"The title is \" + b.getTitle());
}
}
The output of this code is :
The title is null
In this output title is not a explicitly initialized with a string assignment, so the instance variable value is null.
We know that Array is a type of object. its also declared but not explicitly initialized for the value of Null.just as other object reference instance variable.Here most imp line is \" Array elements are always always always given default values, regardless of where the array itself is declared or instantiated\".
When we would like to initialize an array and that time object reference elements value is equal to null.public class BirthDays {
static int [] year = new int[100];
public static void main(String [] args) {
for(int i=0;i<100;i++)
System.out.println(\"year[\" + i + \"] = \" + year[i]);
}
}
Local Primitive is basically for the time travel simulator,We have code in which year is a integer which is signifies as an automatic variable because it is with in the curly braces of a method.public class TimeTravel {
public static void main(String [] args) {
int year = 2050;
System.out.println(\"The year is \" + year);
}
}
Objects basically also behave differently when It is declared within a method rather than as instance
variables.
When its with instance variable object references we can got that time its with leaving an object reference uninitialized,and also that time when we reach the code its not null.
But here most imp thing is a null reference is not the same as an uninitialized reference. we have a example where compiler complain about the following code :import java.util.Date;
public class TimeTravel {
public static void main(String [] args) {
Date date;
if (date == null)
System.out.println(\"date is null\");
}
}
When it is complile we got these type of errors :
%javac TimeTravel.java
TimeTravel.java:5: Variable date may not have been initialized.
If (date == null)
1 error
&
Local arrays basically similar as a object reference,when we declared any array with in a method must be assigned a value before using it.
It means we must declare the array and constructed it In the Local array the most imp thing is array elements are given their default values (0, false, null, u0000, etc.) regardless of whether the array is declared as an instance or local variable.
Command Line Argument is working similar as all other arrays. The main method is called firstly one the JVM invokes , it must be take a String array parameter.class TestMain {
public static void main (String [] args) {
System.out.println(\"First arg is \" + args[0]);
}
}
When we invoked command line :
%java TestMain Hello
output : First arg is Hello
main imp thing must be in mind when we use the command line argument .
- The length of the args array will always be equal to the number of command-line arguments.
- args.length is one, meaning there is one element in the array, and it is at index zero.
- length-1, you\'ll get an ArrayIndexOutOfBoundsException.
The following code is an example of a main method expecting three arguments :public static void main (String [] args) {
if (args.length < 3) {
System.out.println(\"Usage: [name] [social security #]
//[IQ] Try again when you have a clue\");
}
}
Declare class basically a nested class , its also a method , We can also say instance variable and static variables automatic variables also.These are variables making approximately use of all permitted modifiers.modifiers are like :
- Public
- Final
- Static
- Abstract
When we are using java language the in this language we must use classes .And when we use classes the we should be use variables and methods also .Here three methods are there Which is following as :
Public : method can be accessed from code running anywhere in our application.
Private : though, and it vanishes from everyone\'s radar.
When we would like to declare the class and modifiers it then we use nested or inner class . some rules are there :
- each source code file have a one public class only.
- file name and class name should be same .
- package should be first line in the source code if class is a part of package .
- import and package statements apply to all classes within a source code file.
Modifiers fall into two categories :
- Access modifiers: public, protected, private
- Non-access modifiers (including strictfp, final, and abstract.
When one class access to the another class , It means first class can do one of three things :
- Create an instance of class B
- Extend class B (in other words, become a subclass of class B).
- Access certain methods and variables within class B, depending on the access control of those methods and variables.
A class which is in the default access no modifiers are preceding in the deceleration.Its mostly implements thing is
A class with default access can be seen only by classes within the same package.
A class declarations basically use ith the public keyword gives all classes from all packages access to the public class.if all classes are JU. JU stands for the JAVA UNIVERSE. its access to a public class.
If we want to be make a code work , we need to add the keyword public in front of the super class declaration :package cert;
public class Beverage {
}
A class declaration basically a use to the keyword like :
final
abstract
or
strictfp.
All are modifiers use for the addition to access control is on the class .declare class is basically use for the public and also use final .but we cant allow to access always mix nonabstract modifiers.we can use only strictfp in combination with abstract or final.but we never ever mark it .
We never can know how strictfp works.
final class basically used when we are working n the class declaration that time we are using the final keyword when we would like to show the \" the class can\'t be subclasses\" .
We also can say in different terms: no other class can ever extend (inherit from) a final class, and any attempts to do so will give us a compiler error.
We should make a final class only we we need an absolute guarantee that none of the methods in that class will ever be overridden.
Abstract class is basically never be instantiated. its mainly purpose of the mission of life .that\'s the soul purpose of them .
We have a code for the abstract class :
abstract class Car {
private double price;
private Color carColor;
private String model;
private String year;
public abstract void goFast();
public abstract void goUpHill();
public abstract void impressNeighbors();
// Additional, important, and serious code goes here
}
When we execute this code its working fine .but when ever we instantiated car in th another body of code its gives us a compiler error :
AnotherClass.java:7: class Car is an abstract
class. It can\'t be instantiated.
Car x = new Car();
1 error
we have a example . there are 1 of abstract super class which name is fruits and a concrete subclass which name is Apple. Super class which is belonging to a package.
We have a method which is following as :
Create the superclass as follows :
package food;
public abstract class Fruit{ /* any code you want */}
Create the subclass in a separate file as follows:
import food.Fruit;
class Apple extends Fruit{ /* any code you want */}
Create a directory called food off the directory in your class path setting.
Attempt to compile the two files. If we want to use the Apple class, make sure we place the Fruit.class file in the food sub-directory.
We are known as what the mean to use a modifier in a class declaration and now we would like to go fr the modify a method or variable declaration.
The methods and instance or non local variables are also called as members .we can modify a member with both access or non access modifiers.
Member access allowed basically because the methods or variables members are usually access control are same .Here ewe have two or four access control levels :
- public
- protected
- default
- private
Default protected is basically use for when we get only we don\'t type an access modifier in the member deceleration .
We need to know some important issues :
Whether method code in one class can access a member of another class.
Whether a subclass can inherit a member of its superclass.
class Zoo {
public String coolMethod() {
return \"Wow baby\";
}
}
class Moo {
public void useAZoo() {
Zoo z = new Zoo();
// If the preceding line compiles Moo has access
// to the Zoo class
// But does it have access to the coolMethod()?
System.out.println(\"A Zoo says, \" + z.coolMethod());
// The preceding line works because Moo can access the
// public method
}
}
The second type is basically for the super class an subclass can access through inheritance.
class Zoo {
public String coolMethod() {
return \"Wow baby\";
}
}
class Moo extends Zoo {
public void useMyCoolMethod() {
// Does an instance of Moo inherit the coolMethod()?
System.out.println(\"Moo says, \" + this.coolMethod());
// The preceding line works because Moo can inherit the public method
// Can an instance of Moo invoke coolMethod() on an instance of Zoo?
Zoo z = new Zoo();
System.out.println(\"Zoo says, \" + z.coolMethod());
// coolMethod() is public, so Moo can invoke it on a Foo reference
}
}
public members is used when the method or variable member is declared public . ts means all other classes reardless of the packages they belong to the access .we can see the following code :
package book;
import cert.*; // Import all classes in the cert package
class Goo {
public static void main(String [] args) {
Sludge o = new Sludge();
o.testIt();
}
}
Now we can see rhe second file :
package cert;
public class Sludge {
public void testIt() {
System.out.println(\"sludge\");
}
}
We can see in the code Goo and Sludge are in different packages.Goo packages basically use for the invoke the method in Sludge without problems because both the Sludge class and its testIt() method are marked public.
private members invoked when members marked in the variables that its a private and also cant be access by code with difference users.package cert;
public class Roo {
private String doRooThings() {
// imagine the fun code that goes here, but only the Roo class knows
}
}
access modifiers also use with the local variables like :
class Foo {
void doStuff() {
private int x = 7;
this.doMore(x);
}
}
Here we happy local variable Final in the terms of access modifiers.
Visibility |Public|Protected|Default|Private
---------------------------------------------------
From the same class |yes |yes |yes |yes
---------------------------------------------------
From any class in the same package |Yes|Yes|Yes|No
--------------------------------------------------
From any non-subclass class outside the package |Yes|No|NO|NO
---------------------------------------------------
From a subclass in the same package |Yes|Yes|Yes|No
--------------------------------------------------
From a subclass outside the same package |Yes|Yes|No|No
We have already discussing about the access member, which is signifies to code can be invoke the method one class to another class. here we can use to the some there looks like :
- transient
- synchronized
- native
- strictfp
But preferably we are using static.in this function first at modifiers applied to methods, we are using modifiers applied to instance variable.
In a final method we use final keyword, its prevents method from being overridden in a subclass, And its used to enforce for API functionality of a method. We have a example the Thread class have a method which is called isAlive() that checks whether a thread is still active.if we would like to extend the thread class , and also we can correctly implement this method themselves.
A typical final method declaration looks like this
class SuperClass{
public final void showSample() {
System.out.println(\"One thing.\");
}
}
Method argument are basically a type of variable declaration , which is appear in b/w the parenthesis in the method declaration ,A typical method declaration are following as :public Record getRecord(int fileNumber, int recordNumber) {}
method argument is similarity as a local variables . in the above code we can see that fileNumber and recordNumber both follows rules of local variables .e can also have a modifier final :public Record getRecord(int fileNumber, final int recordNumber) {}
Synchronized method is basically a use synchronized keyword.Its indicate the method only 1 time accessed to a thread at a same time.A typical synchronized declaration looks like this :
public synchronized Record retrieveUserInfo(int id) { }
We know that synchronized modifier can be similar as four access control levels and we can also combine synchronized with final,but never with abstract.
The native modifier basically use for the indication. Its indicate the method is implemented in a platform-dependent language, native can never be combined with abstract, and native can be applied only to methods not classes, not variables, just methods.
Strictfp methods use basically as a class modifier, but even we don\'t need to declare a class as strictfp,
We\'ll need to have IEEE754 standard : If we need something to help us fall asleep. however, we don\'t need to know anything about strictfp other than what it\'s used for, that it can modify a class or non abstract method declaration, and that a variable can never be declared strictfp.
Assignment Operators is basically a assigning a value seems straightforward ,primitive and reference variable assignments, nut before we wanna know about what\'s we have in the back up and peek inside of a variable.
Variables are just bit holders, with a designated type. and we also can have an int holder, a double holder, a Button holder, and even a String[] holder,A reference variable bit holder contains bits representing a way to get to the object.
All we can say for sure is that the variable\'s value is not the object, but rather a value representing a specific object on the heap.
Java operator is basically a use for the determine the applying for the any operator to operand of any type.class, scope, or accessibility, or any combination of these. Its produce new values, which is from one or more operands and also we find the output is in the boolean or numeric value.one operator that comes overloaded out of the box:
If applied to aString, the + operator concatenates the right-hand operand to the operand on the left.
main() is the static its Void return Type.Its have a single stirng array argument,its name as a flexible but args name is use in the convention.themain() method is public.impropper main() declaration is create an runtime error not the compile error.
Its a interface , which is single method for the implement : public void run {}.
Primitive assignment is basically use for assigning the value like equal(=) sign is used for the assigning a value to a variable and it\'s cleverly named the assignment operator. These compound assignment operators have a couple of special properties we\'ll look at in this section.
Compound Assignment Operators :
= | *= | /= | %= |
----------------------------------------------
+= | -= | <<= | >>= |
----------------------------------------------
>>>= | &= | ^= | |= |
----------------------------------------------
We can assign a primitive variable using a literal or the result of an expression.
int x = 7; // literal assignment
int y = x + 2; // assignment with an expression (including a literal)
int z = x * y; // assignment with an expression
The compiler automatically narrows the literal value to a byte. In other words, the compiler puts in the cast. The preceding code is identical to the
following:
byte b = (byte) 27; // Explicitly cast the int literal to a byte
Divide a short by a byte and you\'ll
get an int. OK, now we\'re at the weird part.
byte b = 3; // No problem, 3 fits in a byte
byte c = 8; // No problem, 8 fits in a byte
byte d = b + c; // Should be no problem, sum of the two bytes
// fits in a byte
The last line won\'t compile! You\'ll get the following error:
TestBytes.java:5: possible loss of precision
found : int
required: byte
byte c = a + b;
^
Floating-point numbers slightly diff assignment behavior than integer types.We know that the every floating-point literal is implicitly a double (64 bits), not a float. If we try to assign a double to a float, the compiler knows we don\'t have enough room in a 32-bit float container to hold the precision of a 64-bit double,float f = 32.3;
In order to assign a floating-point literal to a float variable,The following assignments will compile:float f = (float) 32.3;
float g = 32.3f;
float h = 32.3F;
If we trying to assign a literal values then we know that the compilers should that time too big to fit into the variable.byte a = 128; // byte can only hold up to 127
The preceding code gives us this error:
TestBytes.java:5: possible loss of precisionfound : int
required: byte
byte a = 128;
We can fix it with a cast:
byte a = (byte) 128;
When we are using a primitive , java simply drop the higher-order bits that won\'t fit.we can also say it loses all the bits to the left of the bits we\'re narrowing to.
We must use an explicit cast to assign 128 to a byte, and the assignment leaves us with the value -128. A cast is nothing more than your way of saying to the compiler, Trust me. I\'m a professional. I take full responsibility for anything weird that happens when those top bits are chopped off.
byte b = 3;
b += 7; // No problem - adds 7 to b (result is 10)
Operators and Assignments and is equivalent tobyte b = 3;
b = (byte) (b + 7); // Won\'t compile without the
// cast, since b + 7 results in an int
The compound assignment operator += let\'s us add to the value of b, without putting in an explicit cast.
When we assign one primitive to another the contents of the right-hand variable are copied, for example,
int a = 6;
int b = a;
We used the variable a only to copy its contents. At this point, a and b have identical contents (in other words, identical values), but if we change the contents of a or b, the other variable won\'t be affected.
class ValueTest {
public static void main (String [] args) {
int a = 10; // Assign a value to a
System.out.println(\"a = \" + a);
int b = a;
b = 30;
System.out.println(\"a = \" + a + \"after change to b\");
}
}
The output from this program is %java ValueTest
a = 10
a = 10 after change to b
We have a authority in java that we can assign a newly created object to an object reference variable as follows:Button b = new Button();
This code have a three imp things which is following as :
- Makes a reference variable named b, of type Button.
- Creates a new Button object on the heap.
- Assigns the newly created Button object to the reference variable b.
We can also use a reference variable to refer to any object that is a subclass of the declared reference variable type, as follows:
public class Foo {
public void doFooStuff() {
}
}
public class Bar extends Foo {
public void doBarStuff() { }
}
}
class Test {
public static void main (String [] args) {
Foo reallyABar = new Bar(); // Legal because Bar is a subclass of Foo
Bar reallyAFoo = new Foo(); // Illegal! Foo is not a subclass of Bar
}
}
In the primitive variables , An assignment of one variable to another means the the content of one variable to copy with another.Object reference variables work exactly the same way.
The contents of a reference variable are a bit pattern.we assign an existing instance of an object to a new reference variable, then two reference variables will hold the same bit pattern a bit pattern referring to a specific object on the heap, the code is :import java.awt.Dimension;
class ReferenceTest {
public static void main (String [] args) {
Dimension a = new Dimension(5,10);
System.out.println(\"a.height = \" + a.height);
Dimension b = a;
b.height = 30;
System.out.println(\"a.height = \" + a.height +
\"after change to b\");
}
}
String objects are given special treatment. For one thing, String objects are immutable; We can\'t change the value of a String object.we have a code like :
class Strings {
public static void main(String [] args) {
String x = \"Java\"; // Assign a value to x
String y = x; // Now y and x refer to the same String object
System.out.println(\"y string = \" + y);
x = x + \" Bean\"; // Now modify the object using the x reference
System.out.println(\"y string = \" + y);
}
}
Output is :
%java String
y string = Java
y string = Java
We can see in this output , even though y is a reference variable to the same object that x refers to, when we change x it doesn\'t change y !
Comparison operator result always in the boolean values we also can say its gives output only in the true or false .This boolean value is most often used in an if test, as follows:
int x = 8;
if (x < 9) {
// do something
}
but the resulting value can also be assigned directly to a boolean primitive :
class CompareTest {
public static void main(String [] args) {
boolean b = 100 > 99;
System.out.println(\"The value of b is \" + b);
}
}
We have a four comparison operators which is used for compare any combination of integers , floating point numbers and characters :
- > greater than
- >= greater than or equal to
- < less than
- <= less than or equal to
The instanceof operator is used basically for object reference variable only and we can use it for checking whether an object is of a particular type.if the object referred to by the variable on the left side of the operator passes the IS-A test for the class or interface type on the right side.we can see in this example :public static void main (String [] args) {
String s = new String(\"foo\");
if (s instanceof String) {
System.out.print(\"s is a String\");
}
}
equality is basically use for the tested operators are equal or not :
- == equals (also known as \"equal to\")
- != not equals (also known as \"not equal to\")
Its mainly compares two things and return output in the boolean terms .
--------------------------------------------------
First Operand | instanceof |
(Reference | Operand | Result
Being Tested) | (Type We are |
| Comparing |
| the Reference |
| Against) |
------------------------------------------------
null |Any Class or Interface| false
type
------------------------------------------------
Foo instance |Foo, Bar, Face, Object| true
------------------------------------------------
Bar instance | Bar, Face, Object | true
-------------------------------------------------
Bar instance | Foo | false
-------------------------------------------------
Foo [] | Foo, Bar, Face | false
-------------------------------------------------
Foo [] | Object | true
-------------------------------------------------
Foo[1] |Foo, Bar, Face, Object| true
-------------------------------------------------
There are four different types of things that can be tested :
- Numbers
- Characters
- Boolean primitives
- Object reference variables
Many programmers are much familiar with comparing primitive values. there are some code which is describe some equality test for the primitive variables :
class ComparePrimitives {
public static void main(String [] args) {
System.out.println(\"character \'a\' == \'a\'? \" + (\'a\' == \'a\'));
System.out.println(\"character \'a\' == \'b\'? \" + (\'a\' == \'b\'));
System.out.println(\"5 != 6? \" + (5 != 6));
System.out.println(\"5.0 == 5L? \" + (5.0 == 5L));
System.out.println(\"true == false? \" + (true == false));
}
}
This program produces the following output:
%java ComparePrimitives
character \'a\' == \'a\'? true
character \'a\' == \'b\'? false
5 != 6? true
5.0 == 5L? true // Compare a floating point to an int
true == false? false
We already know about two reference variables can refer to the same object, we have a exampleButton a = new Button(\"Exit\");
Button b = a;
When its execute both of variables are refer same object , Reference variable also test to the they refer same object using == operator.
import java.awt.Button;
class CompareReference {
public static void main(String [] args) {
Button a = new Button(\"Exit\");
Button b = new Button(\"Exit\");
Button c = a;
System.out.println(\"Is reference a == b? \" + (a == b));
System.out.println(\"Is reference a == c? \" + (a == c));
}
}
This code creates three reference variables. The first two, a and b, are separate Button objects that happen to have the same label. The third reference variable, c, is initialized to refer to the same object that a refers to. When this program runs, the following output is produced :
Is reference a == b? false
Is reference a == c? true
We know that the basic operators :
- + addition
- - subtraction
- × multiplication
- / division
class MathTest {
public static void main (String [] args) {
int x = 5 * 3;
int y = x - 4;
System.out.println(\"x - 4 is \" + y); // Prints 11
}
}
One operator we might be not familiar with is the remainder operator, %.for the following code is :
class MathTest {
public static void main (String [] args) {
int x = 15;
int y = x % 4;
System.out.println(\"The result of 15 % 4 is the remainder of
15 divided by 4. The remainder is \" + y);
}
}
Running class MathTest prints the following:
The result of 15 % 4 is the remainder of 15 divided by 4. The remainder is 3
We can also use the compound assignment operator.if the option being done by a single variable.we have a following code :class MathTest {
public static void main (String [] args) {
int x = 15;
x %= 4; // same as x = x % 4;
System.out.println(\"The remainder of 15 % 4 is \" + x);
}
}
Rules to remember are these :
> Dividing an integer by zero will violate an important law of thermodynamics, and cause an ArithmeticException .
> Using the remainder operator (%) will result in an ArithmeticException if the right operand is zero.
The + operator also be use for the concentration for the two string, we can see in this code :
String animal = \"Grey \" + \"elephant\";
String concatenation gets interesting when we combine numbers with Strings.see this code :
String a = \"String\";
int b = 3;
int c = 7;
System.out.println(a + b + c);
We will find that sometimes we might have trouble deciding whether, say, the left hand operator is a String or not. On the exam, don\'t expect it to always be obvious. Actually, now that we think about it, don\'t expect it ever to be obvious.see this following code:System.out.println(x.foo() + 7);
There are in java language we have a two operators that will be increment and decrement a variable , These operators are composed of either two plus signs (++) or two minus signs (--) :
- ++ increment (prefix and postfix)
- -- decrement (prefix and postfix)
The operator is placed either before (prefix) or after (postfix) a variable to change the value.we can see in this example :class MathTest {
static int players = 0;
public static void main (String [] args) {
System.out.println(\"players online: \" + players++);
System.out.println(\"The value of players is \" + players);
System.out.println(\"The value of players is now \" + ++players);
}
}
In this program program the increment operator is after the variable players. that\'s a postfix notation that means we are using the postfix increment operator, which causes the variable players to be incremented by one but only after the value of players is used in the expression.
OUTPUT :
%java MathTest
players online: 0
The value of players is 1
The value of players is now 2
The following are shift operators:
- >> right shift
- << left shift
- >>> unsigned right shift (also called zero-filled right shift)
The condition operator is is a basically a tenantry operator its mainly used for the boolean expressions, its similar as a if statement but some difference its not executing a block of code if the test is true, a conditional operator will assign a value to a variable, we can also say the goal of the conditional operator is to decide which of two values to assign to a variable.
someVariable = (boolean expression) ? value to assign if true : value to assign if false
We have a some code for the conditional operator :class Salary {
public static void main(String [] args) {
int numOfPets = 3;
String status = (numOfPets<4)?\"Pet limit not exceeded\":\"too many pets\";
System.out.println(\"This pet status is \" + status);
}
}
A conditional operator starts with the boolean operator followed by two possible values for the variable to the left of the conditional operator.The first value (the one to the left of the colon) is assigned if the conditional (boolean) test is true, and the second value is assigned if the conditional test is false.
You can even nest conditional operators into one statement.
class AssignmentOps {
public static void main(String [] args) {
int sizeOfYard = 10;
int numOfPets = 3;
String status = (numOfPets<4)?\"Pet count OK\"
:(sizeOfYard > 8)? \"Pet limit on the edge\"
:\"too many pets\";
System.out.println(\"Pet status is \" + status);
}
}
The bitwise operators take two individual bit numbers, then use AND/OR to determine the result on a bit-by-bit basis.
There are three bitwise operators:The & operator compares corresponding bits between two numbers. If both bits are 1, the final bit is also 1. If only one of the bits is 1, the resulting bit is 0.
- && & AND
- | inclusive OR
- ^ exclusive OR
Let\'s compare two numbers, 10 and 9, with the & operator : 1010 & 1001 = 1000
only the first bit (8) is a 1 in both locations, hence the final number is 1000 in bit representation (or 8 in decimal). Let\'s see this in some code:
class Bitwise {
public static void main(String [] args) {
int x = 10 & 9; // 1010 and 1001
System.out.println(\"1010 & 1001 = \" + x);
}
}
When we run this code, the following output is produced :
%java Bitwise
1010 & 1001 = 8
X | Y | & (AND) | | (OR) | ^ (XOR) |
--------------------------------------------------
0 | 0 | 0 | 0 | 0 |
--------------------------------------------------
0 | 1 | 0 | 1 | 1 |
--------------------------------------------------
1 | 0 | 0 | 1 | 1 |
--------------------------------------------------
We get the following,
1010 | 1001 = 1011
Which is easier to see as
1 0 1 0
|
1 0 0 1
____________
1 0 1 1
This expression produces the number 11 (in decimal). see this code :
class Bitwise {
public static void main(String [] args) {
int x = 10 | 9; // 1010 and 1001
System.out.println(\"1010 & 1001 = \" + x);
}
}
When we run the preceding code, we receive the following :
%java Bitwise
1010 & 1001 = 11
The ~ operator is a flip-the-bits operator. It will change all 1s to 0s and vice versa.
see this following code:
class Bitwise {
public static void main(String [] args) {
int x = 5;
System.out.println(\"x is initially \" + x);
x = ~x;
System.out.println(\"~x is equal to \" + x);
}
}
This program is changing every bit into its complement; thus, the output from
this program is the following:
%java Bitwise
x is initially 5
~x is equal to -6
In bit representation, the conversion looks like this,
~0000 0000 0000 0000 0000 0000 0000 0101
and converts to
1111 1111 1111 1111 1111 1111 1111 1010
Casting is basically we convert the primitive values from one type to another, caste can be implicit or explicit.
Implicit caste: its basically means we don\'t have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when we\'re doing a widening conversion. We mwan to say putting a smaller thing like bytes into a bigger container like an int. Remember those possible loss of precision compiler errors we saw in the assignments section, Those happened when we tried to put a larger thing like a long into a smaller container like a short.
Explicit cast: In this case The large value into small container conversion is referred to as narrowing and requires an explicit cast, where we tell the compiler that we\'re aware of the danger and accept full responsibility.
code for the implicit :int a = 100;
long b = a; // Implicit cast, an int value always fits in a long code for the explicit :
float a = 100.001;
int b = (int)a; // Explicit cast, a float can lose info as an int
Create a float number type of any value, and assign it to a short using casting.
1. Declare a float variable: float f = 234.56F;
2. Assign the float to a short: short s = (short)f;
In an expression involving the operators &, |, &&, and ||, and variables of known values, state which operands are evaluated and the value of the expression. that are four logical operators, which are following as :
- &
- |
- && short-circuit AND
- || short-circuit OR
The && operator is basically much like as operator , its uses also same but some thing is diff it evaluates only the boolean expressions and and can\'t be used as a bitwise operator.We know that for an AND expression to be true, both operands must be true.
For example:if ((2 < 3) && (3 < 4)) { }
The following expression evaluates to true only because both operand one (2 < 3) and operand two (3 < 4) evaluate to true.The short-circuit feature of the && operator is that it doesn\'t waste its time on pointless evaluations. A short-circuit && evaluates the left side of the operation first (operand one), and if operand one resolves to false, the && operator doesn\'t bother looking at the right side of the equation (operand two).class Logical {
public static void main(String [] args) {
boolean b = true && false;
System.out.println(\"boolean b = \" + b);
}
}
When we run the preceding code, we get
C:Java ProjectsBookTest>java Logical
boolean b = false
The bitwise operator (& and |)is also use for the logical operators and expressions also .But because they aren\'t the short-circuit operators, they evaluate both sides of the expression,
The short-circuit operators (&& and ||) can be used only in logical (not bitwise) expressions. The bitwise operators (& and |) can be used in both logical and bitwise expressions, but are rarely used in logical expressions because they are not efficient.
Its mainly use for the determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying operations in that method.That method basically use for the declared to take primitives and/or object references. Here we also know that by this method that how to caller\'s variable can be affected by the called method.
When passed into methods, is huge and important, Its the main imp diff of object reference and primitive variables.
When we pass an object variable in to a method , We must know that we\'re passing the object reference, and not the actual object itself.
We must remember that we are not even passing the actual reference variable, but rather a copy of the reference variable.
The copy variable means we get the copy of the bits in that variable, so when we pass a reference variable,
We can also say like this : both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.
For this example, we will use the Dimension class from the java.awt package:
1. import java.awt.Dimension;
2. class ReferenceTest {
3. public static void main (String [] args) {
4. Dimension d = new Dimension(5,10);
5. ReferenceTest rt = new ReferenceTest();
6. System.out.println(\"Before modify() d.height = \" + d.height);
7. rt.modify(d);
8. System.out.println(\"After modify() d.height = \" + d.height);
9. }
10. void modify(Dimension dim) {
11. dim.height = dim.height + 1;
12. System.out.println(\"dim = \" + dim.height);
13. }
14. }
When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.
C:Java ProjectsReference>java ReferenceTest
Before modify() d.height = 10
dim = 11
After modify() d.height = 11
if java passes objects by passing the reference variable instead its means the java uses pass-by-reference for objects, but its not a exactly.Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of-the-variable !
We are always passing a copy of the bits in the variable. So for a primitive variable, we are passing a copy of the bits representing the value.The bottom line on pass-by-value: the called method can\'t change the caller\'s
variable, although for object reference variables, the called method can change the object the variable referred to.
For example, in the following code :
void bar() {
Foo f = new Foo();
doStuff(f);
}
void doStuff(Foo g) {
g = new Foo();
}
When we passed to the primitive variable is passed to a method , we can see in this code :
class ReferenceTest {
public static void main (String [] args) {
int a = 1;
ReferenceTest rt = new ReferenceTest();
System.out.println(\"Before modify() a = \" + a);
rt.modify(a);
System.out.println(\"After modify() a = \" + a);
}
void modify(int number) {
number = number + 1;
System.out.println(\"number = \" + number);
}
}
In this folowing code , we can see thet the variable a is passed to a method called modify(),
which increments the variable by 1.and now we know that whats the output of the givn code :
C:Java ProjectsReference>java ReferenceTest
Before modify() a = 1
number = 2
After modify() a = 1
When we will trying char in the switch case statement value as this case ,Include a default behavior if none of the char values match :
- Make sure a char variable is declared before the switch statement.
- Each case statement should be followed by a break.
- The default value can be located at the end, middle, or top.
We can write the code with all forms of loops including labeled and unlabeled , we can use of break and continue and state of the values taken by loop counter variables during and after loop execution.
java loops have a three types of loops :
- while,
- do-while
- for
while loop basically use when we don\'t know whats the no of times statement will be executed but in the case of while loop we can say that the how many times statements are will be execute that Senior will me following here
int x = 2;
while(x == 2) {
System.out.println(x);
++x;
}
int x = 8;
while (x > 8) {
System.out.println(\"in the loop\");
x = 10;
}
System.out.println(\"past the loop\");
Running this code produces
past the loop
The following shows a do-while statement in action:do {
System.out.println(\"Inside loop\");
} while(false);
The System.out.println() statement will print once, even though the expression evaluates to false. The do-while loop will always run the code in the loop body at least once.
The for loop is basically use ful for the flow control it will be use when we will know that many statements when we need to execute the statement in the loop block .The for loop declaration has three main parts, which is following here :
- Declaration and initialization of variables.
- The boolean expression (conditional test)
- The iteration expression
firstly we have a for statement lets we declare and initialize zero, one, or multiple variables of the same type inside the parentheses after the for keyword. if we would like to declare the same type of variable which is more than one When we \'ll need to separate them with commas as follows :
for (int x = 10, y = 3; y > 3; y++) { }
The declaration and initialization happens before anything else in a for loop. And whereas
the other two parts the boolean test and the iteration expression will run with
each iteration of the loop, the declaration and initialization happens just once, at the
very beginning. You also must know that the scope of variables declared in the for loop
ends with the for loop!
The following demonstrates this:
for (int x = 1; x < 2; x++) {
System.out.println(x); // Legal
}
System.out.println(x);
// Not Legal! x is now out of scope and
can\'t be accessed.
If you try to compile this, you\'ll get
Test.java:19: cannot resolve symbol
symbol : variable x
location: class Test
System.out.println(x);
in the for lop next section is the conditional expression which is in the evaluation of the boolean values .we can have only one logical expression, but its very complex.for (int x = 0; ((((x < 10) && (y-- > 2)) | x == 3)); x++) { }
The preceding code is legal, but the following is not:
for (int x = 0; (x > 5), (y < 2); x++) { } // too many
//expressions
The compiler will let you know the problem:
TestLong.java:20: \';\' expected
for (int x = 0; (x > 5), (y < 2); x++) { }
^
The rule to remember is this :
We can have only one test expression.
After conditional expression execute each body have a for loop which have iteration which expression will be executed.its always happen after the loop body runs :for (int x = 0; x < 1; x++) {
// body code here
}
The preceding loop executes just once. The first time into the loop x is set to 0, then x is tested to see if it\'s less than 1 (which it is), and then the body of the loop executes. After the body of the loop runs, the iteration expression runs, incrementing x by 1. Next, the conditional test is checked, and since the result is now false, execution jumps to below the for loop and continues on. Keep in mind that this iteration expression is always the last thing that happens !static boolean doStuff() {
for (int x = 0; x < 3; x++) {
System.out.println(\"in for loop\");
return true;
}
return true;
}
Running this code produces
in for loop
None of the three sections of the for declaration are required! The following example is perfectly legal :
for( ; ; ) {
System.out.println(\"Inside an endless loop\");
}--------------------------------------------------
Code in Loop | What Happens
--------------------------------------------------
break |Execution jumps immediately to the
first statement after the for loop.
-------------------------------------------------
return |Execution immediately jumps back to
the calling method.
-------------------------------------------------
System.exit()|All program execution stops; the
VM shuts down.
-------------------------------------------------
The break and continue keywords are used to stop either the entire loop (break) or just the current iteration (continue).
Typically if you\'re using break or continue, We\'ll do an if test within the loop, and if some condition becomes true (or false depending on the program),The break statement causes the program to stop execution of the innermost looping and start processing the next line of code after the block.
We can see in the following code :
for (int i = 0; i < 10; i++) {
System.out.println(\"Inside loop\");
continue;
}
Most of the time, a continue is used within an if test as follows:
for (int i = 0; i < 10; i++) {
System.out.println(\"Inside loop\");
if (foo.doStuff() == 5) {
continue;
}
// more loop code, that won\'t be reached when the above if
//test is true
}
both of the statements which is break and continue statement can be labeled or unlabeled ,a break statement (unlabeled) will exit out of the innermost looping construct and proceed with the next line of code beyond the loop block.
The following example demonstrates a break statement:
boolean problem = true;
while (true) {
if (problem) {
System.out.println(\"There was a problem\");
break;
}
}
//next line of code
In the previous example, the break statement is unlabeled. The following is
another example of an unlabeled continue statementwhile (!EOF) {
//read a field from a file
if (there was a problem) {
//move to the next field in the file
continue;
}
}
We end to understand basically whats the diff b/w labeled and unlabeled break and continue statements .the labeled varieties are are needed to be where we have a nested loop, and need to indicate which of the nested loops we want to break from, or from which of the nested loops we want to continue with the next iteration.
A break statement will exit out of the labeled loop, as opposed to the innermost loop, if the break keyword is combined with a label.
foo:
for (int x = 3; x < 20; x++) {
while(y > 7) {
y--;
}
}
The syntax for the use of a label name in conjunction
with a break statement is the break keyword, then the label name, followed by a
semicolon. A more complete example of the use of a labeled break statement is as
follows:
outer:
for(int i=0; i<10; i++) {
while (y > 7) {
System.out.println(\"Hello\");
break outer;
} // end of inner for loop
System.out.println(\"Outer loop.\"); // Won\'t print
} // end of outer for loop
System.out.println(\"Good-Bye\");
Running this code produces
Hello
Good-Bye
The following code
example is the same as the preceding one, with the exception of substituting
continue for break:
outer:
for (int i=0; i<10; i++) {
for (int j=0; j<5; j++) {
System.out.println(\"Hello\");
continue outer;
} // end of inner loop
System.out.println(\"outer\"); // Never prints
}
System.out.println(\"Good-Bye\");
Running this code produces
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Good-Bye
When we are trying to labeled for the while loop , we would t make the label .Within the loop, it should increment the age by one. Every time it goes through the loop, it checks whether the age is 16.
- The outer label should appear just before the while loop begins. It does not matter if it is on the same line or not.
- Make sure age is declared outside of the while loop.
Exception handling is basically use for the proper code and declare method and overriding methods that throw exceptions.
The term exception basically means exceptional condition and is an occurrence that alters the normal program flow.
A bunch of things can lead to exceptions, including hardware failures, resource exhaustion, and good old bugs.when the exception occurs in the java code its said to be a thrown and which code is responsible for the something about the exception is called an exception handler, and it catches the thrown exception.
The try is used to define a block of code in which exceptions may occur. This block of code is called a guarded region,which really means risky code goes here .
try {
// This is the first line of the \"guarded region\"
// that is governed by the try keyword.
// Put code here that might cause some kind of exception.
// We may have many code lines here or just one.
}
catch(MyFirstException) {
// Put code here that handles this Exception.
// This is the next line of the exception handler.
// This is the last line of the exception handler.
}
catch(MySecondException) {
// Put code here that handles this exception
}
// Some other unguarded (normal, non-risky) code begins here
If we have one or more catch blocks, they must immediately follow the try block. Additionally, the catch blocks must all follow each other, without any other statements or blocks in between. Also, the order in which the catch blocks appear matters, as we will see a little later.
try and catch provides a facility for the provide traffic mechanism for the trapping and handling exception. Because execution transfers out of the try block as soon as an exception is thrown, we can\'t put our cleanup code at the bottom of the try block and expect it to be executed if an exception occurs.
A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement.try {
// This is the first line of the \"guarded region\".
}
catch(MyFirstException) {
// Put code here that handles this error.
}
catch(MySecondException) {
// Put code here that handles this error.
}
finally {
// Put code here to release any resource we/ allocated in the try clause.
}
// More code here
finally clauses are not required. If you don\'t write one, your code will compile and run just fine. In fact, if you have no resources to clean up after your try block completes, you probably don\'t need a finally clause.
The following legal code demonstrates a try with a finally but no catch:
try {
// do stuff
} finally {
//clean up
}
The following legal code demonstrates a try, catch, and finally:try {
// do stuff
} catch (SomeException ex) {
// do exception handling
} finally {
// clean up
}
The following illegal code demonstrates a try without catch or finally:try {
// do stuff
}
System.out.println(\"out of try block\"); // need a catch or finally here
The following illegal code demonstrates a misplaced catch block:try {
// do stuff
}
System.out.println(\"out of try block\"); // can\'t have code between try/catch
catch(Exception ex) { }
We need to briefly review the concept of the call stack. Most languages have the concept of a method stack or a call stack.
Simply put, the call stack is the chain of methods that your program executes to get to the current method.
If your program starts in method main() and main() calls method a(), which calls method b() that in turn calls method c(), the call stack consists of the following:
c
b
a
main
A stack can be represented as growing upward (although it can also be visualized as growing downward).
As you can see, the last method called is at the top of the stack, while the first calling method is at the bottom. If you could print out the state of the stack at any given time, you would produce a stack trace.
The method at the very top of the stack trace would be the method you were currently executing. If we move back down the call stack, we\'re moving from the current method to the previously called method.
We attempt to create two methods that deal with exceptions. One of the methods is the main() method, which will call another method. If an exception is thrown in the other method, it must deal with it.
A finally statement will be included to indicate it is all done. The method it will call will be named reverse(),and it will reverse the order of the characters in the string. If the string contains no characters, it will propagate an exception up to the main() method :
- Create an enclosing class called Propagate and a main() method, which will remain empty for now.
- Create a method called reverse(). It takes an argument of a string and returns a String.
- Check if the String has a length of 0 by using the length() method. If the length is 0, it will throw a new exception.
- Now let\'s include the code to reverse the order of the String. Because this isn\'t the main topic of this chapter, the reversal code has been provided, but feel free to try it on our own.
String reverseStr = \"\";
for(int i=s.length()-1;i>=0;--i) {
reverseStr += s.charAt(i);
}
return reverseStr;
Now in the main() method we will attempt to call this method and deal with any potential exceptions. Additionally, we will include a finally statement that tells us it has finished.
Here our working the basically a develop the java code and the flow of our programs and also exception in functional java code.its mainly the alerts the normal program flow.Exception in its inheritance hierarchy. In other words, exceptions are always some subclass of java.lang.Exception.
try {
// some code here
}
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
In this example, e is an instance of a class with the tersely named array Index Out Of Bounds Exception. As with any other object, We can call its methods.
All exceptions classes are subtype of class Exception.this class basically derived from the class throwable.there are two subclasses which are throwable.Which are a exceptions and errors parent class .
An exception represents something that happens not as a result of a programming error, but rather because some resource is not available or some other condition required for correct execution is not present.
Java provides many exception classes, most of which have quite descriptive names. There are two ways to get information about an exception. The first is from the type of the exception itself. The next is from information that you can get from the exception object.
Class Throwable (at the top of the inheritance tree for exceptions) provides its descendants with some methods that are useful in exception handlers. One of these is printStackTrace().
We can actually catch more than one type of exception in a single catch clause. If the Exception class that we specify in the catch clause has no subclasses, then only the specified class of exception will be caught.
However, if the class specified in the catch clause does have subclasses, any exception object that subclasses the specified class will be caught as well.
We could write a catch clause like the following:try {
// Some code here that can throw a boundary exception
}
catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
Exception matching is the basically a type of hierarchy which is composed of the super class exception and the no of subtypes and we \'were interested in handling one of the subtypes in a special way but want to handle all the rest together, we need write only two catch clauses.
This process is called exception matching. Let\'s look at an example:
import java.io.*;
public class ReadData {
public static void main(String args[]) {
try {
RandomAccessFile raf =
new RandomAccessFile(\"myfile.txt\", \"r\");
byte b[] = new byte[1000];
raf.readFully(b, 0, 1000);
}
catch(FileNotFoundException e) {
System.err.println(\"File not found\");
System.err.println(e.getMessage());
e.printStackTrace();
}
catch(IOException e) {
System.err.println(\"IO Error\");
System.err.println(e.toString());
e.prinStackTrace();
}
}
}
This short program attempts to open a file and to read some data from it. Opening and reading files can generate many exceptions, most of which are some type of IOException. Imagine that in this program we\'re interested in knowing only whether the exact exception is a FileNotFoundException. Otherwise, we don\'t care exactly what the problem is.
The Exception that a method can throw must be declare exception are subclass are RuntimeException.The throws keyword is used as follows to list the exceptions that a method can throw :
void myFunction() throws MyException1, MyException2 {
// code for the method here
}
We can handle the the exception outsell and instance just declare it .and and either be caught there or continue on to be handled by a method further down the stack.
Each method must either handle all checked exceptions by supplying a catch clause or list each unhanded checked exception as a thrown exception. This rule is referred to as Java\'s handle or declare requirement.
Rethrowing is just we can throw the exception from a catch clause,we can also the same exception we just caught.
catch(IOException e) {
// Do things, then if you decide you can\'t handle it
throw e;
}
All catch clause the exception is thrown back to the calling method.id we want to be throw a checked exception from a catch clause, you must also declare that exception! In other words, you must handle and declare, as opposed to handle or declare.
The following example is illegal :public void doStuff() {
try {
// risky IO things
} catch(IOException ex) {
// can\'t handle it
throw ex; // Can\'t throw it unless you declare it
}
}
We will call it BadFoodException.
- Create an enclosing class called MyException and a main() method, which will remain empty for now.
- Create a method called checkFood(). It takes a String argument and throws our exception if it doesn\'t like the food it was given. Otherwise, it tells us it likes the food. We can add any foods we aren\'t particularly fond of to the list.
- Now in the main() method, We will get the command-line argument out of the String array, and then pass that String on to the checkFood() method. Because it\'s a checked exception, the checkFood() method must declare it, and the main() method must handle it (using a try/catch). Do not have main() declare the method, because if main() ducks the exception,
We were not supposed to make assumptions, but we can\'t help it when we\'re writing code.
if (x > 2 && y) {
// do something
} else if (x < 2 || y) {
// do something
} else {
// x must be 2
// do something else
}
You write print statements with them:while (true) {
if (x > 2) {
break;
}
System.out.print(\"If we got here something went horribly wrong\");
}
Added to the Java language beginning with version 1.4, assertions let we test our
assumptions during development, without the expense (in both your time and program overhead) of writing exception handlers for exceptions that we assume will never happen once the program is out of development and fully deployed.
This code we can see the proper use of assertion and and distinguish appropriate from inappropriate uses of assertions. Identify correct statements about the assertion mechanism.
if (x > 2 && y) {
// do something
} else if (x < 2 || y) {
// do something
} else {
// x must be 2
// do something else
}
We write print statements with them:
while (true) {
if (x > 2) {
break;
}
System.out.print(\"If we got here something went horribly wrong\");
}
We can suppose the assume that a number passed into a method (say, methodA()) will never be negative. While testing and debugging, We want to validate our application we font want to have to strip out print statements, runtime exception handlers, or if/else tests whenwe were done with development.private void methodA(int num) {
if (num >= 0) {
// do stuff
} else { // num must be < 0
// This code will never be reached!
System.out.println(\"Yikes! num is a negative number! \" + num);
}
useNum(num + x);
}
Assertions let we test our assumptions during development, but the assertion code in effect evaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove. Let\'s rewrite methodA() to validate that the argument was not negative :
private void methodA(int num) {
assert (num>=0); // throws an AssertionError
// if this test isn\'t true
useNum(num + x);
}
We always assert that something is true. If it is, no problem. Code keeps running. But if your assertion turns out to be wrong (false), then a stop-the-world AssertionError is thrown (that you should never, ever handle!)
right then and there, so you can fix whatever logic flaw led to the problem. Assertions come in two flavors: simple and really simple, as follows:
Really Simple
private void doStuff() {
assert (y > x);
// more code assuming y is greater than x
}
Simple
private void doStuff() {
assert (y > x): \"y is \" + y \" \" x is \" + x;
// more code assuming y is greater than x
}
The difference between them is that the simple version adds a second expression,separated from the first (boolean expression) by a colon, that adds a little more information to the stack trace. Both versions throw an immediate Assertion Error, but the simple version gives you a little more debugging help while the simple version simply tells you that your assumption was false
id we would like to use assertion, we will firstly thinking about how to compile with assrtion in out code.
Expression1 | Expression2
-------------------------------------------------
Legal |Illegal |Legal | Illegal
-------------------------------------------------
assert(x ==2) |assert(x=2)|:x is+x |: void
--------------------------------------------------
boolean z=true;|int z = 0; |public int| public
assert (z) assert (z) go(){ void
return 1; go() { }
: go(); : go();
--------------------------------------------------
assert false |assert 1 |:new Foo();|: Foo f;
--------------------------------------------------
We know whats in this code :int assert = getInitialValue();
if (assert == getActualResult()) {
// do something
}
IN the preceding code assert is used as an identifier,assert is now a keyword! The bottom line is we can use assert as a keyword or as an identifier, but not both..We\'re compiling assertion aware code or code written in the old way, where assert is not a reserved word. assertions are disabled by default!
If we \'were using this keyword then we must explicitly enable assertion awareness at compile time.
If we don\'t use the -source 1.4 flag, then the default behavior is as though we said to the compiler, Compile this code as if we didn\'t known anything about assert as a keyword, so that I may use the word assert as an identifier for a method or variable.
Firstly we have written a assertion ware code , We can also say code that uses assert as a keyword, to actually perform assertions at runtime, we can choose to enable or disable them! assertions are disabled by default.
We can enable assertions at runtime with
java -ea com.geeksanonymous.TestClass
or
java -enableassertions com.geeksanonymous.TestClass
The preceding command-line switches tell the JVM to run with assertions enabled
We must also know the command-line switches for disabling assertions.
java -da com.geeksanonymous.TestClass
or
java -disableassertions com.geeksanonymous.TestClass
The command-line switches to enable and disable assertions can be used in various ways :
- With no arguments
- With a package name
- With a class name
We can combine switches to, say, disable assertions in a single class, but keep them enabled for all others, as follows :
java -ea -da:com.geeksanonymous.Foo
The preceding command line tells the JVM to enable assertions in general, but disable them in the class com.geeksanonymous.Foo. We can do the same selectivity for a package as follows :
java -ea -da:com.geeksanonymous
The preceding command line tells the JVM to enable assertions in general, but disable them in the package com.geeksanonymous, and all of its subpackages!A subpackage is any package in a subdirectory of the named package. For example, look at the following directory tree:
com
|_geeksanonymous
|_Foo
|_Bar
|_twelvesteps
|_StepOne
|_StepTwo
This tree lists three directories,
com
geeksanonymous
twelvesteps
and four classes :
com.geeksanonymous.Foo
com.geeksanonymous.Bar
com.geeksanonymous.twelvesteps.StepOne
com.geeksanonymous.twelvesteps.StepTwo
--------------------------------------------------
Command-Line | What It Means
Example
--------------------------------------------------
java -ea | Enable assertions
java -enableassertions
--------------------------------------------------
java -da | Disable assertions
java -disableassertions
--------------------------------------------------
java -ea:com.foo.Bar |Enable assertions in
class com.foo.Bar
--------------------------------------------------
java -ea:com.foo | Enable assertions in
package com.foo, and any
of its subpackages
--------------------------------------------------
java -ea -dsa | Enable assertions in
general but disable
assertions in system
classes
--------------------------------------------------
java -ea -da:com.foo | Enable assertions in
general, but disable
assertions in package
com.foo and any of its
subpackages
--------------------------------------------------
League uses of assertion are consider appropriate.we can abuse in the java the mentioned use for the assertion.for the example we were never suppose to handle an assertion failure.AssertionError is a subclass of Throwable, so it can be caught.
Following code for the assertion :
public void doStuff(int x) {
assert (x > 0);
// do things with x
}
A public method might be called from code that we don\'t control,because Because public methods are part of our exposed interface to the outside
world, we are supposed to guarantee that any constraints on the arguments will be enforced by the method itself. But since assertions aren\'t guaranteed to actually run.
If we write a private method , we almost certainly wrote any code that calls it,when we assume that the logic in code calling our private method is correct.
private void doMore(int x) {
assert (x > 0);
// do things with x
}
The only method in the program diff that matters between the preceding example and the one before it is the access modifier.
assertion is not use for the validate argument a public method which is a type of rule , if our program requires command line argument,We\'ll probably use the exception mechanism to enforce them.
this is an include codes blocks that should be never reached including the default of a switch statement as follows:
switch(x) {
case 2: y = 3;
case 3: y = 17;
case 4: y = 27;
default: assert false; // We\'re never supposed to get here!
}
The following would be a very bad idea:
public void doStuff() {
assert (modifyThings());
// continues on
}
public boolean modifyThings() {
x++ = y;
return true;
}
The rule is: An assert expression should leave the program in the same state it was in before the expression!
Two benefit are there for the Encapsulation :
- flexibility
- maintainability
These benefits are not become automatically , We have to do something for the enable those things. We should create a classes and code in a way that supports flexibility and maintainability.
public class BadOO {
public int size;
public int weight;
}
public class ExploitBadOO {
public static void main (String [] args) {
BadOO b = new BadOO();
b.size = -5; // Legal but bad!!
}
}
The ability to make changes in our implementation code without breaking the code of others who use our code is a key benefit of encapsulation.
We want to hide implementation details behind a public programming interface. By interface, we mean the set of accessible methods our code makes available for other code to call in .
We can also say like this that our code s API. By hiding implementation details. If we want maintainability, flexibility, and extensibility our design must include encapsulation.
In Object Oriented the concept of IS-A is based on inheritance. IS-A is a way of saying, this thing is a type of that thing.
Our express the IS-A relationship in Java through the keyword extends:
public class Car {
// Cool Car code goes here
}
public class Subaru extends Car {
// Important Subaru-specific stuff goes here
// Don\'t forget Subaru inherits accessible Car members
}
A Car is a type of Vehicle, so the inheritance three might start from the Vehicle class as follows :public class Vehicle { }
public class Car extends Vehicle { }
public class Subaru extends Car { }
In OO terms, you can say the following:
- Vehicle is the superclass of Car.
- Car is the subclass of Vehicle.
- Car is the superclass of Subaru.
- Subaru is the subclass of Vehicle.
- Car inherits from Vehicle.
- Subaru inherits from Car.
- Subaru inherits from Vehicle.
- Subaru is derived from Car.
- Car is derived from Vehicle.
- Subaru is derived from Vehicle.
- Subaru is a subtype of Car.
- Subaru is a subtype of Vehicle.
Returning to our IS-A relationship, the following statements are true :
- Car extends Vehicle means Car IS-A Vehicle.
- Subaru extends Car means Subaru IS-A Car.
HAS-A relationships basically dependent on the usage, rather than inheritance. We can also say
class A HAS-A B if code in class A has a reference to an instance of class B.
For example, We can say the following :
A Horse IS-A Animal. A Horse HAS-A Halter. and the code looks like this :
public class Car { }
public class sporty extends Car {
private stering mystering;
}
In the upper code the Sporty class has an instance variable of type stering, so we can say that Sporty HAS-A stering. In other words, Sporty has a reference to a Stering. Sporty code can use that stering reference to invoke methods on the Stering, and get stering behavior without having Stering-related code (methods) in the Sporty class itself.
We have a authority to create a class that inherits a method from a superclass, we have the opportunity to override the method .The key benefit of overriding is the ability to define behavior that\'s specific to a particular subclass type.
public class Cars {
public void drive() {
System.out.println(\"Generic cars driving Generally\");
}
}
class sporty extends car {
public void drive() {
System.out.println(\"sporty cars take a petrol\");
}
}
The rules for overriding a method are as follows :
- The argument list must exactly match that of the overridden method.
- The return type must exactly match that of the overridden method.
- The access level must not be more restrictive than that of the overridden method.
- The access level can be less restrictive than that of the overridden method.
- The overriding method must not throw new or broader checked exceptions than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it\'s a subclass of FileNotFoundException.
- The overriding method can throw narrower or fewer exceptions. Just because an overridden method takes risks doesn\'t mean that the overriding subclass exception takes the same risks.
- Bottom line: An overriding method doesn\'t have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
- We cannot override a method marked final.
We will want to take advantage of some of the code in the superclass version of a method, yet still override it to provide some additional specific behavior. Run the superclass version of the method, then come back down here and finish with my subclass additional method code. It is easy to do in code using the keyword super as follows :public class Animal {
public void eat() { }
public void printYourself() {
// Useful printing code goes here
}
}
class Horse extends Animal {
public void printYourself() {
// Take advantage of Animal code, then add some more
super.printYourself(); // Invoke the superclass
// (Animal) code
// Then come back and do
// additional Horse-specific
// print work here
}
}
</code>
Overloaded method is basically use for the same method name in a class but with diff argument .
Overloaded a method often means we were being a little nicer to those we call our methods.because our code of burden of coping with different argument types rather than forcing the caller to do conversions prior to invoking our method , the rules are simple which is following as :
- Overloaded methods must change the argument list.
- Overloaded methods can change the return type.
- Overloaded methods can change the access modifier.
- Overloaded methods can declare new or broader checked exceptions.
- A method can be overloaded in the same class or in a subclass
Illegal Override Code | Problem with the Code
-------------------------------------------------
private void eat() { } |Access modifier is more
restrictive.
-------------------------------------------------
public void eat() |Declares a checked
throws IOException { } exception not declared
by superclass version.
--------------------------------------------------
public void |A legal overload, not
eat(String food) { } an override, because the
argument list changed.
--------------------------------------------------
public String eat() { } |Not an override because
of the return type, but
not an overload either
because there\'s no
change in the argument
list.
--------------------------------------------------
When we want to overload that code is shown :public void changeSize(int size, String name, float pattern) { }
The following methods are legal overloads of the changeSize() method :public void changeSize(int size, String name) { }
public int changeSize(int size, float pattern) { }
public void changeSize(float pattern, String name)
throws IOException { }
When the method is invoked more than one method of the same name might exist for the object type we are invoking a method on.
Deciding which of the matching methods to invoke is based on the arguments. If we invoke the method with a String argument, the overloaded version that takes a String is called.
If we invoke a method of the same name but pass it a float, the overloaded version that takes a float will run.The following are examples of invoking overloaded methods :
class Adder {
public int addThem(int x, int y) {
return x + y;
}
// Overload the addThem method to add doubles instead of ints
public double addThem(double x, double y) {
return x + y;
}
}
From another class, invoke the addThem() method
public class TestAdder {
public static void main (String [] args) {
Adder add = new Adder();
int b = 27;
int c = 3;
int result = a.addThem(b,c); // Which addThem is invoked?
double doubleResult = a.addThem(22.5,89.36);
// Which addThem?
}
}
The overloaded method that takes an Animal will be invoked, even if the actual object passed is a Horse. Once the Horse masquerading as Animal gets in to the method, however, the Horse object is still a Horse despite being passed into a method expecting an Animal.
So it\'s true that polymorphism doesn\'t determine which overloaded version is called polymorphism does come into play when the decision is about which overridden version of a method is called.
But sometimes, a method is both overloaded and overridden. Imagine the Animal and Horse classes look like this:
public class Animal {
public void eat() {
System.out.println(\"Generic Animal Eating Generically\");
}
}
public class Horse extends Animal {
public void eat() {
System.out.println(\"Horse eating hay \");
}
public void eat(String s) {
System.out.println(\"Horse eating \" + s);
}
}
Method Invocation Code | Result
----------------------------------------------------
Animal a = new Animal(); |Generic Animal Eating
a.eat(); Generically
----------------------------------------------------
Horse h = new Horse(); |Horse eating hay
h.eat();
--------------------------------------------------
Animal ah = new Horse(); |Horse eating hay
ah.eat(); Polymorphism works the
actual object type
(Horse), not the
reference type (Animal),
is used to determine
which eat()is called.
-------------------------------------------------
Horse he = new Horse(); |Horse eating Apples
he.eat(\"Apples\"); The overloaded eat
eat(String s) method
is invoked.
--------------------------------------------------
Animal a2 = new Animal();|Compiler error!
a2.eat(\"treats\"); Compiler sees that
Animal class doesn\'t
have an eat() method
that takes a String.
--------------------------------------------------
Animal ah2 = new Horse();|Compiler error! Compiler
ah2.eat(\"Carrots\"); still looks only at the
reference type,and sees
that Animal doesn\'t have
eat() method that takes
a string. Compiler doest
care that the actual
object might be a Horse
at runtime.
---------------------------------------------------
Overloaded Method| Overridden method
----------------------------------------------------
argument list |Must change |must not
change
-----------------------------------------------
return type |Can change |must not
change
----------------------------------------------
Can change |Can change |Can reduce or
eliminate
must now throw
new or broder
check exception
--------------------------------------------------
access | can check |must not make
more restrictive
--------------------------------------------------
invocation |reference type |object type
determines which determines
overloaded version which method is
is selected.happns selected.happns
at compile time.the at run time.
actual method that\'s
invoked is still a
vertual method invoc
-ation that happns
at run time but the
compiler will alredy
know the signature of
the method to be incl
ude o at runtime the
argument match will
alredy have been nailed
down just not the
actual class in which
the method lives.
---------------------------------------------------
Every class must be a constructor including abstract class.A constructor looks like this:
class Foo {
Foo() { } // The constructor for the Foo class
}
Constructors are used to initialize instance variable state, as follows:
class Foo {
int size;
String name;
Foo(String name, int size) {
this.name = name;
this.size = size;
}
}
In the preceding code example, the Foo class does not have a no-arg constructor. That means the following will fail to compile,
Foo f = new Foo(); // Won\'t compile, no matching constructor
but the following will compile,
Foo f = new Foo(\"Fred\", 43); // No problem. Arguments match Foo constructor.
Constructors are invoked at runtime when we say new on some class type as follows :
Horse h = new Horse();
- But what really happens when we say new Horse() :
- Horse constructor is invoked.
- Animal constructor is invoked (Animal is the superclass of Horse).
- Object constructor is invoked (Object is the ultimate superclass of all classes, so class Animal extends Object even though we don\'t actually type \"extends Object\" in to the Animal class declaration. It\'s implicit.) At this point we are on the top of the stack.
- Object instance variables are given their explicit values (if any).
- Object constructor completes.
- Animal instance variables are given their explicit values (if any).
- Animal constructor completes.
- Horse instance variables are given their explicit values (if any).
- Horse constructor completes.
Rules are there :
- Constructors can use any access modifier, including private. (A private constructor means only code within the class itself can instantiate an object of that type, so if the private-constructor class wants to allow an instance of the class to be used, the class must provide a static method or variable that allows access to an instance created from within the class.)
- The constructor name must match the name of the class.
- Constructors must not have a return type.
- It\'s legal (but stupid) to have a method with the same name as the class, but that doesn\'t make it a constructor. If we see a return type, it\'s a method rather than a constructor.
- If we don\'t type a constructor into our class code, a default constructor will be automatically generated by the compiler.
- The default constructor is always a no-arg constructor.
- If we want a no-arg constructor and we have typed any other constructor(s) into our class code, the compiler won\'t provide the no-arg constructor (or
- any other constructor) for us. In other words, if we have typed in a constructor with arguments, we won\'t have a no-arg constructor unless we type it in ourself !
- Every constructor must have as its first statement either a call to an overloaded
- constructor (this()) or a call to the superclass constructor (super()).
- If we do type in a constructor (as opposed to relying on the compiler-generated default constructor), and we do not type in the call to super(), the compiler will insert a no-arg call to super() for us.
- A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
- A no-arg constructor is not necessarily the default constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, we are free to put in our own no-arg constructor.
Horse class with two constructors :
class Horse {
Horse() { }
Horse(String name) { }
}
Will the compiler put in a default constructor for the class above? No!
class Horse {
Horse(String name) { }
}
Now will the compiler insert a default constructor
class Horse { }
The compiler will generate a default constructor for the preceding class, because the class doesn\'t have any constructors defined.
class Horse {
void Horse() { }
}
Constructors can have arguments just as methods can, and if we try to invoke a method that takes, say, an int, but we don\'t pass anything to the method, the compiler will complain as follows:
class Bar {
void takeInt(int x) { }
}
class UseBar {
public static void main (String [] args) {
Bar b = new Bar();
b.takeInt(); // Try to invoke a no-arg takeInt() method
}
}
Overloading a constructor means typing in multiple versions of the constructor, each having a different argument lists, like the following examples :
class Foo {
Foo() { }
Foo(String s) { }
}
The preceding Foo class has two overloaded constructors, one that takes a string, and one with no arguments. Because there\'s no code in the no-arg version, it\'s actually identical to the default constructor the compiler supplies, but remember since there is already a constructor in this class (the one that takes a string), the compiler won\'t supply a default constructor.
This objective covers two aspects of return types :
- What we can declare as a return type, and
- What we can actually return as a value.
It all depends on whether we are overriding an inherited method or simply declaring a new method.We will cover a small bit of new ground, though, when we look at polymorphic return types and the rules for what is and is not legal to actually return.
Overloading is not much more than name reuse. The overloaded method is a completely different method from any other method of the same name.
So if we inherit a method but overload it in a subclass, we are not subject to the restrictions of overriding,overload a method, remember, we must change the argument list.
The following code shows an overloaded method :public class Foo{
void go() { }
}
public class Bar extends Foo {
String go(int x) {
return null;
}
}
As we know that When a subclass wants to change the method implementation of an inherited method,
the subclass must define a method that matches the inherited version exactly.
An exact match means the arguments and return types must be identical.We know that overloaded methods can change the return type, but overriding methods cannot.
Have to remember only six rules for returning a value:
We can return null in a method that has an object reference return type.
public Button doStuff() {
return null;
}
</code>
An array is a perfectly legal return type.
<code>
public String [] go() {
return new String[] {\"Fred\", \"Barney\", \"Wilma\"};
}
In a method with a primitive return type, we can return any value or variable that can be implicitly converted to the declared return type.
public int foo() {
char c = \'c\';
return c; // char is compatible with int
}
In a method with a primitive return type, We can return any value or variable that can be explicitly cast to the declared return type.
public int foo () {
float f = 32.5f;
return (int) f;
}
We must not return anything from a method with a void return type.
public void bar() {
return \"this is it\"; // Not legal!!
}
In a method with an object reference return type, We can return any object type that can be implicitly cast to the declared return type.
public Animal getAnimal() {
return new Horse(); // Assume Horse extends Animal
}
public Object getObject() {
int[] nums = {1,2,3};
return nums; // Return an int array, which is still an object
}
public interface Chewable { }
public class Gum implements Chewable { }
public class TestChewable {
// Method with an interface return type
public Chewable getChewable {
return new Gum(); // Return interface implementer
}
}
Firstly we want to discussions about the initial information about string.its nothing but its very important when we would like to know about string.like Handling strings of characters is a fundamental aspect of most programming languages.
Each character in string is 16 bit Unicode character acc to the java language.Because Unicode characters are 16 bitsa rich, international set of characters is easily represented in Unicode. bassiclly in java language string is a object.String s = new String();
This line of code creates a new object of class String, and assigns the reference variable s to it.s = \"abcdef\";
String s = new String(\"abcdef\");
And just because we willl use strings all the time, we can even say this :String s = \"abcdef\";
one of the main thing is in the programming language is to make a efficient use of memory.
String is the main thing which is literals occupy large amounts of a program memory, and that there is often a lot of redundancy within the universe of String literals for a program.
This is to make a java more efficient the JVM sets aside a special area of memory called the String constant pool. When the compiler encounters a String literal, it checks the pool to see if an identical String already exists.
Now we are discussing about the various methods of creating a String.we have some examples to explain for the how to create a string :
Creates one String object and one reference variable
String s = \"abc\";
In this simple case, abc will go in the pool and s will refer to it.
String s = new String(\"abc\");
creates two objects, and one reference variable
Now we are discussing about following methods which are most important for the string class :public char charAt(int index)
This method returns the character located at the String\'s specified index. Remember that String indexes are zero based for example,String x = \"airplane\";
System.out.println( x.charAt(2) ); // output is
public String concat(String s)
This method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke the method for example :String x = \"sporty\";
System.out.println( x.concat(\" car\") );
// output is \"sporty car\"
The overloaded + and += operators perform functions similar to the concat() method for example :String x = \"Identitily\";
System.out.println( x + \" card\"); // output is \"Identitily card\"
Stringbuffur class is the most important thing in the string class .its mainly use for the modifications in the string of characters.String objects are immutable,objects of type StringBuffer can be modified over and over again without leaving behind a great effluence of discarded String objects.
Now are discussing about StringBuffer object with the argument\'s value appended to the value of the object that invoked the method :public synchronized StringBuffer append(String s)
This method will take many different arguments, boolean, char, double, float, int, long, and others, but the most likely use on the exam will be a String argument for example :StringBuffer sb = new StringBuffer(\"set \");
sb.append(\"point\");
System.out.println( sb ); // output is \"set point\"
or
StringBuffer sb = new StringBuffer(\"pi = \");
sb.append(3.14159f);
System.out.println( sb ); // output is \"pi = 3.14159\"
Math class is basically use for the Write code using the following methods of the java.lang.Math class: abs, ceil, floor, max, min, random, round, sin, cos, tan, sqrt.
In the java language that apckage defines classes that are fundamental to the Java language.For this reason, all classes in the java.lang package are imported automatically, so there is no reason to write an import statement for them.
The java.lang package also contains the Math class, which is used to perform basic mathematical operations. The Math class defines approximations for the mathematical constants pi and e. Their signatures are as follows:public final static double Math.PI
public final static double Math.E
The methods of the Math class are static and are accessed like any static method through the class name.
For these method calls the general form is result = Math.aStaticMathMethod();
The abs() method returns the absolute value of the argument for example :x = Math.abs(99); // output is 99
x = Math.abs(-99) // output is 99
The method is overloaded to take an int, a long, a float, or a double argument. In all but two cases, the returned value is non negative.The signatures of the abs() method are as follows:public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)
The ceil() method returns the smallest integer, as a double, that is greater than or equal to the argument and equal to the nearest integer value. In other words, the argument is rounded up to the nearest integer equivalent.
All the following calls to Math.ceil() return the double value 9.0:Math.ceil(9.0) // result is 9.0
Math.ceil(8.8) // rises to 9.0
Math.ceil(8.02) // still rises to 9.0
The floor() method returns the largest double that is less than or equal to the argument and equal to the nearest integer value. This method is the antithesis of the ceil() method.Math.floor(9.0) // result is 9.0
Math.floor(9.4) // drops to 9.0
Math.floor(9.8) // still drops to 9.0
The max() method takes two numeric arguments and returns the greater of the two for example,x = Math.max(1024, -5000); // output is 1024.
This method is overloaded to handle int, long, float, or double arguments. If the
input parameters are the same, max() returns a value equal to the two arguments. The signatures of the max() method are as follows :public static int max(int a, int b)
public static long max(long a, long b)
public static float max(float a, float b)
public static double max(double a, double b)
This method is overloaded to handle int, long, float, or double arguments. If the input parameters are the same, min() returns a value equal to the two arguments.
The signatures of the min() method are as follows:public static int min(int a, int b)
public static long min(long a, long b)
public static float min(float a, float b)
public static double min(double a, double b)
The random() method returns a random double that is greater than or equal to 0.0 and less than 1.0. The random() method does not take any parameters :
for example :
public class RandomTest {
public static void main(String [] args) {
for (int x=0; x < 15; x++)
System.out.print( (int)(Math.random()*10) + \" \" );
}
}
The println() method multiplies the result of the call to Math.random() by 10, and then casts the resulting double (whose value will be between 0.0 and 9.99999999), to an integer.
Here are some sample results :
6 3 3 1 2 0 5 9 3 5 6 6 0 3 5
4 9 3 6 6 8 1 1 3 0 3 2 5 3 4
The signature of the random() method is as follows :public static double random( )
The round() method returns the integer closest to the argument. The algorithm is to add 0.5 to the argument and truncate to the nearest integer equivalent. This method is overloaded to handle a float or a double argument.
The signatures of the round() method are as follows :public static int round(float a)
public static long round(double a)
The sin() method returns the sine of an angle. The argument is a double representing an angle in radians. Degrees can be converted to radians by using Math.toRadians() for example :Math.sin(Math.toRadians(90.0))// returns 1.0
The signature of the sin() method is as follows :public static double sin(double a)
The cos() method returns the cosine of an angle. The argument is a double representing an angle in radians for example :Math.cos(Math.toRadians(0.0)) // returns 1.0
The signature of the cos() method is as follows :public static double cos(double a)
The tan() method returns the tangent of an angle.
The argument is a double representing an angle in radians for example :Math.tan(Math.toRadians(45.0)) // returns 1.0
The signature of the tan() method is as follows :public static double tan(double a)
The sqrt() method returns the square root of a double for example :Math.sqrt(9.0) // returns 3.0
The Java Math.sqrt() method returns NaN instead of an object representing a complex number. NaN is a bit pattern that denotes not a number. The signature of the sqrt() method is as follows :public static double sqrt(double a)
The toDegrees() method takes an argument representing an angle in radians and returns the equivalent angle in degrees for example,
Math.toDegrees(Math.PI * 2.0) // returns 360.0
The signature of the toDegrees() method is as follows :
public static double toDegrees(double a)
The toRadians() method takes an argument representing an angle in degrees and returns the equivalent angle in radians for example :
Math.toRadians(360.0) // returns 6.283185, which is 2 * Math.PI
The signature of the toRadians() method is as follows:
public static double toRadians(double a)
The many methods are there :These are static methods .
- double ceil ( double a )
- double floor ( double a )
- double random ( )
- double abs ( double a )
- float abs ( float a )
- int abs ( int a )
- long abs ( long a )
- double max ( double a, double b )
- float max ( float a, float b )
- int max ( int a, int b )
- long max (long a, long b )
- double min ( double a, double b )
- float min ( float a, float b )
- double sqrt ( double a )
- int min ( int a, int b )
- long min ( long a, long b )
- double toDegrees ( double angleInRadians )
- double toRadians ( double angleInDegrees )
- double tan ( double a )
- double sin ( double a )
- double cos ( double a )
- double sqrt ( double a )
- int round ( float a )
- long round ( double a )
Math class is basically many facts are there : Which programs demonstrate some of the unusual results that can occur when pushing some of the limits of the Math class or performing mathematical functions that are on the edgedouble d;
float p_i = Float.POSITIVE_INFINITY; // The floating point classes have
double n_i = Double.NEGATIVE_INFINITY; // these three special fields.
double notanum = Double.NaN; // They can be Float or Double
if ( notanum != notanum ) // ** NaN isn\'t == to anything, not
// even itself!
System.out.println(\"NaNs not equal\"); // result is \"NaNs not equal\"
if ( Double.isNaN(notanum)) // Float and Double have isNan()
// methods to test for NaNs
System.out.println(\"got a NaN\"); // result is \"got a NaN\"
d = Math.sqrt(n_i); // square root of negative infinity?
if ( Double.isNaN(d) )
System.out.println(\"got sqrt NaN\"); // result is \"got sqrt NaN\"
System.out.println( Math.sqrt(-16d)); // result is \"NaN\"
System.out.println( 16d / 0.0 ); // ** result is (positive) \"Infinity\"
System.out.println( 16d / -0.0 ); // ** result is (negative) \"-Infinity\"
// divide by 0 only works for floating point numbers
// divide by 0 with integer numbers results in ArithmeticException
System.out.println(\"abs(-0) = \"+ Math.abs(-0)); // result is \"abs(-0) = 0\"
The wrapper classes in the Java API serve two primary purposes :
- To provide a mechanism to wrap primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
- To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
In the java language all primitives have a wrapper classes. the wrapper class is basically a instances for using the classes like int is Integer, for float is Float, and so on.
Remember that the primitive name is simply the lowercase name of the wrapper except for char, which maps to Character, and int, which maps to Integer.
For the creating wrapper class we need to know three main things , Its a common approach ,but some approaches take a String representation of a primitive as an argument.
Which is take a String throw NumberFormatException.
The wrapper class xcept character provide constructors, two constructors are main which is flowing here :
- 1st that takes a primitive of the type being constructed.
- 2nd that takes a String representation of the type being constructed.
Float f1 = new Float(3.14f);
Float f2 = new Float(\"3.14f\");
--------------------------------------------------
Primitive |Wrapper Class |Constructor Arguments|
--------------------------------------------------
boolean |Boolean |boolean or String |
--------------------------------------------------
byte |Byte |byte or String |
--------------------------------------------------
char |Character |char |
--------------------------------------------------
double |Double |double or String |
--------------------------------------------------
float |Float |loat or String |
--------------------------------------------------
int |Integer |int or String |
--------------------------------------------------
long |Long |long or String |
--------------------------------------------------
short |Short |short or String |
--------------------------------------------------
The Character class provides only one constructor, which takes a char as an argument for example,Character c1 = new Character(\'c\');
The valueof() methods is basically static method which is provide a most of wrapper classes for crating a wrapper object and also give us a another approaches for making a wrapper classes.
Which approaches mainly represented only String representation . Its a first argument and the second argument method takes a additional argument like int radix. Which is use for the representation its mainly use offer the indicate whats the suffix use in the first argument is represented for example.Integer i2 = Integer.valueOf(\"101011\", 2);
// converts 101011 to 43 and assigns the value 43 to the
// Integer object i2
or
Float f2 = Float.valueOf(\"3.14f\"); // assigns
3.14 to the Float object f2
When we would like to convert the value of a wrapperd numeric to a primitive.
These methods are most likely and closely related with each other.that exists in all of the numeric wrapper classes (plus Boolean)both takes a string as an argument.throw a NumberFormatException if the String argument is not properly formed, and can convert String objects from different bases (radix), when the underlying primitive type is any of the four integer types:
The difference between the two methods is
- parseXxx() returns the named primitive.
- valueOf() returns a newly created wrapped object of the type that invoked the method.
tosting()method is already have a many java classes .cos its to important and asy to use for it .This method allowed to us to get some meaningful representation of a given object.For instance, if we have a Collection of various types of objects, We can loop through the Collection and print out some sort of meaningful representation of each object using the toString() method, which is guaranteed to be in every class.All of the wrapper classes have a no-arg, nonstatic, instance version of toString(). This method returns a String with the value of the primitive wrapped in the object—for instance : Double d = new Double("3.14"); System.out.println("d = " + d.toString() ); // result is "d = 3.14"
The Integer and Long wrapper classes let we convert numbers in base 10 to other bases. These conversion methods, toXxxString(), take an int or long, and return a String representation of the converted number, for example :String s3 = Integer.toHexString(254); // convert 254 to hex
System.out.println(\"254 in hex = \" + s3); // result is \"254 in hex = fe\"
String s4 = Long.toOctalString(254); // convert 254 to octal
System.out.println(\"254 in octal = \"+ s4); // result is \"254 in octal = 376\"
equals()
> java.lang.String
> java.lang.Boolean all wrappers
> java.lang.Object.
We always compare the primitive values using this method.Primitive variables are stored in memory as some absolute number of bits, depending on the type of primitive being handled.
We can also say like this that we can\'t know from one Java implementation to the next how big a reference variable is it might be 64 bits, it might be 97 bits.but the key thing to remember is that wherever a Java program might run, all of the reference variables running on a single VM will be the same size (in bits) and format.
When two String objects have the same value. When we are using == this operators is called the equal() method.
When we want to determine if two objects are meaningfully equivalent, use the equals() method. this operator returns a boolean value true this means that that are equal .if returns false .that means its doent.here we have a code .that are following here :String x1 = \"abc\";
String x2 = \"ab\";
x2 = x2 + \"c\";
The class object is very important of the all classes.which has an equals() method.That means every other Java class inherits an equals() method. In java.lang, the String and wrapper classes have overridden the equals() method to behave as we just discussed.
Hashcode method is basically use for the Distinguish between correct and incorrect implementations. Every exception, every event, every array extends from java.lang.Object.We don\'t need to know every method in Object, but we will need to know about the methods l
Override tosting() method is calling when we need to mere mortal to be able to read something meaningful about the objects of our class.Code can call toString() on our object when it wants to read useful details about our object.for the example we have a example :
public class HardToRead {
public static void main (String [] args) {
HardToRead h = new HardToRead();
System.out.println(h);}
}
Now we discuss to how comparing the two object references using the == operator evaluates true only when both references refer to the same object.We saw that the String class and the wrapper classes have overridden the equals() method. so that we could compare two different objects to see if their contents are meaningfully equivalent.
When we really need to know if two references are identical, use ==. But when we need to know if the objects themselves are equal, use the equals() method. For each class we write, we must decide if it makes sense to consider two different instances equal.For some classes, we might decide that two objects can never be equal.
Its a type of potential limitation.if we don\'t override equal() method.you won\'t be able to use the object as a key in a hashtable.
The equals() method in Object uses only the == operator for comparisons,so unless we override equals(), two objects are considered equal only if the two references refer to the same object.
If we would like to objects of our class to be used as keys for a Hashtable,then we must override equals() so that two different instances can be considered the same.
Now we would like to decide to override equals() in our class. It might look something like this :
public class EqualsProg {
public static void main (String [] args) {
Moof one = new Moof(8);
Moof two = new Moof(8);
if (one.equals(two)) {
System.out.println(\"one and two are equal\");
}
}
}
class Moof {
private int moofValue;
Moof(int val) {
moofValue = val;
}
public int getMoofValue() {
return moofValue;
}
public boolean equals(Object o) {
if ((o instanceof Moof) && (((Moof)o).getMoofValue()
== this.moofValue)) {
return true;
} else {
return false;
}
}
}
Pulled straight from the Java docs, the equals() contract says :
- It is reflexive
- It is symmetric
- it is transitive.
- It is consistent
- For any non null reference value.
hashcode() value of an object is basically use for the some collections classes.
Even we can think of it as kind of an object ID number, it isn\'t necessarily unique.
Collections such as HashMap and HashSet use the hashcode value of an object to determine where the object should be stored in the collection, and the hashcode is used again to help locate the object in the collection.
Collections is basically a framework in the java programming language.The Collections Framework in the java.util package is loaded with interfaces and utilities.
Now we are discussing about the implementation of he hashcode(). hashcode () is simply use for the comparison. we have a code for the hashCode().class HasHash {
public int a;
HasHash(int xVal) {
a = aVal;
}
public boolean equals(Object o) {
HasHash h = (HasHash) o; // Don\'t try at home without
// instanceof test
if (h.a == this.a) {
return true;
} else {
return false;
}
}
public int hashCode() {
return (a * 22);
}
}
Because the equals() method considers two objects equal if they have the same a value, we have to be sure that objects with the same a value will return identical hashcodes.
hashCode() contract is basically use for the drum roll.........
When its invoked in the java application then its application is in execution mode.Its must be consistently return the same integer, provided no information used in equals() comparisons on the object is modified.
If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
There are a few basic operations you will normally use with collections:
- Add objects to the collection.
- Remove objects from the collection.
- Find out if an object (or group of objects) is in the collection.
- Retrieve an object from the collection (without removing it).
- Iterate through the collection, looking at each element (object) one after another.
Now we are discussing abut key interfaces of the collection frame work .Its a important to know whats the purpose of the each of the key interfaces and also use the collections and we also know that how can i choose based on a stated requirement.
The collections API begins with a group of interfaces, but also gives us a truckload of concrete classes. that interface are six which is flowing here:
- Collection
- Set
- Sorted Set
- List
- Map
- Sorted Map
--------------------------------------------------
Map Impl. |Set Impl. | list impl. |
-------------------------------------------------
HashMap |HashSet |ArrayList |
-------------------------------------------------
Hashtable |LinkedHashSet |Vector |
-------------------------------------------------
TreeMap |TreeSet |LinkedList |
-------------------------------------------------
LinkedHashMap | | |
-------------------------------------------------
Not all collections in the Collections Framework actually implement the Collection interface. In other words, not all collections pass the IS-A test for Collection.
The sorted means basically the values are in list systematically in order . like if we would like to take a alphabetical order the A comes before b and f comes before g.
For a collection of String objects, then, the natural order is alphabetical.
For Integer objects, the natural order is by numeric value
if the collection is in the orders it means we can iterate through the collection in a specific (not-random) order.
A Hashtable collection is not ordered. Although the Hashtable itself has internal logic to determine the order.
We won\'t find any order when you iterate through the Hashtable. An ArrayList, however, keeps the order
established by the elements index position.
A List cares about the index.firstly the most imp thing is list has that non list is a set of methods related to the index,Those key methods include things like get(int index), indexOf(), add(int index, Object obj), etc.
All three List implementations are ordered by index position a position that we determine either by setting an
object at a specific index or by adding it without specifying position, in which case
the object is added to the end.
Arraylist is basically give us a fast iteration and fast random access.its a growable array .
Vector is the very old concept in the java java language.
Vector and Hashtable were the two original collections.its much similar ike a array list but its something difference its a synchronized for thread safety.
Vector is the only class other than ArrayList to implement RandomAccess.
A LinkedList List is basically ordered by index position.Its similarly like Vector is the only class other than ArrayList to implement RandomAccess.this linkage gives us new method.for adding and removing from beginning or end.
Sets basically cares about the uniqueness,.Its never allowed duplicate.Set have a three sets which implementations are described in the following sections.these are following as:
- Hash Set
- LinkedHashSet
- TreeSet
Its a basically unsorted , its also unordered set.It mainly use for inserting the object of hashcode, so the more efficient our hashCode() implementation the better access performance we\'ll get.
Linked List is basically a orders set of hash set .its mainly use for the maintains a doubly-linked List across all elements. We can construct a LinkedHashSet so that it maintains the order in which elements were last accessed, rather than the order in which elements were inserted.
Tree set is basically a two sorted collection , for this tree set its used Red-Black tree structure, and its guaranteed that its elements are in the ascending order , according to the neutral order of the elements.
Map is an unique identifier.This unique key have a specific value.Those keys and values are of the course objects.Its very much familiar with maps. Its any support language to a data structures that use a key/value or name/value pair.
Hash map is basically gives us a unsorted ans unordered map.When we need to the map and i don\'t want an to the go in the order then hash map is the best way to go .
HashMap allows one null key in a collection and multiple null values in a collection.
Hashtable is basically like a vector .Its in the java from prehistorical time.
Vector is a synchronized
Hashtable doesn\'t let us have anything that\'s null.
Its a basically a counter part of LinkedHashSet.Its manly use for the collections maintenance of the insertion order.
Its slower than HashMap for adding and removing elements, We can expect faster iteration with a LinkedHashMap.
Tree map is basically a sorted map.We know that sorted by the natural order of the elements.
But like TreeSet, TreeMap lets we pass our own comparison rules in when we construct a TreeMap, to specify how the elements should be compared to one another when they are being ordered.
Garbage Collection is basically a State the behavior that is guaranteed by the system.Its mainly use for the Write code that explicitly makes objects eligible for garbage collection.
Recognize the point in a piece of source code at which an object becomes eligible for garbage collection.
Memory management : .Java\'s garbage collector provides an automatic solution to memory management.
When we are discussing about garbage collection in the java then we find out the garbage collection is the phrase used to describe automatic memory management in Java.
When we going to execute the s/w program it uses memory in several different ways.
it\'s typical for memory to be used to create a stack, a heap, in Java\'s case constant pools, and method areas.
The heap is that part of memory where Java objects live, and it\'s the one and only part of memory that is in any way involved in the garbage collection process.
The garbage collector is basically work on the under Java virtual machine.when its running or not its up to only JVM.Its totally up to the JVM .its not guaranteed that we want to know when garbage collection is start to running.
We cant say surly when its work.We know that garbage collector uses a mark and sweep algorithm, When we are seeing about the java implementation its true but in the case of java specification we cant sure abut the java implementation.
We also know that garbage collector uses reference counting;The important concept is which we must to know that when does an object become eligible for garbage collection.Its ans is the thread.We cans say that every Java program has from one to many threads,Each thread has its own little execution stack. The garbage collector does some magical, unknown operations, and when it discovers an object that can\'t be reached by any live thread it will consider that object as eligible for deletion, and it might even delete it at some point.When we are discussing about reaching an object, we\'re really talking about having a reachable reference variable that refers to the object in question. If our Java program has a reference variable that refers to an object ,and that reference variable is available to a live thread, then that object is considered reachable.
We also know that the an object becomes eligible for garbage collection when there are no more reachable references to it. Obviously, if there are no reachable references, it doesn\'t matter what happens to the object. We have a some code which is xplain something which is useful for us:
public class GarbageTruck {
public static void main(String [] args) {
StringBuffer sb = new StringBuffer(\"hello\");
System.out.println(sb);
// The StringBuffer object is not eligible for collection
sb = null;
// Now the StringBuffer object is eligible for collection
}
}
In this code StringBuffer which is an object , which have a value Helo , thats assigns reference variable sb in the third line.Even rest of code doesn\'t use the StringBuffer .Its not imp for the garbage collection.
Its also a decouple a reference variable from an object by setting the reference variable to refer to another object.we have a following code :class GarbageProg {
public static void main(String [] args) {
StringBuffer a1 = new StringBuffer(\"hello this is my first garbage programe \");
StringBuffer a2 = new StringBuffer(\"welcome to my progarme \");
System.out.println(a1);
// At this point the StringBuffer \"hello this is my first grambage progame \" is not eligible
a1 = a2; // Redirects a1 to refer to the \"welcome to my programe \" object
// Now the StringBuffer \"hello this is my first garbage programe \" is eligible for collection
}
}
When we are created an object then we need to the method.When the method is invoked the local variable is automatically created exist only for the duration of the method.Once the method has returned, the objects created in the method are eligible for garbage collection.
its a diff way for the objects can become eligible for garbage collection even if they still have valid references!. We also know that the islands of isolation.
We have a code its very simple example for the call instance
public class Island {
Island a;
public static void main(String [] args) {
Island a2 = new Island();
Island a3 = new Island();
Island a4 = new Island();
a2.a = a3; // a2 refers to a3
a3.a = a4; // a3 refers to a4
a4.a = a2; // a4 refers to a2
a2 = null;
a3 = null;
a4 = null;
// do complicated, memory intensive stuff
}
}
When the code reaches // do complicated, the three Island objects have instance variables so that they refer to each other, but their links to the outside world have been nulled. These three objects are eligible for garbage collection.
firstly we would like to mentioned that contrary to this section\'s title, garbage collection cannot be forced.
When java provides some ,method that allow us to request that the JVM perform garbage collection, if we are about to perform some time-sensitive operations, we want to probably minimized to the chances which is use for the delay of the garbage collection. but we also know that the methods that Java provides are requests, and not demands.
java provides us to some mechanism for the run some code just before our object is deleted by the garbage collector, which method is use for that. that name is finalize() method,its mainly for the all classes inherit from class.
Object we have a main prob is that we may have gathered by now, we can\'t count on the garbage collector to ever delete an object.
So, any code that we put into our class\'s overridden finalize() method is not guaranteed to run.its method use for the running a any object but its not guaranteed.
We have two concepts for the finalize() method which is following here:
- For any given object, finalize() will be called only once by the garbage collector.
- Calling finalize() can actually result in saving an object from deletion.
firstly we know that the when we put any code in the normal method we can put this code in the finalized method.We could write code that passes a reference to the object in question back to another object, effectively unintelligible the object for garbage collection.
The garbage collector, however, will remember that, for this object, finalize() already ran, and it will not run finalize() again.
Inner Class mainly use for the flexibility/extensibility.
We can also said that a class should have codeonly for the things an object of that particular type needs to do; any other behavior should be part of another class better suited for that job.
If we would like to explain the inner class then we can see the best example for the Event handler.
Regular is basically use for the inner class..
- static
- method local
- anonymous
We can see other sections also we will just use the term inner class and drop theregular.its syntax somehting like this :
class MyOuter {
class MyInner { }
}
Inner class is always declare in the curly braces the outer class like above example.if we would like to compile this code we can see :
%javac MyOuter.java
We you ll end up with two class files:
> MyOuter.class
> MyOuter$MyInner.class
the inner class is simply the last class of the program , its in the end.its a mainly separate class that y class file is the generated. like :
%java MyOuter$MyInner
The only way we can access the inner class is through a live instance of the outer class! In other words, only at runtime when there s already an instance of the outer class to tie the inner class instance to.
Inner class is basically a instance for the instantiate.In every program have a instance of the outer class to tie to the inner class.here no exceptions are in this rule .
An inner class instance can never stand alone without a direct relationship with a specific instance of the outer class.
IN the outer class that its creates instances of the outer class, because outer class also wants to use instance class for the helper object.
We will modify the MyOuter class to instantiate an instance of MyInner :class MyOuter {
private int a = 7;
public void makeInner() {
MyInner in = new MyInner();
in.seeOuter();
}
class MyInner {
public void seeOuter() {
System.out.println(\"Outer a is \" + a);
}
}
}
If we want to create an instance of the inner class, we must have an instance of the outer class. we want instantiate the inner class from a static method of the outer class or from any
other code in any other class. Inner class instances are always handed an implicit
reference to the outer class.The code to make an instance from anywhere outside nonstatic code of the outer class is simple, but we must memorize this for the exam!public static void main (String[] args) {
MyOuter mo = new MyOuter();
MyOuter.MyInner inner = mo.new MyInner();
inner.seeOuter();
}
- The keyword this can be used only from within instance code. In other words, not within static code.
- The this reference is a reference to the currently-executing object. In other words, the object whose reference was used to invoke the
- currently-running method.
- The this reference is the way an object can pass a reference to itself to some other code, as a method argument:
public void myMethod() {
MyClass mc = new MyClass();
mc.doStuff(this); // pass a ref to object running myMethod
}
A regular inner class is a member of the outer class just as instance variables and methods are, so the following modifiers can be applied to an inner class :except static turns it into a top-level nested class rather than an inner class.
- final
- abstract
- public
- private
- protected
- static
A regular inner class scoped basically in the inside in other class of the curly braces.but method code in the out side. this is also defined as a method . we can see in this code :
class MyOuter {
private String a = \"Outer\";
void doStuff() {
class MyInner {
public void seeOuter() {
System.out.println(\"Outer a is \" + a);
} // close inner class method
} // close inner class definition
} // close outer class method doStuff()
} // close outer class
A method-local inner class can be instantiated only within the method where the inner class is defined. no other code running in any other method inside or outside the outer class can ever instantiate the method-local inner class.
The inner class object cannot use the local variables of the method the inner class is in.
The local variables of the method live on the stack, and exist only for the lifetime of the method, When the method ends, the stack frame is blown away and the variable is history.Unless the local variables are marked final! The following code attempts to access a local variable from within a method-local inner class :class MyOuter {
private String a = \"Outer\";
void doStuff() {
String b = \"local variable\";
class MyInner {
public void seeOuter() {
System.out.println(\"Outer a is \" + a);
System.out.println(\"Local variable b is \" + a); // Won\'t Compile!
} // close inner class method
} // close inner class definition
} // close outer class method doStuff()
} // close outer class
When this code is compile the :
MyOuter.java:8: local variable b is accessed from within inner class;
needs to be declared final
System.out.println(\"Local variable b is \" + b);
^
make a local variable b as final fixes the prb :
final String b = \"local variable\"; // Now inner object can use it
In the java programming language inner classes declared without any class name at all.And if that\'s not weird enough, we can even define these classes not just within a method, but within an argument to a method. The most important job here is to learn to not be thrown when we see the syntax. The exam is littered with anonymous inner class code; we might see it on questions about threads,wrappers, overriding, garbage collection, and we get the idea.
firstly we should know this code:-
class Maggie {
public void pop() {
System.out.println(\"Maggie\");
}
}
class Food {
Maggie m = new Maggie() {
public void mag() {
System.out.println(\"anonymous Maggie\");
}
};
}
Now we accusing about whats the happening in this code :here most impotent thing is :
- here two classes are mentioned maggie and food.
- maggie has one method mag()
- Food has one instance variable, declared as type maggie.
- That\'s it for Food. Food has no methods.
Maggie reference variable refers not to an instance of Maggie, but to an instance of an anonymous subclass of Maggie.
Here both of flavour ahev a main and one and only one most important diffrece is that : flavor one creates an anonymous subclass of the specified class type, whereas flavor two creates an anonymous implementer of the specified interface type. see this example :interface Cookable {
public void cook();
}
class Food {
Cookable c = new Cookable() {
public void cook() {
System.out.println(\"anonymous cookable implementer\");
}
};
}
class MyWonderfulClass {
void go() {
Bar b = new Bar();
b.doStuff(AckWeDon\'tHaveAFoo!); // Don\'t try to compile this at home
}
}
interface Foo {
void foof();
}
class Bar {
void doStuff(Foo f) { }
}
We know that static nested class is referred to as top-level nested classes, or static inner classes, but they really aren\'t inner classes at all.While an inner class enjoys that special ,a static nested class does not.
It is simply a non interrelationship with the outer class,class scoped within another. So with static classes it\'s really more about name-space resolution than about an implicit relationship between the two classes,class BigOuter {
static class Nested { }
}
The syntax for instantiating a static nested class is as much like a normal nested class its a very little different from a normal inner class,, we can see this code :
class BigOuter {
static class Nested { }
}class Broom {
public static void main (String [] args) {
BigOuter.Nested n = new BigOuter.Nested(); //Use both class names
}
}
for the writing code to define , its instantiate , and start for new threads we are using two threads which are following as :
- java.lang.Thread
- java.lang.Runnable
That the thread have a quality of single thread runtime enviorment , in this quality 1st action is performed and second 1 is performed when 1st one is cmpletly end.
In the java programming language thread means two different things, which are following as :
> An instance of class java.lang.Thread
> A thread of execution
first in the java language we are using the instance of java.lang.Thread for the thread. then we have to find the methods of thread classes which are managing thread including creating, starting, and pausing them.we have a many methods which are following them :
- start()
- yield()
- sleep()
- run()
We can define and instantiate a thread in one of two ways :
Extend the java.lang.Thread class
Implement the Runnable interface
for the discussing the thread we need a place to put our run method.now we are discussing about the Extending java.lang.Thread method and classes .
The simplest way to define code to run in a separate thread is to :
- Extend the Thread class.
- Override the run() method.
we can also see in this way :
class MyThread extends Thread {
public void run() {
System.out.println(\"Important job running in MyThread\");
}
}
In this approach some limitations that\'s are if we extend Thread,we cant can\'t extend anything else,And it\'s not as if we really need that inherited Thread class behavior, because in order to use a thread we will need to instantiate one anyway.
Now we are discussing about second method which is Implementing java.lang.Runnable.Implementing the Runnable interface gives us a way to extend from any class we like, but still define behavior that will be run by a separate thread. It looks like this :
class MyRunnable implements Runnable {
public void run() {
System.out.println(\"Important job running in MyRunnable\");
}
}
Every thread when its execution is start this is as an instance of thread class.its our run() method is in a Thread subclass or a Runnable implementation class.
If we extended the Thread class,instantiation is dead simple:MyThread t = new MyThread();
There are some additional overloaded constructors, but we will look at those in a moment.
When thread object is created and its also know as whatsits target .That time its lauch a new call stack It\'s so simple it hardly deserves its own subhead:
t.start();
Here are some stuffs are going on:
- A new thread of execution starts.
- The thread moves from the new state to the runnable state.
- When the thread gets a chance to execute, its target run() method will run.
Staring more than one thread means that multiple thread are working at a time.
Here we have a one code in which three thread instances are gogn and its create a sngle runnable instance.all thrad instance working in a same runnable instance but each have a unique name.and at the last all thread started by invoking start().
class NameRunnable implements Runnable {
public void run() {
for (int a = 1; a < 4; a++) {
System.out.println(\"Run by \" + Thread.currentThread().getName());
}
}
}
public class ManyNames {
public static void main (String [] args) {
NameRunnable nr = new NameRunnable(); // Make one Runnable
Thread one = new Thread(nr);
one.setName(\"tom\");
Thread two = new Thread(nr);
two.setName(\"serah\");
Thread three = new Thread(nr);
three.setName(\"john\");
one.start();
two.start();
three.start();
}
}
When this code is running mode the we get :
% java ManyNames
Run by Tom
Run by Tom
Run by Tom
Run by serah
Run by serah
Run by serah
Run by john
Run by john
Run by john
Its a part of the java virtual machine .its have a authority of decision,decides which thread should run at any given moment, and also takes threads out of the run state,we can see in the single processor machine only one thread running at a time and also in the one time only one stack is running.
When we say eligible, we really mean in the runnable state.
Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be chosen to the currently running thread. And just so we are clear about how little is guaranteed here:
The order in which runnable threads are chosen to run is not guaranteed.
We can see the some methods are follows the rules of influence thread scheduling, we can see in the following codepublic static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join()
public final void setPriority(int newPriority)
We have a some methods in which thread method inherits he class in the java programming language. These three thread-related methods are following here :
- public final void wait()
- public final void notify()
- public final void notifyAll()
The wait() method has three overloaded versions.which are following here :
> new
> runnable
> dead
In the java programming language we have a 5 thread stages . in this list we can see all thread stages :
- new
- runnable
- running
- waiting/blocked/sleeping
- dead
The preventing thread execution is basically term that recognize conditions that might prevent a thread from executing. That\'s why we are using this .Now we can see many times that when the thread running in the non runnable state and that time our thread is going to dead state .
I am not talking about the stop state.A thread that\'s been stopped usually means a thread that\'s moved to the dead state.when a thread will get kicked out of running but not sent back to either runnable or dead.The we are concerning here :
- Sleeping
- Waiting
- Blocked because it needs an object\'s lock
This method is a like static method for the thread.we use it for the our code to slow a thread down by forcing it to go into a sleep mode before coming back to runnable.When a thread sleeps, it drifts off somewhere and doesn\'t return to runnable until it wakes up.
For the invoking we would like to go for static Thread.sleep() method, giving it a time in milliseconds as follows :try {
Thread.sleep(5*60*1000); // Sleep for 5 minutes
} catch (InterruptedException ex) { }
Threads always run with some priority , represented usually as a number between 1 The scheduler in most JVMs uses preemptive, priority based scheduling. This does not mean that all JVMs use time slicing.
The JVM specification does not require a VM to implement a time-slicing scheduler, where each thread is allocated a fair amount of time and then sent back to runnable to give another thread a chance.
Although many JVMs do use time slicing, another may use a scheduler that lets one thread stay running until the thread completes its run() method.and 10. scheduler might do one of the following:
- Pick a thread to run, and keep it there until it blocks or completes its run() method
- Time slice the threads in the pool to give everyone an equal opportunity to run.
A thread gets a default priority that is the priority of the thread of execution that creates it.
For example, in the codepublic class TestThreads {
public static void main (String [] args) {
MyThread t = new MyThread();
}
}
The thread referenced by t will have the same priority as the main thread, since the main thread is executing the code that creates the MyThread instance.
We can also set a thread\'s priority directly by calling the setPriority() method on a Thread instance as follows:FooRunnable r = new FooRunnable();
Thread t = new Thread(r);
t.setPriority(8);
t.start();
Its a basically nonstatic method in the java language.its a thread which thread join onto the end of another thread.
If we have a another thread that can\'t do its work until another thread as completed its work, then we want to first thread to join another thread.this means that anther thread will not be runnable until first thread has finished.Thread t = new Thread();
t.start();
t.join();
synchronizing code is basically use for the writing code using synchronized, wait, notify, and notifyAll to protect against concurrent access problems and to communicate between threads.
We have basically a two different threads have access to a single instance of a class, and both threads invoke methods on that object and those methods modify the state of the object.
In other words, what might happen if two different threads call, say, a setter method on a single object.
A scenario like that might corrupt an object\'s state.and if that object\'s state is data shared by other parts of the program, well, it\'s too scary to even visualize.
We have a two steps foe the withdrawal checking the balance and making the withdrawal are never split apart.
We need them to always be performed as one operation, even when the thread falls asleep in between step 1 and step 2!
We call this an atomic operation because the operation, regardless of the number of actual statements,is completed before any other thread code thatacts on the same data.
We can\'t guarantee that a single thread will stay running throughout the entire atomic operation.
But we can guarantee that even if the thread running the atomic operation moves in and out of the running state, no other running thread will be able to act onthe same data.
now we are discussing about syncronisaiton works with licks.in the java programming language every object have a built in lock.its only we use when object has a syncronised code. until they have only 1 lock per object.if at a tym one thread pick the lock then that tym no other thread sncronised the lock.At that point, the lock is free until some other thread enters a synchronized method on that object. We need to remember the following key points about locking and synchronization : > Only methods can be synchronized, not variables. > Each object has just one lock. > Not all methods in a class must be synchronized. A class can have both synchronized and nonsynchronized methods. > If two methods are synchronized in a class, only one thread can be accessing one of the two methods. In other words, once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class. > If a thread goes to sleep, it takes its locks with it. > A thread can acquire more than one lock. > We can synchronize a block of code rather than a method.
yes .Static method is synchronized.
Here only one copy for the synchronized data which is we can trying for protect so we would like to need only one lock for the per class for the synchronization of static methods.and its a lock for the per class.
Here we have a such locks which is every class loaded. in the java programming language corresponding to the object uses a instances of java.lang.Class representing that class.
About synchronized the block of code .here many steps for that :
- Create a class and extend the Thread class.
- Override the run() method of Thread. This is where the synchronized block of code will go.
- For our three threaded objects to share the same object, we will need to create a constructor that accepts a StringBuffer object in the argument.
- The synchronized block of code will obtain a lock on the StringBuffer object from step 3.
- Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer.
- Finally, in the main() method, create a single StringBuffer object using the letter A, then create three instances of our class and start all three of them.
If any thread enter the synchronized method and its also have a lock then the thread also going to the locked on an objects lock.
This thread is going on the particular objects.and wait there until the lock is released and going on the runnable state.
Dead lock is the something horror in the java language.its like a stage which is occur when two threads are block.with each waiting for the others lock Neither can run until it gives up the lock, so they\'ll sit there forever and ever and ever.
This can happen, for example, when thread A hits synchronized code, acquires a lock B, and then enters another method that s also synchronized. But thread A can\'t get the lock to enter this synchronized code lock C because another thread D has the lock already...................................................
Give Up | Keep Locks | Class Defining |
Locks | | the Method |
-------------------------------------------------|
wait() | notify() |java.lang.object |
--------------------------------------------------
| join() |java.lang.Thread |
--------------------------------------------------
| sleep() |java.lang.Thread |
--------------------------------------------------
| yield() |java.lang.Thread |
--------------------------------------------------
Thread integration basically define the and explain the infraction b/e thread and object lock.when executing synchronized wait, notify, and notifyAll.
The last thing we need to look at is how threads can interact with one another to communicate about among other things their locking status.
The java.lang.Object class has three methods, which are following here:
- wait()
- notify()
- notifyAll()
That help threads communicate about the status of an event that the threads care about. One key point to remember (and keep in mind for the exam) about wait/notify is this :
- wait()
- notify()
- notifyAll()
The must be called from within a synchronized context! A thread can\'t invoke a wait or notify method on an object unless it owns that object\'s lock.
In this topic we know that notify all of the threads which thread are waiting on a particular object.if its correct then we can use notifyAll() on the object to let all the threads rush out of the waiting area and back to runnable.
notifyAll(); // Will notify all waiting threads--------------------------------------------------
Class Object | Class Thread |Interface Runnable|
--------------------------------------------------
wait() | start() | run() |
--------------------------------------------------
notify() | yield() | |
--------------------------------------------------
notifyAll() | sleep() | |
--------------------------------------------------
| join() | |
-------------------------------------------------
New thread state is the state basically the thread in this stage exactly not alive means its alive as a Thread object.but in this condition its not yet thread of execution.that\'s y we consider that time its not alive. this state mainly thread is in after the Thread instance has been instantiated, but the start() method has not been invoked on the thread.
Runnable state basically which state when our thread ready for the run .But in that time also thread scheduler didn\'t select for the running state .When the thread is enters the in this state the start method is invoked.When the thread is in the runnable state, it is considered alive.
In this state thread is now ruining state and also thread scheduler select it for there the running state.
The thread may be blocked waiting for a resourcein which case the event that sends it back to runnable is the availability of the resource for example, if data comes in through the input stream the thread code is reading from, or if the object\'s lock suddenly becomes available.A thread may be sleeping because the thread\'s run code tells it to sleep for some period of time, in which case the event that sends it back to runnable is that it wakes up because its sleep time has expired. Or the thread may be waiting, because the thread\'s run code causes it to wait, in which case the event that sends it back to runnable is that another thread sends a notification that it may no longer be necessary for the thread to wait.
The important point is that one thread does not tell another thread to block. There is a method, suspend(), in the Thread class, that lets one thread tell another to suspend, but the suspend()method has been deprecated and won\'t be on the exam (nor will its counterpart resume()). There is also a stop() method, but it too has been deprecated and we won\'t even go there. Both suspend() and stop() turned out to be very dangerous.
When the running method is completely end then we use this state .That\'s means the thread is dead,now a time its also a thread object but its not for the execution.Once a thread is dead, it can never be brought back to life! if we \'ll invoke start() on a dead Thread instance, we will get a runtime exception. And it probably doesn\'t take a rocket scientist to tell us that if a thread is dead, it is no longer considered to be alive.
Source file declaration have a may rules for the declaring class ,import statement ,and packages statements .
Here only be public class for the each source code file.
The comments always appears only in beginning or end of any source code line
Must match the public class an me and file name.
The package statement must be the first line in a source code file.
Must be import statement go b/w in the package statement and class declaration.import and packages they must apply to all classes with in the source file.
A file can have more than one non public class.
When a lass is in the default access then that time when we are declaration time we don\'t have an.
A class is which declare the public keyword for the all cases from all packages access to a public class.
In other word we can say that all classes in the JAVA UNIVERSE have access to a public class.
Final keyword is basically a use for the class can\'t be subclasses.We can also say no other class can ever extend a final class.
If we are deeply dependent on the implementation of certain method then using final fives us the security that nobody can change the implementation out from under us.
An abstract class never be instantiated,its mainly purpose to be extended the subclass,coding with abstract subclass .
We take advantages of polymorphism and give us the greatest degree for the flexibility and extensibility.
We cant mark a class a other abstract and final.
They have a very similar but different meanings.An abstract class must be subclasses. where as final class must not be subclasses.
The combination of abstract and final modifier,used for the class or method declaration the code will not be compile.
We have a example where we can see that public default, final and abstract class.We create a abstract super class named Car and a concrete class named a Sporty.
The super class which is belong to the package called Car and sub class which can be belong to the default packages. We have a some steps which is following here :
Create a super class follows :package Car;
public abstract class Sporty{......}
Create a subclass in a separate file which is following :
import car.sporty;
class Vagnor extends Car{.......}
When we create an interface , We were defining a contract for the whats tech working in there and how is that working . The interface basically a contract , we can write an interface Bounceable.
When we would like to define any class to treat for the Bouneceable interface and provide code for the interface\'s two thing.
Interfaces can e implemented by any class, from any inheritance tree.this is we take a radically diff classes and give them a common characteristics.
We have a authority to put the constant in an interface.We have a guarantee that any class implementing the interface will have access to the some content.
By placing the constants in the interface .Any class implemented by the any packages for the implementing the java program and interface has direct access to the contents just similar as the class is the inherited them , We need to create a rule which is called as one key rule.
public static finale
The method argument are the variable declaration only its basically appear in between the parenthesis in the method declaration.Its very typical method for declaration, when we are using multiple arguments.
Public Record getRecord(int ile number, Int recnumber) {}
We can say method argument is similar ike a local variables , we can also see in the above example both variables means file number and rec number both follow this rule applied to local variable.This means that its can also have a modifiers final.
public Record getRecord(int fileNumber, Ffinal int recordNumber )
IN this example we can see that the variable recNumber is declared as final, and the modifies means reassigning the new value to the variable.
synchronize keyword basically shows its method can be accessed by only one thread at the time.All we concerned with is knowing with is knowing at the this method is applied sot he methods :
> not variable
> not classes
> just methods.
A typical synchronized declaration only use for the :
> public
> synchronized
synchronized modifier can be matched to the four access control.
A native modifier shows that the method is implementing in late form dependent code.We need to know that the native is a type of modifier and native cans be apply and applied the methods
> not class
> not variable
We know that the strictfp modifiers.but now we are discussing about individual method of stritfp.this is normally force floating point to adhere to the IEEE754 standerd with strictfp can predict how our floating point will behave regardless of the underlying platform the JVM is running on.
class AgedP {
_____ _____ _____ _____ _____
public AgedP(int x) {
_____ _____ _____ _____ _____
}
}
public clss Kinder extends AgedP {
_____ ____ ____ _____ _____ _____
public Kinder( int a){
_____ ____ ____ _____ _____ ___();
}
}
Fragments: Use the following fragments zero or more Times :
--------------------------------
| AgedP | Super | this | |
--------------------------------
| ( | ) | { | } |
--------------------------------
| ; | | | |
--------------------------------
class AgedP{
AgedP() {}
public AgedP(int a){
}
}
public class Kinder extends AgedP {
pblic Kinder(nt a) {
super ();
}
}
As there is no dropable file for the variable a and the parenthesis are already in place and empty there is no way to construct a call to the super class constructor that takes an argument , therefore the only renaming possibilities is to create a call tot he no-argument super class constructor. this is done as: super();. The line cannot be left blank , as the parenthesis are already in place
Encapsulation basically use for the help , Its mainly use for the implementation behind an interface. Encapsulate code have a main two most important features which is following here :
- Instances variable are kept protected.
- Getter and setter methods mainly provide the access to instance variable.
Inheritance basically use for the interchange to the class to be a subclass of a super class and here by we also can say to the inherit public ad protected variable and methods of the super class .
Its mainly concept is that polymorphism ad overridden casting .in this method all classes are subclasses of type objects and objects method.
Polymorphism basically stands for the \"Many forms\" its a type of reference variable its always of a single and unchangeable type and its can refer to the subtype objects.
The methods are working with both concepts abut this is not happening with the constructor.
In the method also some method is not the accept both of things .
Like final method is not be overridden.only inherited method may be overridden and we know also the private method are not inherited.
When we would like to implement the interface we should be complete the full application .Its implement by properly and concernedly overriding all of the methods defines by the interface.most important thing is a single class can implement many interface.
return type methods is basically use in the overloaded method but in this case its perfectly use but in the overridden methods are cant do it.
object reference return types ca accept null as a return value.
Its with an object reference return type, can return a subtype.,
A constructor is always invoked when the new object is created ts mainly use that time. costumer call the each superclass in an object inheritance. constructor have a same name as the class. constructor can use any access modifiers.in this time Instance members are accessible only after the super constructor runs.interface do not have a construct.
static method basically for the implement behavior that are not affected by the state of any instance.here only one value of the static variable.this method is cant access an instance variable directly. Its method also not overridden but they ca be redefined.
coupling refers tot he degree to which one class knows about or uses members of another class.its loose coupling is the desirable state of having classes that are well encapsulated minimize references to each there.tight coupling is the undesirable state of having classes that break the rules of loose coupling.
stack basically use for the Local variable its a mainly method variable its live on the stack.in the Heap case we know that its a type of object their instances variables live on the heap .
Literals basically many types are their but right now we can see that Integer literals can be decimal , its also can be octal for the example 013 or its can be see also in the hexadecimal for the example 0x3d.its only for the longs end L or 1.this is only for the Float literals for the end in F to f, and we use the literals end in a digit or D or d.int he boolean case we can see that true and false.and the Literals for the chars are a single charterer inside single quotes \'d\'.
Scope is basically refers to the life time of a variable. here we know that its have a mainly four basic scopes which is following here :
- static variables live basically as long as their class lives.
- instances variable live as long as their object lives.
- local variable live as long as their method is on the stack; however ,if their method invokes another method.they are temporarily unavailable.
- block variables live until the block completes.
We have a some important basic assignments are thee which is mainly recognize there :
- Literals integers are implicitly int.
- Integer expression always result in the int-sized result never smaller.
- Here we know also that the Floating point numbers are implicitly doubles.
- Compound assignment perform an automatic cast.
- Reference variable holds the bits that are used to the refer to an object.
When we would like to use the variable then an array of object is instantiated,objects are with in the array are not instantiated automatically but all the references get the default value is null.when an array of primitive is instantiated elements get default values.its always initialed with default value.
When we would like to passing the value in the methods then method can take primitives and or objects references as argument.Its arguments are always copies.
Its argument never actual objects.Its a primitive argument is another copy of a references of the original primitive.
Its references argument is another copy to the original attachments.and objects.
Array can hold basically primitive or objects but the array itself is always an object.
When we would like to declare an array that time we must remind that the brackets should be in the left and right of the name .
It is never legal to include the size of an array in the declaration .Elements in an array of objects are not automatically created.
We\'ll get the NUllPointException if we try to use an element in a object array .If that elements does not refer to a real object.its is indexed beginning with zero,Its an multidimensional arrays are just arrays of arrays.
The dimensional in a multidimentionals array can have sift lenghts.
Static initialization basically blocks run once.
When its class is first loaded.then instance initialization blocks run every time a new instances is created.
They run after all super constructors and before the constructors code has run .
If its multiple int blocks exists in the class they follows the rules a stated above AND they run in the order in which they appear in the source file.
The wrapper classes correlated tot he primitive types.Its have a two main functions :
- Its wrap primitives so that they can be handled like objects.
- To provide utility methods for primitives.
Wrappers are using most importance families method whch is three are there :- xxxValue()
- parseXxx()
- valueof()
Its primitive wining uses the smallest method argument possible.Its used mainly individually boxing and var-args are compatible with overloading.
We can\'t widen from one wrapper to the another type of wrapper.its cant widen an box.we can crate a box then widen .We can combine var-args either widening or boxing.
IN the programming language JAVA Garbage collection provides automated memory management.
Its mainly purpose of GC is to delete objects that cannot be reached.
Only the JVM decides when to run the GC we can only suggest it.We don\'t know exactly hats the GC also .
The object must be consider eligible before they can be garbage collection .an object is eligible when we must live thread can reach it .java application can run out the memory .
Relation Operator basically a always result in a boolean value.like true and false.
The are six relational operator >,>=,<=,==, and !=
The last two (== and !=) are some times reffed to as equality operator.Equality operator are mainly two types :
- There are two equality operators : == and !=.
- Four types of things can be tested: number , characters,booleans,and reference variable.
Instance is for the reference variable only and checks for the whether the object of of a particular type.this can be used only for the test object against class types that are i the same class hierarchy.its for an instances an object passes the instance of the test of any of its super class implement the interface of the right side of the instance of the operator.
There are four primary math operator which called arithmetic operator :
- Add
- Substact
- multyply
- divide.
The remind operator % returns the remainder of the division.its expression are evaluated form the left to right unless we add parenthesis are unless some operator in the expression have higher precedence then other.the *,/ and % operator have higher ta + and -.
String Concatenation Operator is basically a operand is the string this is the + operator concatenates the operands.its both of the operands are numeric and the + operator adds the operands.
Increment operator or decrement operator basically suing the two operators this is called :
- Prefix (-- or ++)
- Post fix(-- or ++)
The post fix use run before the value used in the expression .and prefix uses run after the value is used in the expression.In any expresseion both operands are fully evaluated before the oprator is applied.varaile marked final cannot be incremented or decremented.
Conditional operator is basically called the Ternary operator its mainly return the two values based on the whether a boolean expression is true or false.its have a two conditions which is following here :
- returns the value after the ? if the expression is true.
- returns the value after the : if the expression is false.
Logical operator basically 6 are there which is following here :
- &
- |
- ^
- !
- &&
- ||
These are operators are logical operators.Its work with two expression that must resolve the boolean value.The && and & opretor retuns true only if both operands are true.the || and | opratiors are return true if either or both operands are true,
ThreadPools are useful when you need to limit the number of threads running in your application. Built in thread pools in the java.util.concurrent package.
Thread pools address two different problems :-
They usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.
Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
A constructor is a member function of a class that is used to create objects of that class.
It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
A common example for a transient variable in Java involves the serialization of objects that contain sensitive or temporary data.
instanceof operator is used to check whether the object is an instance of the class or subclass or interface.
The instanceof is also known as type comparison operator because it compares the instance with type.
It returns either true or false.
instanceof operator with variable having null value, it returns false
StringBuffer
Yes! We can invoke the main() method of one class in another class. Since main() method is a static method, it can be invoked by using the class name with the method name.
In C command line arguments, values are passed in the main() method having the two parameters.One is int argc i.e. arguments count and the another is char *argv[] i.e. arguments vector which is an array of pointers to character strings.
The == and eqauls() method, both are used to check the equality of the two strings, but in the different sense.The eqauls() method put the two strings in the two different arrays and compare the characters one by one.
If all the characters are matched then this method will return true otherwise false.
The == operator checks whether the two strings points to the same the object or not. The == operator checks the bit pattern of the two references.
Abstract class is a class that can not be instantiated and having zero or more abstract method.It must be subclassed by other class implementing the abstract method.
The abstract class is modified by keyword \'abstract\'.
Interface can be think of as fully abstract class.All the method within the interface are abstract must end with a semicolon followed by parantheses.
If a class implement an Interface,it must provide the definition to all the methods of the interface or it must be the abstract class.
If you modify a variable or method by a static modifier it means there is only one copy of that variable or method shared by all theinstances of that class. A class can not be modified as static,but an inner class.A final variable is just like a constant. It\'s value can not be change once it is initialized. It must be initialized at the time of variable declaration or the constructor completed.
If you modify a class with a final keyword, it means, this class can not be subclassed. No class can inherit the features of the final class. If you try to this, an error will result.
Example:
package p1;
public final class FinalClass{public void show(){System.out.println(\"This is a final class.\"); } }
class FinalSub extends FinalClass{ //errorpublic static void main(String[] args){FinalClass f=new FinalClass();f.show();}}
Output: The above program will result an error in compilation like \'can\'t subclassed a final class\'.
package p1; public final class FinalClass{ public void show(){ System.out.println(\"This is a final class.\"); } } class FinalSub extends FinalClass{ //error public static void main(String[] args){ FinalClass f=new FinalClass(); f.show(); } }
JavaBeans is an API reusable, platform indepent component writtenin java programming language.A JavaBean is a simple class havingthe setter and getter methods for each property.
It is good convension to implement the Serializable interface.
Example:
import java.io.*;
public class MyBean implements Serializable {
// Properties private String name = null; private int age = 0; // Getter and Setter Methods
public String getName() { return name; } public void setName(String s) { name = s; } public int getAge() { return age; }
public void setAge(int i) { age = i; } }
One of the most powerful feature of Java is its multithreading mechanism.The synchronization is used to coordinate the activities between the multiple threads.
Java uses the monitor to synchronize the methods or the block of code. A \'synchronized\' keyword is used with the method signature or before a block of code.
If all the thread of the class want to access the same method concurrently, monitor helps them to synchronize the accessone thread at a time by locking the resource being accessed on the accessing object.
The java.lang.reflect package provides the information about the code, i.e. objects and classes.Reflection provides the programmatic access to variables, methods, constructors to operate on objects.
It is used to retrieve the member information for any loaded class.
Example:Class a=Class.forName(\"java.lang.String\");Method m[]=a.getDeclaredMethods();java.lang.reflect package provides classes such as Method,Modifier,Field,Constructor,Proxy etc. Using these classes we can retrieve the needed information of the loaded class.
Serialization can be obtained in a class by implementing the java.io.Serializable interface.All the subclasses of a serializedclass are also themseleves serialize.
This interface contains no methods and used simply to identify being serialized.
Its main purpose is to save the object state into a device or filefor the future use.
This process is calles serialization. When we want to access the state of the object we make it deserialized.The classes that require serialization must implement the following methods for the serialization and deserialization process.
private void writeObject(java.io.ObjectOutputStream out) throws IOException{//write the object state} private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{//read the object state} The writeObject() method is responsible for saving the state of the object into a resource, i.e. device or a file. The readObject()method is responsible for the accessing the object state.
No! Methods can\'t be overloaded based on the return type.For methods overloading you must change the argument list.
You can change the number of parameter passed or their data types.The return type may be the same, doesn\'t matter.
Before performing the garbage collection the JVM called the finalize() method to cleanup the resources such as closing the file or socket connection etc.
The finalize() method is declared in the java.lang.Object class.
When you implement the finalize method, you are actually overriding it from the Object class.Your finalize() method must be declared as follows:
protected void finalize () throws throwable{//some cleanup code here}
AWT(Abstract Window Toolkit} and Swing are the components of the JFC(Java Foundation Classes), and used for creating the GUI(Graphical User Interface).AWT is a portable GUI library for stand-alone applications and/or applets.
Swing implements a set of GUI components that build on AWT technology and provide a pluggable look and feel. Swing is implemented entirely in the Java programming language.AWT over Swing:*Speed*Applet Portability*Look and FeelSwing over AWT:*Portability*Behavior*Features
A heavyweight component is one that is associated with its own native screen resource.Using the JMF with the JFC/Swing is a heavy weight component.
All AWT components are heavyweight and all Swing components are lightweight. Mixing the AWT components with Swing is painful task.
An applet life cycle contains the following methods:*init()*start()*stop()*destroy()Besides these your applet can implement the paint() method.Example:
import java.applet.Applet;import java.awt.Graphics;
import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString(\"Hello world!\", 50, 100); } }
The browser starts execution of an applet with the init() method. This method is used for initialization of the component.The start() method is called applet is ready to display the content and called after the init() completed and before the paint() called.
An Exception is an abnormal condition that may occur during the program execution.Exception is a class drived from the Throwable class.
Two types of exception are there:Checked exception and Unchecked exception. If a checked exception is thrown by a method it must declare it or handle it by providing a try/catch block.
Java provides the five keywords for handling the exception: try,catch,throw,throws and finally.When an exception is thrown,the class Exception or its subclassmust be instantiated and passed to the catch block as a parameter.
When an exception is thrown by a method, it must declare or handle it.A method can declare the exception using the keyword throws with the method signature and a list of exceptions type so that the calling methods can guard themselves.
For example:
public void myMethod() throws IOException, ArithemeticException{//some code here that might cause the exception}If a method does not declare the exception then it must handle the exception by providing the try/catch block.For example:public void myMethod(){try{//some code here that might cause the arithematic exception}catch(ArithematicException e){}}
You never know that the exception will be thrown or not.That means you are not sure that the catch will be executed or not.
So it is better not to put the code inside the catch block which must be executed such as closing a file or a socket connection. Java provide another keyword \'finally\' for this purpose.
The finally block must come immediately after the all catch blocks or after the try block if there is no catch associated with the try block. The finallyblock must be executed, doesn\'t matter the exception is thrown or not.
In java, there are three types of access modifiers: *public *protected *privateBut, there are four access control levels, burn itinto your mind. The fourth access control level isdefault.We get default access control if we don\'t use any of the access modifiers.
Besides access modifiers, the other modifiers in java are: *abstract, *static, *final, *strictfp, *transient, *volatile, *native, *synchronized, etc.
Yes! synchronized is a modifier in java. It is used for synchronized a resource if multiple threads want to access the resource.
Polymorphism is a useful mechanism in java. Polymorphism means \'one name with multiple implementaions.\'Java supports two types of polymorphism: static and dynamic polymorphism.
Polymorphism can be achieved in java by method overloading (static polymorphism) and method overriding (dyanmic polymorphism).
Overloading: Using the same method name with multiple implementation in such a way that the argument list must be changed and return type may change. For overloading, change in the argument list is a must. Overloading resolve at the time of compilation.
Overriding: Using the same method name with thesame argument list and return type called method overriding. However in Java 5, the ruturn type ofthe overrriding method may be changed with the subtype of the overridden method.
Inheritance is the mechanism of using the features of one class into another class.The class which acquire the properties of another class (super class)is called subclass or drived class.
Java provides the keyword \'extends\' to support the Inheritance.
Example:
package p1; public class SuperClass{ void show(){ System.out.println(\"Super class\"); } } class SubClass extends SuperClass{ public static void main(String[] args){ SubClass s=new SubClass(); s.show(); } }
Using the same method name with different arguments list is called method overloading.To overload amethod, you must change the arguments list. Thereturn type may or may not be change.
Using the same method name with the same argument list and return type called method overriding. However in Java 5, the ruturn type of the overrriding method may be changed with the subtype of the overridden method.
No! Java does support array within array.We can achieve multidimensional arrays using it.Example:int[][][] m=new int[3][3][2];
Java does not support multiple inheritance. But we can achievethis using interface.A class can\'t extends more than one classbut an interface can extends more than oneinterface.Example:interface I1{//some abstract methods here}interface I2{//some abstract methods here}interface I3 extends I1,I2{//some abstract methods here}
Yes! There are many reporting tools in java: * JFreeChart * Prefuse * JasperReports * jCharts * JFreeReport
Java is a pure Object oriented programming language originally developed by Sun Microsystems, released in 1995 and has the capability in its platform independency.It support multithreading, exception handling and automatic garbage collection facilities.Java supports various applications like:Web applications and web services.
A Class is a just like a container which containsvariables and methods. The variables make up thestate and the methods describe the behavior of theclass.
A method is a group of instructions enclosed by the curly braces{}.A method has a specific signature having the method name along with the parameter list and a return type. Methods describe the behaviour of the class. Methods are where the real work gets done,date get manipulated and algorithms implemented.
Java is a pure Object oriented programming language and supports: * Class * Object * Abstraction * Encapsulation * Polymorphism * Inheritance, etc.
Binding up the data and methods into a singleunit, i.e. class is called encapsulation.Example:
class Area{ //data variable double dim1;
double dim2;
//methods public double calculateArea(double d1,double d2){ //some calculation code here}}
Inheritance is the mechanism of using the features of one class into another class.The class which acquire the properties of another class (super class)is called subclass or drived class.
Java provides the keyword \'extends\' to support the Inheritance.
Example:
package p1; public class SuperClass{ void show(){ System.out.println(\"Super class\"); } } class SubClass extends SuperClass{ public static void main(String[] args){ SubClass s=new SubClass(); s.show(); } }
A Java source code is compiled by java compiler(javac) and converted into the bytecode.This bytecode is then executed by the JVM. A Java Virtual Machine (JVM) is a software program and data structures which use a virtual machine model to execute the instructions.
JVM accepts accepts the byte code and provides output of that bytecode.
A bytecode is highly optimized set of instructions.The JVM is combines a set of standard class libraries which implement the Java API (Application Programming Interface).
Identifiers are just the name of the variables, methods, classes, interfaces etc.Each of the above things is identified by their names in the program.
They are not the thing themselves, they justpoint to the values in the memory. Identifiers follows some rules to be declared: * Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $. * Identifiers may only begin with a letter, the underscore or a dollar sign.
There are two types of modifiers in Java: * Access Modifiers, * Non-access modifiers.Acess modifiers are public, protected and private.Non-access modifiers are abstract, final, static, transient, volatile, strictfp, and synchronized.
Primitives data types in java are: * boolean * char * byte * short * int * long * float * double
The wrapper classes serve the two purpose: * It wraps the primitive to an object so that primitives can be used in the activities which are reserved only for the objects. * Converting primitives to and from String objects. Java provides the Wrapper class for each of the primitives in java. Some of these are: * Boolean * Character * Byte * Short * Integer * Long * Float * Double
Java provides the automatic garbage collection facility.JVM performs the garbage collection to free up the unnecessary memory which can\'t be reached through the object reference. We can\'t force the JVM to perform the garbage collection, but we can request the JVM by our program to to call the method System.gc(), but it is upto JVM to perform garbage collection or not.
A final keyword is used to prevent the inheritance if it is used with the methods and classes.If we modify a class with the final modifier, it means, that class can\'t be subclassed, i.e. we can not make a subclass of final class.If we declare a method to final, it means, that method will not be inheritin the subclass of that class in which the final method is declared.If we declared a final variable, it means, that the value of the variable can not be modified once it is initialized.
You can think of interface as a fully abstract class.An abstract class can have abstract and non-abstract methods, but an interface can have only abstract methods ends with the semicolon.
An interface may also contain constant.Example:public interface MyInterface{int i1;static int i2;static final int i3;void showi1();public void showi2();public abstract showi3();}
An array is simply a data structure that stores the similar types of elements with sequence of consecutively numbered. int a[]=new int[3];This will create an array of int of size 3. The size of the can\'t be increase once it is created.Vector is just like an array, but it is rescalable. That means we can increase or decrease the size of the vector. One most important thing about vector is that unlike array, vector can hold multiple types of element. Vector can be declared as:Vector v=new Vector();Vector provides the methods to manipulate the elements:v.add(\"Hello\");v.add(3);v.add(1,\"world!\");v.set(2,\"How are you!\");v.get(0);Use the vector if you want to store the multiple data types and don\'t know about the size.
The Singleton is a Design Pattern for allowing onlyone instance of your class.
The Singleton's mainpurpose is to control object creation upto one.
It is good for threading problems, because we are surethat there is only one instance of the class.
Constructors are the special member functions which have the same name as the class name. The most important thing is that they don\'t hava return type. Constructors may be overloaded. If you don\'t provide a constructor for the class, the compiler will supply the defualt one. Constructors can have any of the access modifiers. Example: public class MyClass{ int i; int j; public MyClass(){} protected MyClass(int i){} private MyClass(int i,int j){} }
Casting is the process of assigning the value of one type of variable to another type of variable.Two types of casting are there in java:
Implicit casting
Explicit castingWe can directly assign the value of a variable to other variable if that variable can be easily fit by memory size into the other variable, this is called implicit casting.
Example:
int a=5; //a having 4 byte of memorybyte b=6; //b having 1 byte of memorya=b;
//OK! byte b can be easily fit into an int a.b=a; //NO! int a can't be fit into the byte b.b=(byte)a;
//OK! Explicit casting.The above statement telling the compiler that, I know there may be some loss of bits.
final is a keyword used for the following things:-
final variable use to prevent the value modification.final methods can't be inherited.
final class can't be sub-classed.
finally is the block of code used with the try/catch block or the try block if there is no catch associated with the try block.
finalize It is useful where you want some code must be executed whether the exception is thrown or not.finalize is a method that is called by JVM just before the performing the garbage collection.
But is not sure that this method will be called ore not, it depends upon the JVM.It is declared in the Object class. You can override the finalize() method.
Packages are the container for the classes.A single package may contain several classes and sub packages.
Java provides the keyword \'package\' to declare the package. Each package has an identifier and can be import in the other package.
Packages are introduced to resolve the class naming confliction that can arise when two programmers have the same name for their classes.Declaring a package:package p1;class abc{}Importing a package:package p2;import p1.abc;class xyz{}
* String * Thread * ArrayList * Vector * HashMap
* ArrayList * Vector
When you import java.applet.*, it means you are importing all the classes available in the java.applet package. When you import java.applet.Applet, it means you are importing the single class. It is better to import the classes that you need instead of importing all the classes in the package.
The java.lang is the default package which is automatically imported in each of the java source file.
Anonymous class is one that has no name. Java provides the anonymous inner classes with different flavours. An anonymous inner class can also be declared even in the argument list of the method.
An interface tells that what a class can do. It is a good object oriented design to use interfaces in your program. When a class implements the interface, it is actually contracting to implement all the functionality of the interface. Interfaces also support multiple inheritance.
If a class implements the serializable interface, it means that state of objects of that class can be serialized and deserialized. This interface has no methods.
If you want prevent serialization of the fields(variables), mark them transient. The transient variable can\'t be serialized.
The throw keyword is used to throwing the exceptionmanually in the program.For Example:
try{throw new NullPointerException();}catch(NullPointerException e){}
The throws keyword is used with the method signature with the list of Exceptions type. This process is called exception declaration. It tells the calling method to guard themselves to declare the exception or handle it.
For example:void calculate(int a,int b) throws ArithematicException{//some calculation code here}
Yes! Multiple catch statement can be used in exceptions, but with some general rules.A single try block can have multiple catch associated with it but the each catch has an arguments according to the inheritance heirarchy of Exception.
That means a subtype of Exception heirarchy must not be come in the catch block before the supertype of the Exception heirarchy.
Example:
try{int i=3/0; //divide by zero exception}catch(Exception e){}catch(ArithematicException e){}
The above code will result a compilation error \'unreachable code\' at the second catch statement because ArithematicException is a subtype of the Exception class.
The above code should be like this:try{int i=3/0; //divide by zero exception}catch(ArithematicException e){}catch(Exception e){}
Yes! The try statement can be nested within another try block.
Thread is a light weight process.The Java Virtual Machine allows an application to have multiple threads of execution running concurrently
Every thread has a priority from one to ten.
Threads with higher priority are executed in preference to threads with lower priority. Java provides two ways to create the Thread: * Extending the Thread class * Implementing the Runnable interface.
Multithreading allows two or more parts of the same program to run concurrently.A single program or block of code can be executed by any number of treads.
Some problems may arises with multi-threading if two or more threads manipulates the shared or global variable.
Two way of creating the thread in java are: * Extending the Thread class * Implementing the Runnable Interface.Both ways provides the same functionality.But itis better to implement the Runnable interface, because if you extends the Thread class you willnot be able to extend any other class. One classcan extends only a single class but can implements many interfaces.
The method to find if a thread is active: boolean isAlive()
The sleep() method moves the thread to waitingstate for particular time.for exampleThread.sleep(7000);butthe suspend() method moves to waiting state untilthe resume() method gets called.
No! In multi-threading environment a thread can start the another thread but it can not be a member of another thread.
MIN_PRIORITY MAX_PRIORITY NORM_PRIORITY
Garbage collector thread belongs to low priority.
this keyword is used to point to the currently executing object.The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
Example:public class PointExample { public int x = 0; public int y = 0; //constructor public Point(int x, int y) {this.x = x;this.y = y; }}
The StringBuffer is a class that has a mutable sequence of characters.Length and capacity of the StringBuffer object can be find out by the following two methods: * length() * capacity()Capacity of the StringBuffer is always plus 16 to the length. Example:class StringBufferExample { public static void main(String args[]) { StringBuffer sb = new StringBuffer(\"Hello World!\");
System.out.println(\"Buffer value= \"+sb); System.out.println(\"Length = \" +sb.length()); System.out.println(\"Capacity = \" +sb.capacity()); }}
There are two ways to compare the two strings in java:* using the == operator, * using the equals() method.
For Example:String s1=new String(\"Hello!\");String s2=new String(\"Hello!\");if(s1==s2) System.out.println(\"Equal using == operator.\");elseif (s1.equals(s2))System.out.println(\"Equal using equals method.\");elseSystem.out.println(\"Not Equal.\");
The System class provide systemlevel functionality to Java applications.Some of the facilities provided by System class: * Reading input from the keyboard.
* Writing output to console. * Reading and writing system properties and environment variables Runtime class provides support for runtime environment.
flush()
The StreamTokenizer is class in Java that takesan input stream and parses it into \"tokens\",allowing the tokens to be read one at a time. Each byte read from the input stream is acharacter in the range from \'u0000\' to \'u00FF\'.The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Some Methods defined by StreamTokenizer class: * void whitespaceChars(int low, int hi) * void wordChars(int low, int hi) * String toString() * void slashStarComments(boolean flag) * void parseNumbers() * void ordinaryChars(int low, int hi) * int lineno() ,etc.
The values assigned to the variables of an objectmake up the state of the object.Saving the stateof the object for the future use into some file or the device is called the Serialization.
When we want to use that object, we read the values of the variables from the file or device.
This process is called De-serialization.
An applet is a tiny Java program that can run on browser and can be included in an HTML page, much in the same way an image is included in a page.When you use a Java technology-enabled browser to view a page that contains an applet, the applet\'s code is transferred to your system and executed by the browser\'s Java Virtual Machine (JVM).
Two methods help here:public java.net.URL getDocumentBase();public java.net.URL getCodeBase();The getDocumentBase() returns the URL to the host that server the HTML document.The getCodeBase() returns the URL to where the original applet class was loaded from.
The life cycle of an Applet: * init() * start() * stop() * destroy()
Applets are loaded and executed within a web browser, and hence you can load specific URL.* Get a reference to the applet context * Call the showDocument method with a URL object as parameter.
The following code can help here: import java.applet.*;
public class MyApplet extends Applet { // Applet code here // load an html page public void showPage (String aPage) //aPage should contained address of the HTML page to be shown { URL url = null; try { url = new URL (aPage); } catch (MalformedURLException e) { //handle exception } if (url != null) { getAppletContext().showDocument (url); } } }
The getDocumentBase() method returns \"the URL of the document in which the Applet is embedded.\"It actually return the URL of the directory in which the document resides.
The getCodeBase() method gets the base URL.
This is the URL of the directory which contains this applet.It Returns:the base URL of the directory which contains this applet.
In java applets, the parameter tag is used in the html used to send parameter to applet. In applet you can read the parameters passed by html code.
The getAppletInfo() method returns the string that describes the applet. The getParameterInfo() method returns an array of string arrays that specify the name,type, and description of each of the parameter.
Sometimes you need to allow two or more applets to communicate on the Web page.Because the applets all run within the same Java context-that is, they are all in the same virtual machine together-appletscan invoke each other\'s methods.
The AppletContext class has some methods for locating another applet by name, or retrieving all the applets in the currentruntime environment. The AppletContext class in the java.applet package contains the two member functions getApplet and getApplets.
By using these functions, an applet can find other applets and invoke methods on them.
Example:Html file: Using the name attribute, you can refer to a applet: Applet anotherApplet = getApplet(\"applet1\"); anotherApplet.someMethod(); //calling any public method
Events represent the activity that occurs between the user and the application.Java�s Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.
When the user interacts with a program, by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program.
This code determines how to handle the event so the user gets the appropriate response.
Java provides the Event class and each event is represented by an object that gives information about the event and identifies the event source. Whenever an event occured by an event sourse,
An appropriate evetnt handler(EventListener) is called. The Event Listener knows that how to handle the handle.
An event listener is an object used to handling a particular kind of event.Event Handling Interfaces * ActionListener * AdjustmentListener * ComponentListener * ContainerListener * FocusListener * ItemListener * KeyListener * MouseListener * MouseMotionListener * WindowListener
The adapter classes allow you to use the Listener Interfaces without having to create a body for every method. Adapter class provides the empty implementation for Listener interface\'s method.You don\'t have to override all the listener\'s method.
* MouserListener * MouseMotionListener
* public void mouseClicked(MouseEvent e) * public void mouseReleased(MouseEvent e)) * public void mouseOver(MouseEvent e) * public void mouseDoubleClicked(MouseEvent e) * public void mousepressed(MouseEvent e)
A Panal and the Frame, both are the component of the Abstract Window Toolkit(AWT). A panel is a component which can be embedded in a frame, and a frame is nothing but a window application an can embed all the components. Frame-is a top level container. while the panel is sub-level container..not the top level container..
The default layout of panel is flowlayout. The default layout of frame is border layout.
A Choice is a compact form that requires you to pull it down to see the list of available choices.Only one item may be selected from a Choice.
A List may be displayed in such away that several List items are visible. A List supports the selection of one or more List items.
The different types of Layouts are : * FlowLayout, * BorderLayOut, * GridBagLayout, * GridLayout, * CardLayout.
A CardLayout object is a layout manager for a container.It treats each component in the container as a card.Only one card is visible at a time, and the container acts as a stack ofcards.
The ordering of cards is determined by thecontainer\'s own internal ordering of its component objects. The CardLayout class manages two or more components (usually JPanel instances) that share the same display space. CardLayout defines a set of methods that allow an application to flip through these cards sequentially, or to show a specified card.
The addLayoutComponent(java.awt.Component, java.lang.Object) method can be used to associate a string identifier with a given card for fast random access.
GridLayout class puts all the components in a rectangular grid and is divided into an equal sized rectangles and each component is placed inside a rectangle.The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size.
Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component occupying one or more cells, called its display area.GridLayout has the constructors :GridLayout(int rows, int cols) and GridLayout(int rows, int cols, int hgap, int vgap)The major difference between GridLayout and GridBagLayout is that GrigBagLayout supports components of different sizes, and you can specify layout options for each component.
Use the GridBagLayout when you need tabular layouts (or layouts that can be thought of as matrices) and when it is important to specify the resizing behavior of each component.
The classes that implements java.util.Set interface (such as, HashSet,TreeSet) do not support duplicate elements.
Swing is a library of GUI controls which improves upon the Abstract Window Toolkit.The Swing toolkit includes a rich set of components for building GUIs and adding interactivity to Java applications. It includes rich undo support, a highly customizable text package, integrated internationalization and accessibility support. Swing is completely written in Java to truly leverage the cross-platform capabilities of the Java platform. Swing is part of the Java Foundation Classes (JFC).
The JFC also include other features important to a GUI program.Swing provides significantly enhanced functionality, such as actions, tables, trees, images buttons, tabs, toolbars, and sliders.
Applet is component of AWT whereas JApplet is a component of Swing. JApplet is a Swing version of Applet.An applet is a heavy-weight component, and JApplet is a light-weight component.
The swing components provide better look and feel than awt.
Swing components are derived from the javax.swing.* package and they are prefixed with a latter \'J\'(like JFrame, JButton, JApplet) Whereas applet is derived from the package java.applet.*
The javax.swing package has the following classes to create the swing the component: * Buttons and Labels * Checkboxes and Radio Buttons * Lists and Combo Boxes * Borders * Menus * The PopupMenu Class * The JScrollPane Class * The JSplitPane Class * The JTabbedPane Class * Scrollbars and Sliders * Dialogs
In javax.swing package, Using the JTabbedPane class, you can have several components, such as panels, share the same space.The user chooses which component to view by selecting the tab corresponding to the desired component. The add() method of JTabbedPane class is used to add container component to the JTabbedPane component of Java Swing.
Example:import javax.swing.*;import java.awt.*;public class MyTabbedPane{ public static void main(String[] args){ JFrame f = new JFrame(\"My Tabbed Pane Frame\");f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTabbedPane t = new JTabbedPane(); frame.add(t, BorderLayout.CENTER); JButton b = new JButton(\"1\"); t.add(\"Tab 1\", button); b = new JButton(\"2\"); t.add(\"Tab 2\", button); frame.setSize(300,300); frame.setVisible(true); }}
Jtree is a just like a tree which is used to disply the items in the form of the tree.A JTree object does not actually contain your data; it simply provides a view of the data.
Each row displayed by the tree contains exactly one itemof data, which is called a node.
Every tree has a root node from which all nodes descend.
Using the JTable class you can display tables ofdata, optionally allowing the user to edit the data.JTable does not contain data; it is simply a view of your data.
The JTable class is an implementation of the Active Record design pattern.
It is used for creating, reading, updating, and deleting records in the database table.
The JFC(Java Foundation classes) tells you how to create graphical user interfaces (GUIs) for applications and applets, using the Swing components.The Java Foundation Classes (JFC) are a graphical framework for building portable Java-based graphical user interfaces (GUIs).
JFC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D.
JAR file is a file format based on the popular ZIP file format and is used for aggregating many files into one. A JAR file is essentially a zip file that contains an optional META-INF directory.A JAR file can be created by the command-line jar tool, or by using the java.util.jar API in the Java platform. JAR file format enables you to bundle multiple files into a single archive file.
The manifest file is named MANIFEST.MF. In Java ,a manifest file is a specific file contained within a JAR file.It is a meta data file that contains name-value pairs organized in different sections.
If a JAR file is intended to be used as an executable file, the manifest file specifies the main class of the application.
A javaBean property has the two methods: * setProperty() * getProperty()
BeanInfo classes provides a high degree of control over how a bean appears and behaves at design time.BeanInfo classes are design-time-only classes.If a bean implementor wants to provide information regarding methods, properties when they can provide a bean info class by implementing BeanInfo interface and provide information regarding the bean properties,methods etc.
The Serializable interace is used in Beans.
Classes that are available in java.beans package :* BeanDescriptor * Beans * DefaultPersistenceDelegate * Encoder * EventHandler * EventSetDescriptor * Expression * FeatureDescriptor * IndexedPropertyDescriptor * Introspector * MethodDescriptor * ParameterDescriptor * PersistenceDelegate * PropertyChangeEvent * PropertyChangeListenerProxy * PropertyChangeSupport * PropertyDescriptor * PropertyEditorManager * PropertyEditorSupport * XMLDecoder * XMLEncoder
Difference between java and C++ : * C evolved into C++, and C++ transmuted into Java.* Java is the language of the Internet whereas C++ was designed mainly for systems programming, * Java supports object-oriented programming, same way as C++. * Java does not support operator overloading.
* Java does not include a preprocessor or support the preprocessor directives.
* Java does not support multiple inheritance. * Java does not support destructors, but rather, add the finalize() function. * Java does not support templates. * Java does not support pointers.
A process is a program in execution, whereas a single process can contains multiple threads.The key difference is that processes are fully isolated from each other whereas threads share (heap) memory with other threads running in the same application.
Threads share the address space of the process that created it; processes have their own address.
You can initialize your applet using the init() method.
The order of invocation in Applet is : * init() * start() * paint() * stop() * destroy()
The update() method is defined by the AWT and is called when your applet has requested that a portion of its window be redrawn. The problem is that the default version of update() first fills an applet with the default background colour and then calls paint().You can override the update() method. The paint() in this case will simply call update(). public void update(Graphic g) { //Redisplay your window here.}public void paint(Graphics g) { update(g); // call to the update()method.}
JNI stands for Java Native Interface. The Java Native Interface (JNI) enables the integration of code written in the Java programming language with code written in other languages such as C and C++.It allows programmers to take full advantage of the Java platform without having to abandon their investment in legacy code. JNI lets Java code use code and code libraries written in other languages, such as C and C++, and allows you to call Java code from within native code.
The JNI allows writing native methods to handle situations when an application cannot be written entirely in the Java programming language e.g. when the standard Java class library does not support the platform-specific features or program library.
The JNI framework lets a native method utilize Java objects in the same way that Java code uses these objects.
All the swing components are derived from abstract javax.swing.JComponent class.
The following tag is used for this purpose : tag upload file.
The layout for toolbar is Flow Layout. There is no Specific Layout for adding ToolBar.You can use null layout for use a toolbar at the position where you want.
You can also use DefaultToolBarLayout.
We can add panel to a Frame : Panel p = new Panel(); Frame f =new Frame(\"My frame\"); f.getContentpane().add(p);
The corresponding Layout for Card in Swing CardLayout.
AWT supports lightweight components. Light weight componenets can be created using Java without mixing any other language code.A light weight component is one that subclasses java.awt.Component (or java.awt.Container) directly - implementing the look-and-feel of the component in Java rather than delegating the look-and-feel to a native peer.
The Java Bean is simple java class which is contains Getters and Setters methods nothing else.These methods can only used to set or get the values of the variables.
They neither contain any business logic nor do they interact with the database.
Whereas a plain old java class contains the business logic, provides some data processing capabilities, database interaction, etc.
Applets are the tiny java program runs under the control of web browser and dynamically downloaded over the internet. Browser takes care of the life cycle of the Applet, i.e. calling the init(), start(), paint(), stop(), destroy(), etc methods.Applets are designed to run dynamically over the web.An application runs stand-alone, with the support of a virtual machine under the control of local user\' operating system.
An application starts execution with the main() method. The main method here is nothing but the system method used to invoke the application.
Java achieve inheritance using two notions : By extending the class and implementing the interface.When you \"implement\" an interface, you are stipulating that your class adheres to the \"contract\" of the interface that you specified. Use interfaces to say \"What objects can do\" or \"What can be done to an object.
\"Interfaces are intended to define the what without defining the how. Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation.
Java is not fully object oriented language, because not all values in Java are Objects.�The basic numeric types such as int, long, double, etc., are not objects and need to be \"boxed\" into objects in order to pass them as Object parameters or call methods on them. Java does not support Multiple inheritance and operator overloading. Java uses static keyword.
We can perform a function declared as static without an object this violates real world reflection and object orientation.
The Object class is the root class of all the Java classes.
Unicast object means there is one receiver. Use multicast to allow one-to-many connections.The example for multicast is the java eventhandling model.
Interface which does not contain any variables and methods.Examples: * java.io.Serializable, * java.lang.Cloneable, etcBoth of these interfaces declare no methods, by implementing them, a class signals some fact to the JVM (either it\'s OK to serialize it, or it\'s ok to clone it.)
The null interface is also called as Marker Interface or tagged interface.
As of December 2008, the latest version of Java is 1.6.0_11
Class loaders determine when and how classes can be added to a running Java environment.In Java, code is loaded (either from the disk or over the network) by a Class Loader.
Class loaders perform two functions : First, the JVM needs to load the byte code for a particular class, it asks a class loader to find the byte code.
Each class loader can use its own method for finding requested byte code files. Second, class loaders define the namespaces seen by different classes and how those namespaces relate to each other.
Class Loaders provide Java\'s dynamic loading capability, which allows classes to arrive and depart from the runtime environment.In a JVM, each and every class is loaded by some instance of a java.lang.
ClassLoader. The ClassLoader class is located in the java.lang package and developers are free to subclass it to add their own functionality to class loading.Some of the class loaders in the JDK: * java.net.URLClassLoader * java.security.SecureClassLoader * java.rmi.server.RMIClassLoader * sun.applet.AppletClassLoader
Public is an access modifiers tells that this method can be accessed anywhere inside or outside the package by any class\' object reference.Static means there is only one copy of that method is available to all the instances of the class. void is simply a return type of the method telling that this method will return nothing.main is an identifier to identify the method. The main() method is the entry point to the program.
String class provides the immutable character sequence whereas StringBuffer class objects are mutable characters sequence.The StringBuffer is faster than String when performing simple concatenations.
Example:String s=new String(\"Hello\");s.toUpperCase();The String object s is still pointing to \"Hello\" instead of \"HELLO\". Here a new string \"HELLO\" is created but did not assigned to any reference variable.But:StringBuffer sb=new StringBuffer(\"Hello\");sb.toUpperCase();The StringBuffer object sb is now pointing to the \"HELLO\".This is the main difference that string object are immutable and string buffer objects are mutable.
Wrapper classes are used to \"wrap\" the primitives data types into objects so that they can be included in the activities which are reseved for the objects.Yes! String class is a wrapper class, it wraps the string literals to an object.
Default modifier in Interface is public access modifier.
No! An abstract method or abstract class can\'t be marked as a final.They both have the opposite meaning. An abstract class must be subclassed, whereas a final class must not be. An abstract method must be overridden whereas a final method can\'t be inherited, hence can\'t be overridden.
Yes! we can declare variables inside a method as final variables.
A Thread is considered to be dead when it completes its run() method.We can\'t call a start() method on a given Thread object for the second time. Hence a dead thread can\'t be restarted.
Yes we can have constructors in an applet. But applets don\'t usually have constructors because an applet isn\'t guaranteed to have a full environment until its init() method is called.Applet constructor is just like any other constructor, they cannot be overridden.
Both types of exceptions are drived from the class Exception.But Unchecked exception are RunTimeException, which do not to be handled or declared. Whereas Checked Exceptions must be handled by try/catch block or must be declared in the method signature.
Two types of multi-tasking : * Process based multi-tasking. * Thread based multi-tasking. In Process based multitaskin, more than one processes run concurrently. Whereas In Thread based multitasking multiple threads executes concurrently. A single process may contain several executing threads sharing the same address space.
The filter driver determines the total bandwidth of the disk. I/O filters generally used for reading from one stream and writing another stream.
Yes, An applet can communicate with another applet on different. Since an AppletContext will be created for a single page. If it is in multiple pages, different applet context will be there for different applets. But even if the applets are on different pages, they run under the same JVM, so we can create an class similar to AppletContext say this class AppletRegistry, which holds references to all the applets running in the JVM, and this class can be use to hand over the reference to whoever needs it for communication. This registry should maintain a static hashtable that should keep the map of all the applet objects.
== compare reference objects .
equals() compare values .
Both Abstract class and interface can\'t be instantiated.Abstract class may have abstract and non-abstract methods.
Interface may contain only abstract methods.
Abstract class doesn\'t support multiple inheritance.Interface supports multiple inheritance.
Abstract class can have final, non-final, static and non-static variables.Interface has only static and final variables.Interface can\'t have static methods, main method or constructor.
Abstract class can provide the implementation of interface.Interface can\'t provide the implementation of abstract class.The abstract keyword is used to declare abstract class.The interface keyword is used to declare interface.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
singleton :-
static variable:- also called class level variable .
Static variables are initialized when class is loaded.
Static variables are initialized before any object of that class is created.
Static variables are initialized before any static method of the class executes
final variable:- final variable needs initialization always, if you don’t initialize it would throw a compilation error.
The static final variables are constants
final class :- A final class is a class that can't be extended.A final class is a class that can't be extended.
public final class ClasaName{
// . . . Class contents
}
Serialization is the process of producing Stream of bytes from the object and writing it into the output source such as file.The serialization also keeps information to restore the fields during deserialization.To produce stream of bytes, the class should be inherited either from java.io.Serializable interface.which is marker interface.
A method cannot be overloaded on the bases of return types because the compiler will check only the method signature( name of the method and the arguments).So a method cannot be overloaded on the bases of return types.
Exception handling using try-catch-finally for normal termination.Try block : It contains the statements which likely to throw an exception.
If an exception raised, the remaining statements in the try block are skipped.Catch Block : Executed only if try block throws an exception.Finally Block : To maintain cleanup code
To maintain cleanup code while exception handling in try catch block.
Yes, Synchronized means thread safe i.e. only one thread will be executed at a time.
No, Java doesn\'t support multiple inheritance with class, but it supports with iterface.
Yes! Multi-dimensional arrays can be represented by arrays of arrays. var v = new array(3,4,5);
Methods are similar to functions or procedures that are available in other programming languages.Method signature contains method name and parameter list.
A method contains a set of statements that are combined to do a particular task. And, methods are of two types like predefined library methods and user defined methods.method declared inside class.
Interpretation happens at runtime(which means while running the Java program) ,turns it into native code.Compilation of java file will generate class file by calling javac.
Java interpreter is a program which implements the JVM specification and actually executes the bytecodes by running the program.
JVM is a Java virtual machine, JVM is a process that executes a computer program compiled into Java bytecode. Through bytecode java achieves interoperability (platform independent).
Source code for a Java class is called a compilation unit. Forms the input for the Java compiler (javac).
Static variable is also known as class variable, global variable.The static variable is used to refer the common property of all objects,variables that are common to all objects.Static is a modifier used with class, methods and blocks.
Static member never associated with object but with class.Static members are loaded when class is loaded into jvm, hence static members are accessed without()before) creating an object itself.
A static method cannot access instance variable, instance methods and cannot use this or super from static context.
GC is automatic memory management, which is a collector attempts to reclaim garbage or memory occupied by objects that are no longer in use by the program(unreferenced objects). Advantage of GC is memory efficient, automatically done.Can be done By nulling the reference, assigning a reference to another, annonymous object etc.
A resource leak is where memory is being steadily consumed by resources that are no longer being used. In java this situation arises when references to objects that are no longer required. To avoid this you should remember to set all variables to null as soon as you are finished with the reference. This will allow the gc to free up the memory that the objects were consuming.
1) The scope of the private members is anywhere within the class. 2) The scope of the protected members is anywhere with in the same package and only subclass of the different package. 3) The scope of the public members is anywhere!. static members are Common across all objects Also called class variable.A static variable cannot access instance method.
A subclass can re-implement superclass method to provide subclass specific implementation. Accesibility modifiers of superclass and subclass and return type, method signature must be same.
A class having only one instance.
Array have limitations: Size fixed, Homogeneous. While Vector is growable array, allows duplicate elements,ordered, not sorted, Accepts any number of null values. Synchronized,Heterogeneous. It is class of Collection interface.
Package is group classes interfaces. Two types built-in package and user defined package. The package statement should be the first line. Provides access protection. Removes naming collision.
java.lang package by default,imported implicitly.
Anonymous classes make our code compact. They can be declare and instantiate a class at a time. They do not have a name. They are local class only . This section covers the following topics:
Marker Interface
interface contains abstract class.
Converting the state of an object into a byte stream. Serializability of a class is enabled by the class implementing the java.io.Serializable interface.
Through transient keyword.
Runtime exceptions are unchecked exceptions, we can handle them through try catch block. try { ... do stuff ... } catch (SomeException e) { e.printStackTrace(); throw e; }
Throw is used to propagate an exception to its caller inorder to let the calling method to handle an exception rather than implementation method.Throw keyword is always used at block level but not at method signature level. All built-in exceptions are automatically thrown by the JVM. But, built-in exceptions can be programmatically thrown by the developer using throw keyword. All user defined exceptions must be programmatically thrown using �throw� keyword. Syntax: throw; Example: throw new ArithmeticException(�/ by zero�); Throws keyword is used at method signature level to specify the type of exception a method throws. Syntax: method_name( ) � <,ExceptionTypeⁿ>{ }
yes multiple catch statements can be used but it depends upon number of try block which throws an exception.
Yes, try { try { throw new Error(\"oops\"); } finally { console.log(\"finally\"); } } catch (ex) { console.error(\"outer\", ex.message); }
A thread is a smallest unit of dispatchable code. Defining, Instantiating, and Starting threads by Extending Thread class Implementing Runnable interface Methds to Prevent Thread execution Sleep() Join()
A large program is split into multiple tasks, assign a thread for each task and execute them concurrently is called as multithreading.
Defining, Instantiating, and Starting new Threads The code which we want to run as a thread of execution is written inside a run() method. We can define a thread either by: 1. Extending a java.lang.Thread class 2. Implementing a java.lang.Runnable Interface. Runable is better than extending Thread. it shares the same object to multiple threads. if you extends Thread, you can\'t extend another class
thread.isAlive() method.
Threads communication is possible in java. A first thread registers with a gateway for receiving communication. Registration includes identifying a location for receiving messages. The gateway maps message payloads received from second threads to the location of the first thread. The first thread detects a payload in the location and consumes it for processing.
If the thread is not allowed to perform any operations for a particular period of time, then use sleep() method. The sleep() method suspends currently executing thread for the specified time. Join() The currently running thread is suspended until the invoking thread completes its execution (and entered into dead state). The currently executing thread joins at the end of the invoking thread. This is used when the currently executing thread cannot continue until the invoking thread completes its execution.
There may be situations when two or more process are put into waiting state simultaneously to get the resources holding by each other.In this position each would be waiting for the other process to release the resource. So both processes gets locked, waits for the each other\'s resource to released. This situation is called deadlock.
Every thread in java has some priority. The valid priority range is 1 to 10, where 1 is the least and 10 is the max priority. The Thread class defines the following constants to set some standard priorities: 1) Public static final int MIN_PRIORITY (1) 2) Public static final int NORM_PRIORITY (5) 3) Public static final int MAX_PRIORITY (10) The thread with highest priority may get (cannot guarenteed) the chance of first execution. Two threads have the equal priority, we cannot determine which thread will be executed first. Thread class defines following methods to get and set the thread priorities: 1) Public final int getPriority() 2) Public final void setPriority(int priority) Default Priority By default, every thread is set with default priority which is 5. The default priority of the main thread is also 5.
low(MIN priority)
public int capacity() Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur. Returns: the current capacity. public int length() Returns the length (character count). Specified by: length in interface CharSequence Returns: the length of the sequence of characters currently represented by this object.
CompareTo(), Compare() method
The package java.lang contains classes and interfaces that are essential to the Java language. These are: Object, superclass of all classes in Java. Thread, the class that controls each thread in a multithreaded program. Throwable, the superclass of all error and exception classes in Java. Classes that encapsulate the primitive data types in Java. Classes for accessing system resources and other low-level entities. Math, a class that provides standard mathematical methods. String, the class that represents strings. Because the classes in the java.lang package are so essential, the java.lang package is implicitly imported by every Java source file. In other words, you can refer to all of the classes and interfaces in java.lang using their simple names.
java.lang.Object java.io.StreamTokenizer class takes an input stream and parses it into \"tokens\", allowing the tokens to be read one at a time. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.
Vector is a array whose size can be grown or shrink. Allows duplicate elements. It is an ordered collection based on index. Vector is a class of List Interface which is from collection framework. Allows any number of null values. By default, vector elements are not sorted. It is a synchronized collection (thread-safe), since it is a legacy class. Stack is sub class of Vector. Dictionary is an abstract class. Hash table and property are inherited from Map interface which is not derived from collection interface. Based on hashing mechanism. Keys cannot be duplicated but values can be duplicated. Both keys and values are unordered i.e., the entries in Hashtable are unordered. Neither key nor value is null. By default, hashtable entries are not sorted. By default, Hashtable is a synchronized Map. Properties are usually configured in property file with .properties extension. The entries in property file are key, values and separated with equal (=) symbol. Though the Properties class is inherited from Hashtable, but both keys and values must be string objects only. The advantages of using properties file is, the changes can be made in one place, which are reflected across all other placess in our code.
Set Interface has no duplicate elements. HashSet, Linked Hashset, TreeSet class not allows duplicate elements.
We can reuse the code by javabeans.Developers can use software components written by others without having to understand their inner workings.
JAR stands for Java ARchive. It\'s a file format based on the popular ZIP file format and is used for aggregating many files into one. The JAR format also supports compression, which reduces the size of the file and improves download time.
public class Introspector extends Object. he Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean. For each of those three kinds of information, the Introspector will separately analyze the bean\'s class and superclasses looking for either explicit or implicit information and use that information to build a BeanInfo object that comprehensively describes the target bean.
Yes! We can also defined our own exceptions according to our requirment. We can do this by extending the Exception class, in this class we override the toString() method.
Garbage collector removes the unreferenced objects from heap memory. By nulling the reference By assigning a reference to another By annonymous object etc. The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as: protected void finalize() The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes. public static void gc()
Two main drawbacks with C++ language are : Platform dependent and won�t support Internet and WWW. To solve these problems, James Gosling developed a new language called JAVA at sun Microsystems in 1991, which is platform independent and supports WWW & Internet. C++ supports operator overloading multiple inheritance but java does not. Everything (except fundamental types) is an object in Java (Single root hierarchy as everything gets derived from java.lang.Object). Java does not support pointers, templates, unions, operator overloading, structures etc. C++ supports structures, unions, templates, operator overloading, pointers and pointer arithmetic. Java support automatic garbage collection. Java, there is a Thread class that you inherit to create a new thread and override the run() method. C++ has no built in support for threads. Java doesn\'t provide multiple inheritance C++ does support multiple inheritance.
A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). Assignment expressions Any use of ++ or -- Method invocations Object creation expressions
Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call and be called by[1] native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.
The Java Foundation Classes (JFC) are a graphical framework for building portable Java-based graphical user interfaces (GUIs). JFC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D. Together, they provide a consistent user interface for Java programs. Encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications
A Bean is a Java class, but a Java class does not have to be a bean. Bean reusable software. A Java class is meant to carry out the different database operations like retrtieveing data, inserting data and updating data.
The idlj compiler uses the IDL-to-Java language mapping to convert IDL interface definitions to corresponding Java interfaces, classes, and methods, which can be use to implement client and server code.
CGI (Common Gateway Interface) is an attempt at providing users with dynamic content. It allows users to execute a program that resides in the server to process data and access database to produce the relevant data. They are written in the native operating system and then stored in a specific directory. A servlet is an implementation of Java that aims to provide the same service as CGI does, but instead of programs compiled in the native operating system, it compiles into the Java bytecode which is then run in the Java virtual machine. Though Java programs can be compiled into the native code, they still prefer to compile in the Java bytecode.
Interface provides service details not the implementation details to the user. �It is used to achieve full abstraction. �By interface, we can achieve multiple inheritance.
Because of primitive data types.Multiple Inheritance, Operator Overloading not possible in java.
java doesn\'t support multiple inheritance directly because it leads to overiding of methods when both extended class have a same method name. this will leads to ambiguity in executing.
Object is the root class for all java classes.
If we have a local variable declared in the run method then all the existing thread will hava a separate copy for that variable. If we are using the instance variable in the run method then this will be shared by all the existing variable.
The main function of constructor to do initialisation followed by instantiation. It is calle to create an object. A constructor resembles an instance method, but it differs from a method in that it has no explicit return type. Constructors often have the same name as the declaring class. Default constructor(no parameter). Parameterised Constructor (with parameter)
Java supports classes, but does not support structures or unions. Write once, run anywhere, Platform independent (Interoperability). Due to byte code and run by JVM. C++ supports multiple inheritance but java doesn\'t. Pointers are not in java, All classes in Java ultimately inherit from the Object class. Java does not support operator overloading.
Unicast is a one-to one connection between the client and the server. A multicast packet is from one machine to one or more. The difference between a multicast packet and a broadcast packet is that hosts receiving multicast packets can be on different lans
Null Interfaces know as Marker Interfaces having no method.There is a method clone() in Object class.Examples Serializable, Cloneable.
Serializable, Cloneable.
The Class.forName() loads the class into the JVM. It loads the class into the JVM for further use. We use this when we want to load JDBC-ODBC drivers. Class Loader is a part of JVM used to load the classes dynamically. It will load the classes based on demand. Diffrent types of class loaders are extension class loader, system class loader and bootstrap class loader. Bootstrap class loader loads the classes in rt.jar and i18n.jar, extension class loader loads the class in ext dir, system class loader loads all other classes in the class path. two type. 1) Static Loading. 2) Dynamic Loading. Dynamic way is done by the help of class.forName(); Extensions Class Loader,System Class Loader.
A message given to a Web browser by a Web server. The browser stores the message in a text file. The message is then sent back to the server each time the browser requests a page from the server. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user\'s previous activity. Each cookie is effectively a small lookup table containing pairs of (key, data) values session cookie and persistent cookie.
public is a access modifier, static means dosent belongs to an object, void means main does not return any value, main( ) is the method called when a Java application begins.
Passed at the time of running the java program. Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. Java application can accept any number of arguments from the command line. when you invoke an application, the runtime system passes the command line arguments to the application\'s main method via an array of Strings. Each String in the array contains one of the command line arguments
String is immutable and stringbufffer is mutable
A package is a namespace that organizes a set of related classes and interfaces. Java platform provides an enormous class library (a set of packages) suitable for use in your own applications.It is a group of classes, interfaces Advantage is reusability. Packages are of two types. User defined package, built in package.
A Canvas object provides access to a Graphics object via its paint() method.
inter thread communication can be done by 3 methods wait(), notify(),notifyall().
Both are type of polymorphism, method overloading having same method name but different parameter list (number, order, type), it is resolved at compile time so it is known as Early binding. Method overriding having same method name, parameter list and return type is also same.It is resolved at runtime therefore called Late binding.
If we are overriding the method in the same package\'s class then it must not be the private member. If we are overiding the method is the other package\'s class, then it must not be the private and default.
No! For method overloading, the parameter list must be changed. Method overloading does not depend the on return type.
Super class constructors are always executed before subclass constructors is called as constructor chaining. �this()� is used to call matching constructor from the same class. �super()� is used to call matching constructor from immediate superclass.
Contructor can be overloaded,i.e. a single class can hava more than one contructor. A construct may call to another constructor. The first statement in the constructor must be a call to either this() or super() but not both. The super() will call the matching superclass constructor according to the number of arguments passed in the super(). A this() will call the overloaded constuctor in the same class according to the parameter list. The called constructor may also make a call to the other constructor using this(). This type of contructor calling in the same class is called constructor chaining.
When we make a call to the method, we may pass some values in the parameter list. When we pass the actual value of the variable, it simply pass the copy of the variable not actual value. Hence change in the copy of that variable will not affect the actual value of that variable. When we passed the object reference into the parameter list in to a method call, we are actually passing the copy of bits that refer to the object somewhere into the memory not actual value of the object. If we modify the object using the reference of that object will also affect the actual value of that passed object.
Means that all variables must first be declared before they can be used.the operating system allocates memory and decides what can be stored in the reserved memory
We can write query in both JSP page and servlet. It depends upon you. But it is better to separate classes to make a database connection, pass the reference to the JSP page and write query using JSTL 2.0(Java Standard Tag Library).
Constructors are the special member, they do not have a return type. We can call the methods explicitly but constructors are called automatically when we create the object using the new operator. The purpose of constructor is to allocate the memory to the object and initialize the class\' variables. If you don\'t provide the constructor in your class, the compiler will insert the default constructor.
Object can be represented as a sequence of bytes that includes the object\'s data as well as information about the object\'s type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform. Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
Object Orientated Programming and Procedure Oriented Programming are basically two different paradigms for writing code. In procedural programming the main emphasis is on procedure while in object oriented the data is important part. on the same hand data is more secured in object oriented program. Procedural programming separates the data of the program from the operations that manipulate the data. The fundamental advantage of OO programming is that the data and the operations that manipulate the data (the code) are both encapsulated in the object. Object Oriented programming deals with the elemental basic parts or building blocks of the problem, whereas Procedural programming focuses on the steps required to produce the desired outcome. In OOP, decomposing the problem into smaller discrete pieces called \"Objects\".
A class is a construct that defines a collection of properties and methods. It can be viewed as a template. Object is an instance of a class.
Threads block or enters to waiting state on I/O, so that other threads may execute while the i/o Operation is performed.
A transient variable is a variable that may not be serialized. It is not stored as part of its objects persistent state. The value of the variable can\'t be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
The JDK provides a reusable embodiment of the pattern in the form of the java.util.Observer interface and the java.util.Observable class. Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. In Observer Pattern, object maintains a list of its dependents and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
List is an ordered collection of elements. The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index. Unlike sets, lists typically allow duplicate elements. The List interface includes operations for the following: * Positional access * Search * Iteration * Range-view Useful methods of the List Interface: * add() * clear() * contains() * get() * isEmpty() * listIterator() * remove() * size()
Thread.sleep(1000) method hands over the control to other thread for a particular time period. Whereas Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute according to the scheduling algorithm the CPU is running on.
No! The finalize method is invoked by the JVM/GarbageCollector on Objects which are no longer referenced.
The thread is in ready state.
No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both
When we use boolean & operator between the two operands then both the operands are evaluated. If we are using the && operator between the two operands then second operand is evaluated if the first operand is true.
An abstract method does not have a body. It contains only method signature terminated by a semicolon instead of curly braces. Abstract method can be declared only within the abstract class or within the interfaces. The definition to the abstract method will be provided by the class which extends the abstract class or implements the interface.
The System.out writes to the \"standard output\". The System.err writes to \"standard error\". These two streams are setup by the operating system when the Java program is executed, and can be redirected with the uses of \"|\", \">\", etc. on the command line. You can redirect the output of the System.out to any other file. The following example can help to understand the concept : public class Test{ public static void main(String args[]){ System.out.println(\"Output of System.out\"); System.err.println(\"Output of System.err\"); } } First Execution - C:>java Test Output of System.out Output of System.err Second Execution - C:>java Test > abc.txt Output of System.err In the second execution we diverted only the std output stream and std err stream remained unchanged. i.e., by this way, we can handle error stream separately.
Both the synchronized method and block are used to acquires the lock for an object. When you mark a method synchronized, then you are forcing every thread which calls that method to lock the monitor. If you expect a synchronized() {} block in the calling code, it is possible that some code which calls your method might neglect to use synchronized() and end up with a threading problem in your program. synchronized code always use objects as locks to prevent other threads from entering the synchronized block. For instance methods, they are synchronized on the \'this\' reference, and for static methods they are synchronized on the instance of the Class object method belongs to. Best practice is to minimize the code inside synchronized blocks because they prevent concurrent threads from executing - losing any advantage of multi-threaded applications. Synchronized blocks help let those portions of a method that do not access shared resources to be run simultaneously while still keeping those parts that need to be shared thread-safe.
You can not force the JVM for the garbage collection. However you can call the System.gc() method in your program to tell the JVM that it may the time to perform garbage collection. But it is upto the JVM that if will call the System.gc() method or not. There is no way to force the JVM, it works fine without programmer\'s intervention.
Yes, we can call the constructor but within the another constructor of the same class using the this().
We can call the superclass constructor by making a call to super() in the subclass constructor.
When you use multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus a subclass would never be reached if it came after its superclass. Further, in Java, unreachable code is an error.
We can use super.methodNme() or super.variableName.
If you are overriding equals() method of a class, then the other methods you might need to override is hashCode().
Externalizable is an Interface that extends Serializable Interface. Java provides Externalizable interface that gives you more control over what is being serialized. This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you\'ll have to write code that reads/writes only the values of the attributes you are interested in.
Garbage collection does not guarantee that a program will not run out of memory. It ispossible for programs to use up memory resources faster than they are garbage collected. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected.Moreover garbage collection cannot be enforced,it is just suggested.
A native method is the Java interface to non-Java code. It is Java\'s link to the \"outside world\". A native method is a Java method whose implementation is provided by non-java code. A native method is one for which the body of the method is defined elsewhere, entirely outside the Java Virtual Machine, in a library. Only methods can be declared as native. A native code is written in a non-Java language, typically C or C++, and compiled for a single target machine type. Syntax : native public void Native1( ) ;
break completely exits the loop. Continue skips the statements after the continue statement and keeps looping.
If a class implements the interface, it must provides the definition to all the methods declared in the interface or it must be the abstract class. If it is an abstract class then the first concrete subclass must provides the definition to the interface\'s mathods and abstract methods of the abstract class.
THe notify() method wakes up a single thread waiting on the object and passes the control of the monitor to it. The notifyAll() method will wake up all the threads waiting on the object and will select a thread to pass control to it. The unselected thread will again go back to sleep in the JVM scheduler list and they will need yet another call to notifty (or notifyAll) in order to wake them up. The notifyAll() method is the same as the notify() method. The only difference is that in this case all the threads from the non-empty wait set of the object are removed and are re-enabled for thread scheduling in stead of only one thread from the wait set being picked arbitrarily, removed, and re-enabled for thread scheduling as is the case in notify() method.
The wait() method is defined in the Object class. The method should only be called by a thread that has ownership of the object\'s monitor, which usually means it is in a synchronized method or statement block. Threads - wait() method do : * the wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run. * the wait() method is defined in the Object class. * wait() can only be invoked from within synchronized code. * it should always be wrapped in a try block as it throws IOExceptions. There are actually three wait() methods 1. wait() 2. wait(long timeout) 3. wait(long timeout, int nanos) The timeout is measured in milliseconds. when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur: 1. another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread 2. another thread invokes the notifyAll() method for this object 3. another thread interrupts this thread 4. the specified wait() time elapses
The different stated of a thread : * NEW : A Fresh thread that has not yet started to execute. * RUNNABLE : A thread that is executing in the Java virtual machine. * BLOCKED : A thread that is blocked waiting for a monitor lock. * WAITING : A thread that is wating to be notified by another thread. * TERMINATED : A thread whos run method has ended.
A non-static inner class may have object instances that are associated with instances of the class\'s outer class. A static inner class does not have any object instances.
The Reader/Writer classes is character-oriented and the InputStream/OutputStream classes is byte oriented.
Static methods are class bound rather than runtime object type bound. That means they cannot be overridden since polymorphism doesn\'t hold. We can\'t override the static methods. We know overriding depends upon the inheritance. Since the static methods are not inherited, hence we can not override static methods. If u try to that, you are actually redefining the superclass version of the static method, this is not an override.
If a class has no constructors, then the compiler provides a default constructor for that class.
An uncaught exception results in the uncaughtException() method of the thread\'s ThreadGroup being invoked, which eventually results in the termination of the programin.
A thread can enter into waiting state in 3 ways: * sleep() method. * wait() method. * suspend() method.
Resource bundle used to contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user\'s locale. This allows you to write programs that can: * be easily localized, or translated, into different languages. * handle multiple locales at once. * be easily modified later to support even more locales. The Java ResourceBundle class eases the process of separating localized resources from an application\'s source code, but you may want to extend the ResourceBundle class to better fit your needs.
Numeric promotion contexts allow the use of an identity conversion or a widening primitive conversion. Numeric promotion is the conversion of a smaller numeric type to a larger numeric type,so that integer and floating-point operations may take place. In numerical promotion,byte, char, and short values are converted to int values. The int values are also convertedto long values, if necessary. The long and float values are converted to double values. Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. In java, if u are arithematic operator on the operands then : * If either operand is of type double, the other is converted to double. * Otherwise, if either operand is of type float, the other is converted to float. * Otherwise, if either operand is of type long, the other is converted to long. * Otherwise, both operands are converted to type int.
Prefix ++ operator first increments the value of operand by 1 and then return the value. Postfix ++ operator first reutrn the value and then increments the value of operands by 1.
Both the statements provides the condition checking of the expressin but Switch statement reduces the complexity of using the multiple if-else clause.
The hashCode() is id number allocated to an object by JVM. Objects in Java have hash codes associated with them. An object\'s hash code is a signed number that identifies the object (for example, an instance of the parent class). An object\'s hash code may be obtained by using the object\'s hashCode() method as follows: int hashCode = SomeObject.hashCode(); The method hashCode() is defined in the Object class and is inherited by all Java objects. In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value.
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
A Java virtual machine or JVM is a virtual machine that runs Java byte code. This code is most often generated by Java compilers, although the JVM has also been targeted by compilers of other languages. The JVM has a stackA stack is a data structure that works on the principle of Last In First Out (LIFO). This means that the last item put on the stack is the first item that can be taken off, like a physical stack of plates. A stack-based computer system is one that is base based architecture. The JVM has instructions for the following groups of tasks * Load and store * Arithmetic * Operand stack management (push / pop) * Type conversion * Control transfer (branching) * Object Creation and Manipulation * Method invocation and return * Throwing exceptions
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. A hashmap is not synchronized and faster than hashtable. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. HashMap does not guarantee that the order of the map will remain constant over time.
Java is strictly pass-by-value. A common misconception exists that parameters in Java are passed by reference. They are not. Parameters are passed by value. Java doesn\'t pass method arguments by reference, it passes them by value i.e. it simply copies the bit pattern holding by the references.
Immutable objects means the value of that object can not be modify by applying operations on them. Java Provides the String class to create the mutable string objects. String s = new String(\"Immutable string.\");
A weak reference is a reference that does not protect the referenced object from the garbage collector.
Object cloning means creating the identical object of any object. If you say : obj1=obj2; In the above statement obj1 is not actually making another copy of object, it simply makes the copy of reference bits. For this purpose java provides the clone() method for object cloning. This method is defined by the Object class.
An object pool is a set of initialised objects that are kept ready to use. Object pooling is a way to manage access to a finite set of objects among competing clients. in other words, object pooling is nothing but sharing of objects between different clients. Pooling basically means utilizing the resources efficiently, by limiting access of the objects to only the period the client requires it. Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.
We know that an object is ready to garbage collected if it is not reachable by any reference. JVM has the facility for the reference counting. Suppose a parent object that has a reference to its child object, which has a reference back to its parent. These objects will never have a reference count of zero even though they may be unreachable by the roots of the executing program. Another disadvantage is the overhead of incrementing and decrementing the reference count each time. Because of these disadvantages, reference counting currently is out of favor. Garbage collection have some disadvantages: * The application�s working set may be larger. * Performance may not be as good as if you hand-optimize memory management (for more details, see �Performance�). * A common design pattern whereby resources are tied to the lifetime of objects does not work effectively under GC. * You must ensure that for any object you want to be long-lived you maintain a chain of strong references to it from a root object, or resort to reference counting for that object.
The Tag interface defines the basic protocol between a Tag handler and JSP page implementation class. It defines the life cycle and the methods to be invoked at start and end tag.
Static method hava some of the following restrictions : * Static methods can not be overridden. * Static methods can only be invoked directly without object reference within the same class and with the class name in another class. * There is only one copy of static method for the entire class. * They are available before creating the instance of the class. * Static method can\'t be declared as final or abstract.
The JIT (just-in-time compiler), also known as dynamic translation, is a technique for improving the runtime performance of a computer program. Java program is compiled into an intermediate language called bytecodes, and it can be downloaded through the network and executed on any computers that have Java execution environment. JIT compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor. The JIT is a code generator that converts Java bytecode into machine language instructions. Some Java Virtual Machines (VMs), including the VM in the Netscape Navigator browser, include a JIT in addition to a Java interpreter. Java programs compiled by a JIT generally run much faster than when the bytecode is executed by an interpreter.
A Locale class represents a specific geographical, political, or cultural region. The Locale class allows you to control how multilanguage text is displayed in a Flash application at runtime. We and create a Locale object using the constructors in this class: * Locale(String language) * Locale(String language, String country) * Locale(String language, String country, String variant)
The URL has a number of component parts. The URL locates a the resource over the internet. The URL class encapsulates Internet URLs. In a way, it does for the Internet resources what the File class does for local files. URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.
The two important TCP Socket classes : * Socket * ServerSocket Socket class allows us to read and write through the sockets. It provides two methods : getInputStream() and getOutputStream(). ServerSocket is used for normal two-way socket communication.
String s=\"Hello\"; String s1=s+\"World\"; In the second line above, We are trying to concatenating the \"Hello\" and a new strign object \"World\". Here a new object is created \"HelloWorld\" and returned to the reference s1. Since string objects are immutable, the reference s is still pointing to \"Hello\".
The classpath is the connection between the Java runtime and the filesystem. It defines where the compiler and interpreter look for .class files to load or the CLASSPATH is an environment variable that tells the Java compiler javac.exe where to look for class files to import or java.exe where to find class files to interpret. The class path can be set using either the -classpath option when calling an SDK tool (the preferred method) or by setting the CLASSPATH environment variable.
A path tells the java compiler and java interpreter where ot find the classes they need to execute or import. Multiple entries in the class path are separated by a semicolon on Windows (;) and by a colon on UNIX (:).
The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures. A collection framework includes : * Collection Interface * Iterator Interface * Set Interface * List Interface * ListIterator Interface * Map Interface * SortedSet Interface * SortedMap Interface * HashSet & TreeSet Classes * ArrayList & LinkedList Classes * HashMap & Treemap Classes Vector & Stack Classes
Yes! We can compile our java program without main() method.
After method and constructor, Initialization blocks are the third place where the operations can be performed. Initialization block do not have identifier and they are of two types : * Instance initialization block. * static initializaton block. Static initialization block starts with the keyword static with opening and ending curly braces. Static initialization block is used to initialize the static variable of the class because they are available before any instance created of the class i.e. before executing the constructor. Hence static initialization block are the right place to initialize the static variable.
When an exception is thrown within the try block the JVM start searching from the first catch block associated with the try block, the first matching catch block is executed and rest are ignored.
If a class doesn\'t have any constructors, the compiler will supply the default constructor.
If a thread cannot acquire a lock on an object, it will enter to the waiting state until it acquire the lock on that object.
Coupling is the degree of dependence between the two modules. Coupling is broken down into loose coupling, tight coupling, and decoupled. Coupling is also used to describe software as well as systems. It is good to have low coupling between the modules for better object oreinted design.
The following syntax is used to define the interface : accessModifier interface InterfaceName{ dataType var1; dataType var2; .............. .............. void method1(); void method2(); .............. .............. } Here accessModifier may be default or public. Interface may contain constant variables. These variables are implicitly public static final, you don\'t have to type it explicitly. Interface can have only public abstract methods, you dont have to type public abstract modifiers explicitly.
An abstract class have abstract modifier in its declaration. An abstract class can contain instance variable, methods that can be concrete methods and abstract methods. An abstract class may not have any abstract method, that does not mean that it is not an abstract class. Example : public abstarct AbstractClass{ // instance variable int a; int b; //instance methods public int getValue(){} public void setValue(int){} //abstract method public int getMaxValue(); }
The JVM heap is where the objects of a Java program live. The JVM\'s heap stores all objects created by an executing Java program. Objects are created by Java\'s \"new\" operator, and memory for new objects is allocated on the heap at run time. The JVM heap size determines how often and how long the VM spends collecting garbage. A Java Virtual Machine on 32-bit operating systems typically has a maximum heap size of 64Mb. You can modify the JVM heap size .
Threads that work in the background to support the runtime environment are called daemon threads. Daemon threads are typically used to perform services for your application/applet. The virtual machine exits whenever all non-daemon threads have completed. Two methods are used in this context: public final void setDaemon(boolean isDaemon) public final boolean isDaemon() By default a thread you create is not a daemon thread. However you can use the setDaemon(true) method to turn it into one. Daemon thread is a low priority thread which runs in the back ground doing the garbage collection operation for the java runtime system.
Volatile means the storage is likely to change at anytime and be changed but something outside the control of the user program. This means that if you reference the variable, the program should always check the physical address (ie a mapped input fifo), and not use it in a cashed way. Variables declared to be volatile will not be optimized by the compiler because the compiler must assume that their values can change at any time. We use volatile keyword to declare the volatile variable.
Suppose You are having the four classes named A, B, C, and D. Assume that class A is the superclass of class B and class C. Now in a programming language, that support multiple inheritance, class D can inherit from the two classes B and C. Suppose class A has a variable v and this variable is inherited in the classes B and C. Again v is inherited by the class D from B and C. Now class D has indirectly inherited variable v form the class A but class D contain two version of the variable b inherited from classes B and C. This is the reason that Java does not support Multiple inheritance. This problem is called diamong problem, because if we desing it graphically, it looks like a diamond shape.
Arraylist is faster than the Vector because ArrayList doesn\'t have synchronisation overhead, i.e. ArrayList has synchronized methods.
Java is considered more secure than any other language because of its bytecode facility. Java applet\'s bytecode is dynamically downloaded over the network instead of the .exe file and executed by the JVM in the browser. So there is no overhead of virus or currepted file, because the JVM also checks the length of the bytecode. Security Implementation Mechanisms : * Java Authentication and Authorization Service (JAAS). * Java Generic Security Services (Java GSS-API). * Java Cryptography Extension (JCE). * Java Secure Sockets Extension (JSSE). * Simple Authentication and Security Layer (SASL). Java security services are separate from the security mechanisms of the operating system. Java provides security at various layers: * Application-Layer Security : At the application layer, application firewalls can be employed to enhance application protection by protecting the communication stream and all associated application resources from attacks. * Transport-Layer Security : Transport-layer security relies on secure HTTP transport (HTTPS) using Secure Sockets Layer (SSL). Transport security is a point-to-point security mechanism that can be used for authentication, message integrity, and confidentiality. * Message-Layer Security : In message-layer security, security information is contained within the SOAP message and/or SOAP message attachment, which allows security information to travel along with the message or attachment.
The Phantom memory is a false memory. Memory that does not exist in reality. Phantom references point to objects that are already dead and have been finalised.
Reflection is an API in java that allows an executing Java program to examine or \"introspect\" upon itself, and manipulate internal properties of the program. For example, it\'s possible for a Java class to obtain the names of all its members and display them. A reflection is what you see when you look in the mirror. Reflection is for dealing with class files you know very little about ahead of time. It is a powerful approach to analyze the class at runtime. If new classes are added into your application dynamically then Reflection is used to get the structure of the class. Example : import java.lang.reflect.*; public class ShowMethods { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Method methods[] = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) System.out.println(methods[i].toString()); } catch (Throwable e) { System.err.println(e); } } }
HotSpot is a JIT compiler. JIT is a part of the JVM that compiles Java bytecode to native machine code at runtime, to make your Java program run faster. HotSpot is the name of Sun\'s JIT compiler which is included in Sun\'s JVM. HotSpot generate native machine code for the CPU that they execute on.
Creating too many threads in one JVM can cause the system to run out of memory or thrash due to excessive memory consumption. To prevent resource thrashing, server applications need some means of limiting how many requests are being processed at any given time. A thread pool offers a solution to both the problem of thread life-cycle overhead and the problem of resource thrashing. Methods in org.apache.avalon.cornerstone.blocks.threads that return ThreadPool ThreadPool AbstractThreadManager.getThreadPool(java.lang.String name) : Retrieve a thread pool by name. ThreadPool AbstractThreadManager.getDefaultThreadPool() : Retrieve the default thread pool.
The comparable interface should be used when the current object is to be compared to objects of its type only. The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn\'t know how to compare the objects and expects you to give it. You have a set of objects where you want to sort it in both ascending and decending order. Just Comparable will not help you in this. Here you can implement your own comparator and pass it to the sorting algorithm to use.
List is an ordered collection of elements by index. Key methods of List are : get(int index), indexOf(Object o), add(int index, Object o), etc. A Set cares about Uniqueness, it doesn\'t allow duplicates elements. The equals() method helps you to find out whether two objects are identical. A map stores the elements in the form of Key/Value pairs. Here key and value both are objects. A map cares about unique key (unique ID) to a specific value. You can search value in a Map by giving its key.
Exceptions are the abnormal condition that you can handle by your program, but Error is an unrecoverable condition that can be handled by the program at runtime. Both Exceptiona and Error classes are drived from the class Trowable. Java running out of memory is an Error and can not be handled by the program.
Java is an open source language that means you are free to download the java compiler and JVM. You don\'t have to buy these software.
The applet can send a GET/POST request to the servlet by opening a servlet URL with a query string. For example : // servlet URL URL url = new URL(getCodeBase(), \"/MyServlet?name=ABC\"); // open a connection to the servlet URLConnection servletCon = url.openConnection(); servletCon.setDoInput(true); // true, if we get data back // get the input stream from the servlet InputStream in = servletCon.getInputStream(); // read the response from the servlet .................. .................. }
Different types of inner classes : * Regular inner classes. * Method local inner classes. * Anonymous inner classes. * Static nested classes.
Nested top-level classes are declared within an enclosing class. Nested top-level classes are always defined with a static keyword. A nested top-level class/interface is defined as a static member of its enclosing class/interface, i.e. static inner classes are called nested top level classes.
A member class is one that is declared within the class as like member varaibles and member functions. These classes are called inner classes, and can be instantiate with only if the enclosing class has been intantiated.
No! A top level class can\'t be private or protected, it can only be either public or default.
When invoked, the process starts but does not complete. Sometimes this may appear to be caused by the input that is being fed to the process which adds to the confusion over why the problem occurs.When you invoke any process from Java, you must use separate threads to pump data to/from
Composition is a design technique that establishing relationships between classes. There are two fundamental ways to relate classes : inheritance and composition. Composition is an alternative way of inheritance to ralate classes. Example : class Fruit { //... } class Mango { Fruit fruit = new Fruit(); //... }
Aggregation is a collection of several things grouped together or aggregation is a special kind of association that specifies a whole or a part of relationship. For example : A \'Car\', is consisted of an engine,a steering wheel, four tires, seats, gear box, fuel tank, engine oil tank, air filters etc. So all constituents of car are parts of it. Aggregation is transitive, i.e., if A is a part of B, and B is a part of C, then A is also a part of C. Aggregation is antisymmetric, i.e., if A is a part of B, then B is not a part of A.
The methods of Object class are : * protected Object clone() : Creates and returns a copy of this object. * boolean equals(Object obj) : Indicates whether some other object is \"equal to\" this one. * protected void finalize() : Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. * Class extends Object> getClass() : Returns the runtime class of an object. * int hashCode() : Returns a hash code value for the object. * void notify() : Wakes up a single thread that is waiting on this object\'s monitor. * void notifyAll() : Wakes up all threads that are waiting on this object\'s monitor. * String toString() : Returns a string representation of the object. * void wait() : Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. * void wait(long timeout) : Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. * void wait(long timeout, int nanos) : Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
When two or more threads access the shared variable and perform read/write operations, this variable should be declared within the synchronized method. The Java language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. The volatile modifier requests the Java VM to always access the shared copy of the variable so the its most current value is always read. Either put the variables in a synchronized method or block, or declare them volatile.
Drawbacks of inheritance : * Difficulty of understanding complex hierarchy. * Makes writing a compiler harder, e.g. requires more dynamic type checking since type of an object can change during runtime. * Adversely affects execution speed, program size, program complexity, and incurs method passing overhead. * Inheritance forces a set of methods and fields on a class. You may not want some of these, and it is not necessary that all of these are required. There is no concept of partial inheritance. * Interface stability of base classes sometimes require even more complexity.
The restrictions placed on the values of each case of a switch statement are : * The values of each case of a switch statement must be a compile time constant. * Only use the values that can be promoted to an int value, i.e. use byte, short, char, int only.
In Java API, we have an Array class which has a variable named \"length\" to count the length of the array, hence we say, aaaa.length to count the length of the array. In the String class, we have a method named length(), which returns the length of the string.
In most of the programming languages, variables can be assigned value in two ways : First, at the time of variable declaration. Second, later in the program. If you assigned value to variable later in the program, then the varaible will not hava a value at the time of compilation, it will be assigned a value at runtime. This runtime assignment of value to variable is called Dynamic typing.
Assignment of value to the variable at the time of variable declaration is called static typing.
Map is an Interface and HashMap is a class that implements the Map interface. HashMap is not serialized.
An object is a runtime entity. It is an instance of the class and have its own state, made up of values assigned to all variables of its class collectively. An object will hava access to all the behaviours(methods) of its class. The object can be allocated memory using the \"new\" keyword. For Example : //class declaration class CrateObject{ } //Object creation CreateObject o = new CreateObject();
Java uses the unicode character set for all the characters and symbols of the world. The Unicode provides the Standard character set to support all language, platform, program. Before the invention of Unicode, many different character sets and encodings had to be used for different languages. It was not possible to store plain text files containing text from languages using different character sets in the same document. Unicode provides a unique number for every character. The Unicode Consortium is a non-profit organization founded to develop, extend and promote use of the Unicode Standard, which specifies the representation of text in modern software products and standards.
A stream is sequence of flowing data. Stream is an abstract class in Java, that is used to either read the data or write the data to/from a disk file, device, a network socket, other programs, a memory array etc. There are two types of streams that Java support : * Byte oriented streams. * Characters oriented streams. Classes of the Streams : * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * ByteArrayInputStream * ByteArrayOutputStream * CharArrayReader * CharArrayWriter * DataInputStream * DataOutputStream * FileInputStream * FileOutputStream * FileReader * FileWriter * FilterInputStream * FilterOutputStream * FilterReader * FilterWriter * InputStream * InputStreamReader * LineNumberReader * ObjectInputStream * ObjectOutputStream * OutputStream * OutputStreamWriter * PipedInputStream * PipedOutputStream * PipedReader * PipedWriter * PrintStream * PrintWriter * PushbackInputStream * PushbackReader * RandomAccessFile * Reader * SequenceInputStream * StreamTokenizer * StringReader * StringWriter * Writer
TCP/IP is a reliable connection oreinted network protocol. It ensure that a file sent from one network node to another node is a complete file. UDP is a connectionless, unreliable network protocol. UDP is faster than TCP/IP. UDP is used where the speed of data transmission is more important than reliability.
In multithreading environment multiple threads run concurrently, sometimes you need two thread to communicate to each other by forwarding the data. The multithread data access and communication classes are: Mutex, Condition, and Lock
A thread group represents a set of threads. Every Java thread is a member of a thread group. In addition, a thread group can also include other thread groups. Threads can only access the ThreadGroup to which they belong. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. A tree structure can be formed from ThreadsGroups containing other ThreadGroups. Java provides the ThreadGroup class for creating and managing the thread groups. The ThreadGroup class provides two constructors : ThreadGroup(String name) ThreadGroup(ThreadGroup parent, String name)
When you write a large number of objects into an Object output stream, these objects might be unreachable by the reference that the reference table is hoding. If they are not garbage collected by the JVM, resulting the running out of memory error. A call to the ObjectOutputStream.reset() method resets the object/handle table to its initial state, allowing all previously written objects to be eligible for garbage collection.
The following code can help u to obtain serialVersionUID of a class import java.io.*; public class jk { public static void main(String args[]) { String s = new String(\"test\"); Class cl = s.getClass(); long uid = ObjectStreamClass.lookup(cl).getSerialVersionUID(); System.out.println(uid); } }
This output of the above program : 10
The above program give an error in compilation, like a non-static field can be referenced from a static context. The problem lies in the variable i in print statement inside the main() method. The variable i can only be accessed through the object reference.
The above program give an error in compilation, illigal start of expression at static int i in the static initialization block.
The above program give 3 errors in compilation : 1. a non-static variable i can be referenced from a static context in the main method. 2. modifier static is not allowed in the static initialization block. 3. can\'t assign a value to final variable.
The above program will give an error : can not assign a value to a final variable at i=10 in the static initialization block.
Program will give error : illigal start of expression at \"static final int i=0;\"
Program will give error : illigal start of expression at \"static int i=0;\"
The program will give error : a non-static method display() can be referenced from a static context.
Output of the program : 0 90
Output of the program : 0 90
Output of the program : 0 90 90
Output of the program : 0 90
The program will give an error : a non-static method display() can not be referenced from a static context.
This keyword is basically a Java keyword ,\'this\' can be used to access class variables and methods.
thread is the basically as basic unit of program execution. A process can have several threads running concurrently, each performing a different job, such as waiting for events or performing a time consuming job that the program doesn\'t need to complete before going on. When a thread has finished its job, the thread is suspended or destroyed. See also process.
Throw is the bassically as a Java keyword that allows the user to throw an exception or any class that implements the \"throwable\" interface.
Throws is the basically a Java keyword , It is used in method declarations that specify which exceptions are not handled within the method but rather passed to the next higher level of the program.
Transaction is basscially an atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which either complete or roll back. Transactions enable multiple users to access the same data concurrently.
transient is the basically a keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included.
try is the basically as a Java keyword that defines a block of statements that may throw a Java language exception. If an exception is thrown, an optional catch block can handle specific exceptions thrown within the try block. Also, an optional finally block will be executed regardless of whether an exception is thrown or not.
It is basically a class or interface.
Variable is the basically identifier, which item of data named by an identifier. Each variable has a type, such as int or Object, and a scope.
For example :
- Class variable,
- Instance variable,
- local variable.
Void is basically a type of Java keyword , It is used in method declarations to specify that the method does not return any value. void can also be used as a nonfunctional statement.
Volatile is basically a Java keyword used in variable declarations that specifies that the variable is modified asynchronously by concurrently running threads.
While is the basically a type of Java keyword, It is used to declare a loop that iterates a block of statements. The loop\'s exit condition is specified as part of the while statement.
Wrapper is the type of object, its encapsulates and delegates to another object to alter its interface or behavior in some way.
Class method is the bassically a that type method which is invoked without reference to a particular object. Class methods affect the class as a whole, not a particular instance of the class. Also called a static method. See also instance method.
Clas variablw is the basscially a type of data item which is associated with a particular class as a whole not with particular instances of the class. Class variables are defined in class definitions. Also called a static field. See also instance variable.
A pseudo-method that creates an object. In the Java programming language, constructors are instance methods with the same name as their class. Constructors are invoked using the new keyword.
That is the bassically a java keyword which is used for the represent an instance of the class in which it appears.
Web application archive file. A JAR archive that contains a Web module.
A Utility class is bassicaly a class that contains grouped static functionality
yes
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread\'s run() method when the thread is initially executed.
The advantages of Spring framework are:
- Spring is a layered architecture
- Spring Enables POJO (Plain Old Java Object) Programming. POJO programming enables continuous integration and testability.
- Dependency Injection and Inversion of Control Simplifies JDBC
- Spring is an open source framework available to all for commercial purpose.
Features of Spring :
Lightweight :- Spring is lightweight in terms of size and overhead. The entire spring network can be distributed in a single JAR file that weights in at just over 1 MB.
Inverse of Control :- The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don\'t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A IOC container) is then responsible for looking it all.
Aspect-Oriented :- Spring supports the features of aspect oriented programming approach that enables cohesive development.
Container :- Spring is a container because it manages the life cycle and configuration of application objects.
Framework :- Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI.
The bean factory performs several steps before a bean is ready is use:
- Instantiate.
- Populate properties.
- The factory calls BeanNameAware\'s setBeanName() method.
- The factory calls BeanFactoryAware\'s setBeanFactory() method.
- PostProcessBeforeInitialization() method is called if BeanPostProcessor associated with the bean.
- An init-method is called, if specified.
- Finally, PostProcessAfterInitialization() is called if BeanPostProcessor associated with it.
Piecing together beans within the Spring container is known as wiring. Wiring the beans means you are telling the Spring container what beans are needed and how the container should use dependency injection to tie them together. You should have some basic idea of XML for basic wiring of beans.
A bean can be added in spring application using :<beans>
<bean id=\"foo\" class=\"com.Foo\"/>
<bean id=\"bar\" class=\"com.Bar\"/>
</beans>
in the Spring configuration file. In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.
The org.springframework.beans.factory.xml.XmlBeanFactory is a class that implements the BeanFactory interface. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file to XmlBeanFactory.
BeanFactory factory = new XmlBeanFactory(new FileInputStream(\"beans.xml\"));
To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve.
MyBean myBean = (MyBean) factory.getBean(\"myBean\");
The singleton property of <bean> tells the context whether or not a bean is to be defined as a singleton.
This attribute in bean tag named \"singleton\" if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true.
So, all the beans in spring framework are by default singleton beans.
<beans>
<bean id=\"bar\" class=\"com.act.Foo\" singleton=\"false\"/>
</beans>
Prototyped beans are useful when you want the container to give a unique instance of a bean each time it is asked for, but you still want to configure one or more properties of that bean through Spring.
<bean id=\"student\" class=\"com.StudentImpl\"
singleton=\"false\">
A new instance of a prototype bean will be created each time getBean() is invoked with the bean\'s name.
We use the <property> element to set the properties that reference other beans.
The <ref> sub-element of <property> lets us do this:
<bean id=\"foo\"
class=\"com.Foo\">
<property name=\"bar\">
<ref bean=\"bar\"/>
</property>
</bean>
You can embed a <bean> element directly in the <property> element.
For Example:<bean id=\"student\"
class=\"com.StudentImpl\">
<property name=\"course\">
<bean class=\"com.CourseImpl\"/>
</property>
</bean>
The drawback of wiring a bean reference in this manner is that you can\'t reuse the instance of StudentImpl anywhere else.
When autowiring using byType or constructor, it\'s possible that the container may find two or more beans whose type matches the property\'s type or the types of the constructor arguments. What will happen if there are ambiguous beans suitable for autowiring?
Spring can\'t sort out ambiguities and chooses to throw an exception rather than guess which bean you meant to wire in. If you encounter such ambiguities when autowiring, the best solution is not to autowire the bean.
Yes. You can wire a string value to a property whose type is a non-string. The java.beans.PropertyEditor interface provides a means to customize how String values are mapped to non-String types. 7
This interface is implemented by java.beans.PropertyEditorSupport that has two methods:
getAsText() : returns the String representation of a property\'s value.
setAsText(String value) : sets a bean property value from the String value passed in.
If you want to map the non-string property to a String value, the setAsText() method is called to perform the conversion.
The ThrowsAdvice lets you definebehaviour should an exception occur. ThrowsAdvice is a marker interface and contains no method but need to be implemented. A class that implements this interface must have at least one method with either of the following two signatures: * void afterThrowing(Throwable t) * void afterThrowing(Method m, Object[] o, Object target, Throwable t)
The PreparedStatementCreator interface is a callback interfaces used by the JdbcTemplate class. This interface creates a PreparedStatement given a connection, provided by the JdbcTemplate class. Implementations are responsible for providing SQL and any necessary parameters. A PreparedStatementCreator should also implement the SqlProvider interface if it is able to provide the SQL it uses for PreparedStatement creation. This allows for better contextual information in case of exceptions. It has one method: PreparedStatement createPreparedStatement(Connection con) throws SQLException Create a statement in this connection. Allows implementations to use PreparedStatements. The JdbcTemplate will close the created statement.
Spring Framework supports:
- Programmatic transaction management.
- Declarative transaction management.
Spring provides a unique transaction management abstraction, which enables a consistent programming model over a variety of underlying transaction technologies, such as JTA or JDBC. Supports declarative transaction management. Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA. Integrates very well with Spring\'s various data access abstractions.
PQSRQSRQ
type var-name[];
OR
type[] var-name;
// both are valid declarations
int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
int[] intArray = new int[30];
int[] intArray = new int[]{ 1,2,3,4,5,6,7};
We know about the variable access, Which is signifies to the ability of code in one class to access a variable in another class, in this case we\'ll looking at the other keywords that apply to variable declarations,but first we\'ll do a quick review of the difference between instance and local variables.
Instance variable is basically a signifies inside the class but in the outside of any method and its initialized when class is initialized. its mainly a field which is belongs to the unique object.This is following in the code.:class Employee {
// define fields (instance variables) for employee instances
private String name;
private String title,
private String manager;
// other code goes here including access methods for private fields
}
Local variable is basically use for the declared within a method, Its means mainly variable is not just initialized within the method, but also declared within the method, Local variable is basically in always n the stack but its not happening in the case of heap.if the variable is an object reference the object itself will still be created on the heap.
There is no such thing as a stack object, only a stack variable.
class TestServer {
public void logIn() {
int count = 10;
}
}
The compiler will reject any code that tries to use a local variable that hasn\'t been assigned a value, because unlike instance variables local variables don\'t get default values.
class TestServer {
public void logIn() {
int count = 10;
}
public void doSomething(int i) {
count = i; // Won\'t compile! Can\'t access count outside method login()
}
It is possible to declare a local variable with the same name as an instance variable.
class TestServer {
int count = 9; // Declare an instance variable named count
public void logIn() {
int count = 10; // Declare a local variable named count
System.out.println(\"local variable count is \" + count);
}
public void count() {
System.out.println(\"instance variable count is \" + count);
}
public static void main(String[] args) {
new TestServer().logIn();
new TestServer().count();
}
}
OUTPUT is :
local variable count is 10
instance variable count is 9
final variable is basically declared by the final keyword , It makes impossible to reinitialize that variable once it has been initialized with an explicit value.
object reference variable is basically a reference variable marked final can\'t ever be reassigned to refer to a
different object.When the data is in the object form and we would like to modified but the reference variable can not be changed , we can also say like we can use final reference to modify the object it refers to, but we can\'t modify the reference variable to make it refer to a different object.there are no final objects, only final references.
A reference variable\'s value in other words, the bit pattern the variable holds is not an object,A reference variable holds bits that represent, in a platform-dependent format, a way to get to an object.
We can see in this code :class FinalTest{
final int x; // Will not work unless x is assigned in the constructor
public void showFinal() {
System.out.println(\"Final x = \" + x);
}
}
Attempting to compile the preceding code gives us the following:
%javac FinalTest.java
FinalTest.java:2: Blank final variable \'x\' may not have been
initialized. It must be assigned a value in an initializer, or in
every constructor.
final int x;
1 error
If we would like to declare an instance variable as final, but don\'t give it an explicit value at the time we declare it, the variable is considered a blank final. The final instance variable can stay blank only until the constructor completes.class FinalTest{
final int x; // Will work because it\'s initialized in the constructor
public FinalTest() {
x = 28; // Whew! The compiler is relieved that we took care of it
System.out.println(\"Final x = \" + x);
}
}
declaring an object reference variable as final:import java.util.Date;
class TestClass {
final Date d = new Date();
public void showSample() {
d.setYear(2001); //Altering Date object, not d variable, so it\'s OK
}
}
If we mark to the instance variable as a transient variables , When we enter to the serialize the object declaring it then the java to ignore this variable.
Serialization is the very good and important feature of the java , When we would like We can save it and also called the flatten an object by writing its state we can also say the value of its instance variables to a special type of IO stream.
A Volatile modifier explains the JVM that a thread accessing the variable must always reconcile which is own private copy of the variable with the master copy of the memory .
The volatile modifier may also be applied to project managers
Static modifiers has a many special type of methods and variables which is treating as a concepts entirely separate from the other modifiers.the count will just be initialized back to a default value with each new instance. The answer to both the utility method always runs the same scenario and the keep a running total of instances scenario is to use the static modifier. Variables and methods are marked static which is belong to the class, That\'s why we can use static method or variable without having any instances of that class at all. We need only have a class available to be able to invoke a static method or access a static variable.
Static variables : It can be accessed without having an instance of a class. But in this case instance a static variable of a class will be shared by all instances of that class; there is only one copy, That are following in this code.
class Frog {
static int frogCount = 0; // Declare and initialize static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println(\"Frog count is now \" + frogCount);
}
}
Accessing Static method is very impotent for the any code .When instance of the classes in the code is absence then how to code is appropriate that we can use the accessing static method for make a appropriate code.
So in this way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to on a reference to an instance, as follows :class Frog {
static int frogCount = 0; // Declare and initialize static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
}class TestFrog {
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.print(\"frogCount:\"+Frog.frogCount); //Access static variable
}
}
Another point to remember is that static methods can\'t be overridden! This doesn\'t mean they can\'t be redefined in a subclass, as we\'ll see a little later when we look at overriding in more detail, but redefining and overriding aren\'t the same thing.
Things you can mark as static:
Methods
Variables
Top-level nested classes
Things we can\'t mark as static :
Constructors
Classes
Interfaces
Inner classes
Inner class methods and instance variables
Local variables
Declaration rules is basically a identifying correctly constructed source files, package declarations, import statements, class declarations, interface declarations, method declarations, variable declarations, and identifiers.
We just focusing about Source File Structure which is the kind of import and package issues .The following legal code declares a class Foo, in package com.geeksanonymous :
package com.geeksanonymous; // Notice the semicolon
class Foo { }
Here in this code its singing a only one package statement per source cod file , that\'s are following as :
package com.geeksanonymous;
package com.wickedlysmart; // Illegal! Only one package declaration allowed
class Foo { }
If class Foo adds any import statement then the code is :
package com.geeksanonymous;
import java.util.*; // Wildcard package import
import com.wickedlysmart.Foo; // Explicit class import
class Foo { }
If the Class Foo dont have a package then the import statements must be above the:
class declarationof the above code .as folows :
import java.util.*; // Wildcard package import
import com.wickedlysmart.Foo; // Explicit class import
class Foo { }
We can use import function in the two ways :
- wildcard import
- explicit class import
Import statements are little more than a way for us to save keystrokes when we\'re typing our code. We essentially give the class a longer name, which we call the fully qualified name.
The compiler would never know what you meant if you typed the following:
class Bar {
void doStuff() {
Foo f = new Foo(); // Here you want the WickedlySmart version
} // But how will the compiler know?
}
To eliminate the confusion, you\'re required to do one of two things to help the
compiler:
1. Use an import statement,
import com.wickedlysmart.Foo;
class Bar {
void doStuff() {
Foo f = new Foo(); // Now the compiler knows which one to use
}
}
or
2. Use the fully qualified name throughout your code:
class Bar {
void doStuff() {
com.wickedlysmart.Foo f = new com.wickedlysmart.Foo() // No doubts
}
}
When we want our code to actually run, We have to get the ball rolling with a main() method. The following rules apply to the main() method :It should be declared public (for the purposes of the exam, assume it must be public).
- It must be marked static.
- It must have a void return type.
- It must have a single String array argument.
- We can name the argument anything we want.
other methods is that it has the signature the JVM is looking for when you invoke Java as follows :
java MyClass
method the one with a signature matching what the JVM is searching for. If it finds the matching method, We are good to go. If it doesn\'t, We get a runtime error like this :
Exception in thread \"main\" java.lang.NoSuchMethodError: main
The tricky thing about this error is that we can get it even when there is a main()
method. The following code compiles fine, but still produces the previous NoSuchMethodError when we try to invoke this class from the command line:class MyClass {
public void main (String [] args) { }
}
Interface implementation is a identifying class that correctly implement N an interface which is from java.lang
When we create an interface We can define the functioning of the class i mean to say we can define whats the exactly the call can do .without saying anything about how the class will do it. Interface is basically a contract.
In this interface we are allowed to put a constants in an interface,it would be much easier for programmers to remember names like HIGH_GRAVITY, LOW_BOUNCE, and HIGH_BOUNCE as opposed to knowing the exact int values corresponding to each of those. we have a following code :
public final static int LOW_BOUNCE = 4;
public final static int HIGH_GRAVITY = 3;
//
That way, if a method takes the int values,
public void animateIt(int gravity, int bounceFactor) { }
then the code that calls animateIt() can substitute the constants wherever the
int values are expected, as follows:
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE);
changes we\'ve made
to the Bounceable interface:
public interface Bounceable {
int LOW_GRAVITY = 1;
int MEDIUM_GRAVITY = 2;
int HIGH_GRAVITY = 3;
int LOW_BOUNCE = 4;
int MEDIUM_BOUNCE = 8;
int HIGH_BOUNCE = 12;
void bounce();
Interface Implementation (Exam Objective 4.2) 59
void setBounceFactor(int bounceFactor);
void setGravity(int gravity);
}
By placing the constants right in the interface, any class that implements the interface
has direct access to the constants, just as if the class had inherited them. For example,
the following would be legal for a Bounceable implementation class:
class Ball implements Bounceable {
// Lots of exciting code goes here
public void bounce() {
animator.animateIt(LOW_GRAVITY, HIGH_BOUNCE); // MUCH easier this way
}
// Still more action-packed code goes here
}
We have a some Rules for the interface constraints :
- public
- static
- final
When we would like to implement an interface , we\'re agreeing to adhere to the contract defined
in the interface. its mean we are authorized person for the provide legal implementations for
every method defined in the interface,and that anyone who knows what the interface methods look like (not how they\'re implemented, but how they can be called and what they return) can rest assured that they can invoke those methods on an instance of our implementing class.
We looked earlier at several examples of implementation classes, including the Ball class that implements Bounceable, but the following class would also compile legally:
public class Ball implements Bounceable { // Keyword \'implements\'
public void bounce() { }
public void setBounceFactor(int bf) { }
}
Implementation classes must adhere to the same rules for method implementation as a class extending an abstract class. In order to be a legal implementation class, a nonabstract implementation class must do the following:
- Provide concrete (nonabstract) implementations for all methods from the declared interface.
- Follow all the rules for legal overrides
- Declare no checked exceptions on implementation methods other than those declared by the interface method, or subclasses of those declared by the interface method.
- Maintain the signature of the interface method, and maintain the same return type (but does not have to declare the exceptions declared in the interface method declaration).
The system identifies you by the user id and group id assigned to you by system administrator. You don\'t need to remember your user id and group id, the system translate username as user id and group name as group id. You need to know your username only.
An Action class in the struts application extends Struts \'org.apache.struts.action.Action\" Class. Action class acts as wrapper around the business logic and provides an interface to the application\'s Model layer. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the processed data from business layer to the view layer.
An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects an appropriate Action and creates an instance if necessary, and finally calls execute method.
To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class don\'t add the business process logic, instead move the database and business process logic to the process or dao layer.
The ActionServlet (command) passes the parametrized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
The new operator instantiates a class by allocating memory for new object and returning a reference to that memory. The new operator also invokes the object constructor. The new operator dynamically allocates memory for an object. It has this general form: class-var = new classname( ); The reference returned by the new operator does not have to be assigned to a variable. The answer is that Java\'s simple types are not implemented as objects. Rather, they are implemented as \"normal\" variables
Following is added into jdk1.5 .which was not into jdk1.5: Java Language Features Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations) Virtual Machine Class Data Sharing Garbage Collector Ergonomics Server-Class Machine Detection Thread Priority Changes Fatal Error Handling High-Precision Timing Support So many other new features has been added.
ActionForm class is used to capture user-input data from an HTML form and transfer it to the Action Class. ActionForm plays the role of Transport Vehicle between the presentation Tire & Business Tier.
Life Cycle :
1. Request received by Controller
2. Create or recycle ActionForm
3. Call reset()
4. store ActionForm in proper scope
5. populate ActionForm from Request
6. Validate the ActionForm
7. If errors found then forward back to input attribute page(configured in Action mapping in struts-config.xml) with
ActionForm in scope. If no errors found then call execute() with the ActionForm.
The steps would be like this (in terms of the diagram)
A. Client will point to the controller
B. Controller would point to action form
C. Actionform would point to action class
D. Action class would point to JSP?
E. JSP would point to client
It contains the statements which likely to throw an exception. If an exception is raised, the remaining statements in the try block are skipped. Try block must be followed by either catch or finally or both. The catch block is executed only if try block throws an exception. Catch block cannot be written without try block. For each try block there can be zero or more catch blocks.
To use the Struts Spring plugin, add the ContextLoaderPlugIn to your Struts config file (usually struts-config.xml):
<plug-in className=\"org.springframework.web.struts.ContextLoaderPlugIn\">
<set-property property=\"contextConfigLocation\"
value=\"/WEB-INF/applicationContext.xml\"/>
</plug-in>
The \"contextConfigLocation\" property is the location of the Spring beans configuration file.
For each action that uses Spring, you need to define the action mapping to use org.springframework.web.struts.DelegatingActionProxy and declare a matching (action \"path\" == bean \"name\") Spring bean for the actual Struts action. This is an example of an action that requires an instance of UserDatabase:<action path=\"/logon\"
type=\"org.springframework.web.struts.DelegatingActionProxy\">
<forward name=\"success\" path=\"/logon.jsp\"/>
</action>
The corresponding Spring bean configuration:
<bean id=\"userDatabase\" class=\"org.apache.struts.webapp.example.memory.MemoryUserDatabase\" destroy-method=\"close\" />
<bean name=\"/logon\" class=\"org.apache.struts.webapp.example.LogonAction\">
<property name=\"userDatabase\"><ref bean=\"userDatabase\" /></property>
</bean>
For more information on the Spring configuration file format, see the Spring beans DTD.
The Struts action org.apache.struts.webapp.example.LogonAction will automatically receive a reference to UserDatabase without any work on its part or references to Spring by adding a standard JavaBean setter:
private UserDatabase database = null;
public void setUserDatabase(UserDatabase database) {
this.database = database;
}
Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.
Request Lifecycle in Struts 2 applications
User Sends request: User sends a request to the server for some resource.
FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
Interceptors are applied: Interceptors configured for applying the common functionalists such as workflow, validation, file upload etc. are automatically applied to the request.
Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving data from the database.
Output rendering: Then the Result renders the output.
Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.
Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.
The Flow of a Struts 2.0 Application
The following are the sequence of steps that will happen when a Html Client makes a request to a Web Application built on top of Struts 2.0
The Client (which is usually a Html Browser) makes a Request to the Web Application.
The Web Server will search for the Configuration Information that is very specific to the Web Application (taken from the web.xml file), and will identity which Boot-strap Component has to be loaded to serve the Client\'s Request.
In Struts 2.0, this Component is going to be a Servlet Filter (whereas in Struts 1.0, the component is an Action Servlet).
The Filter Servlet then finds out the Action Class for this Request that is mapped in the Configuration File. File.
Before passing the Request to the Action class, the Controller passes the Request to a series of Interceptor Stack (explained later).
Then the Request Object is passed on to the corresponding Action Class.
The Action Class then executes the Appropriate Business Logic based on the Request and the Request Parameters.
After the execution of the Business Logic, a Result (\"success\" or \"error\") is returned either in the form of String or in the form of Result Object back to the Controller.
The Controller uses the Return Result to choose which View to be rendered back to the Client Application.
The JRE is the environment within which the virtual machine runs.JRE JAVA Runtime Environment JVM JAVA Virtual Machine JRE is the container, JVM is the content. JRE=JVM+ rt.jar The JRE includes the JVM, which is what actually interprets the byte code and runs the program. To do this the JVM uses libraries and other files provided by the JRE.
There are two types of Controllers in Struts.
1.Main Controller/FrontController
Ex: ActionServlet
2.Application Controller
Ex:Action Class
ASP Stands for Active server Pages.ASP used to create interacting web pages.
Collections is a class, contains methods such as sort(), binarySearch(), copy(), etc.ADD, Remove, Search, retrieve operations can be performed.
EJB technology is the server-side component architecture for the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.
This method is used to detect the automatically unicode and sets its encoding appropriately. Simply we can use the setSheetName(int sheet, String encoding) method. this has the facility to set the unicode for setting encoding appropriately.
In this page of the tutorials we are trying to find records of an excel sheet using POI2.5 API Event. The class RowRecordextends Record implements Comparable. in this program it class is store the row information for the sheet.
This methods get the first column number for the sheet.
This methods get the last col number for the sheet.
The org.apache.poi.hssf.record.NumberRecord class extends Record and implements CellValueRecord interface, java.lang.Comparable interface.
We creates an object of the shape. In this object of the shape we are assigning rectangle shape and set the size and position. Initial values for x and y axis are 0.The height and width are 400 and 400 respectively. Then create an object of Shape and set values, fill type, background color and foreground color of the slide. Then finally add into slide. We are using setFillType(Fill.FILL_SHADE) method to set fill type, setBackgroundColor(Color.blue) method to set background color and setForegroundColor(Color.green) method to set the text color.
This methods add a picture to the workbook and the return type is int of this method. In This method two parameters are passed into this method. The first parameter is pictureData and second parameter is format .The pictureData is byte form of the picture. In this example we are using Picture.PNG as format.
setPageSize(java.awt.Dimension pgsize):-
This methods provide the feature of for change the size current page. The page size range passed as parameter in this method. The return type is void. This method is defined as public in SlideShow class.
Encapsulation, Inheritance and Polymorphism are the three OOPs Principles. Encapsulation: Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. Inheritance: Is the process by which one object acquires the properties of another object. Polymorphism: Is a feature that allows one interface to be used for a general class of actions.
The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.The postfix form returns the current value of all of the expression and thenperforms the increment or decrement operation on that value.
Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.
String objects are constants, whereas StringBuffer objects are not. String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings.
abcdefabcDEF
The File class is used to create objects that provide access to the files and directories of a local file system.
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-bits, it is usually represented as 8-bits. UTF-8 represents characters using 8, 16 and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns
An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
The BeanFactory is provide an advanced configuration mechanism capable of managing beans of any kind of storage facility.
The ApplicationContext builds on top of the BeanFactory and adds other functionality like integration with Springs AOP features, message resource handling for use in internationalization, event propagation, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements.
java.lang.Object
1. casting
2. Hierarchical and object oriented structure.
Basically for inter tribal communication.
== is used to check whether the references are of the same object.
.equals () is used to check whether the contents of the objects are the same.
But with respect to strings, object reference with same content
will refer to the same object.
String str1=Hello;
String str2=Hello;
(str1==str2) and str1.equals(str2) both will be true.
If you take the same example with String-buffer, the results would be different.
String-buffer str1=Hello;
String-buffer str2=Hello;
str1.equals(str2) will be true.
str1==str2 will be false.
No. String is not a Wrapper class
Using length () method of String class.
String str1 = \"ABC\";String str2 = \"XYZ\";String str1 = str1 + str2;There are 3 Objects.
The trim () eliminate spaces from both the ends of a string.
ArrayIndexOutOfBoundsException
New features in Java SE 8 Lambda Expressions Pipelines and Streams Date and Time API Default Methods Type Annotations Nashhorn JavaScript Engine Concurrent Accumulators Parallel operations PermGen Error Removed New features in Java SE 7 Strings in Switch Statement Type Inference for Generic Instance Creation Multiple Exception Handling Support for Dynamic Languages Try with Resources Java nio Package Binary Literals, Underscore in literals Diamond Syntax Automatic Null Handling
1. Running Java File with single command,directly run the file with java command and it implicitly compiles. 2. Added new String Methods e.g. isBlank() ,lines(),strip(), stripLeading(), stripTrailing(),repeat(int) 3.JEP 323, Local-Variable Syntax for Lambda Parameters .
var list = new ArrayList< String >() (var s1, var s2) -> s1 + s2 It was in Java 8 but got removed in Java 10. Now it’s back in Java 11 The JDK 11 also allow annotations to be added to lambda’s parameters without having to write full variable type name Function< String, String > append = (@NonNull var string) -> string + " World";
Oracle will soon roll out Java 12 in March 2019 and new releases
Java 11 is the second LTS release after Java 8. Since Java 11, Oracle JDK would no longer be free for commercial use. Java 10 was the last free Oracle JDK that could be downloaded. You’ll need to pay for more support. You can continue using it, but won’t get any patches/security updates. Oracle will not be providing free long-term support (LTS) for any single Java version since Java 11. While Oracle JDK is no longer free, you can always download the Open JDK builds from Oracle or other providers such as AdoptOpenJDK, Azul, IBM, Red Hat, etc. In my opinion, unless you are looking for Enterprise level usage with the appetite to pay for the support fees, you can use OpenJDK and upgrade them as and when necessary.
isBlank() – This instance method returns a Boolean value. Empty Strings and Strings with only white spaces are treated as blank. import java.util.*; public class Main { public static void main(String[] args) throws Exception { // Your code here! System.out.println(" ".isBlank()); //true String s = "r4r"; System.out.println(s.isBlank()); //false String s1 = ""; System.out.println(s1.isBlank()); //true } } lines() :- This method returns a stream of strings, which is a collection of all substrings split by lines. import java.util.stream.Collectors; public class Main { public static void main(String[] args) throws Exception { String str = "R4R CO IN"; System.out.println(str); System.out.println(str.lines().collect(Collectors.toList())); } } strip(), stripLeading(), stripTrailing() strip() – Removes the white space from both, beginning and the end of string. But we already have trim(). Then what’s the need of strip()? strip() is “Unicode-aware†evolution of trim(). When trim() was introduced, Unicode wasn’t evolved. Now, the new strip() removes all kinds of whitespaces leading and trailing(check the method Character.isWhitespace(c) to know if a unicode is whitespace or not) An example using the above three methods is given below: public class Main { public static void main(String[] args) throws Exception { // Your code here! String str = " R4R "; System.out.print("Start"); System.out.print(str.strip()); System.out.println("End"); System.out.print("Start"); System.out.print(str.stripLeading()); System.out.println("End"); System.out.print("Start"); System.out.print(str.stripTrailing()); System.out.println("End"); } } repeat(int) The repeat method simply repeats the string that many numbers of times as mentioned in the method in the form of an int. public class Main { public static void main(String[] args) throws Exception { // Your code here! String str = "R4R".repeat(2); System.out.println(str); } }
Some of the important Java 11 features are: Running Java File with single command New utility methods in String class Local-Variable Syntax for Lambda Parameters Nested Based Access Control JEP 321: HTTP Client Reading/Writing Strings to and from the Files JEP 328: Flight Recorder