Core Java Programming Questions & Answers

Explore model answers categorized by subjects like Java, HTML, DBMS, and more.

Core Java Programming Questions & Answers

What is Reference variable?

Answer:
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.

What is public access?

Answer:
public Access is basically use for given a authority for the packages for accessing to a class .It is using of the public keyword.

What is Runtime exceptions?

Answer:
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.

What is Abstract class ?

Answer:
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 :

  1. It extends another abstract class
  2. 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.

What is abstract method ?

Answer:
An Abstract method is basically a method , which method is use : 

  1. For the deceleration. It\'s not contain the functional codes.
  2. An abstract method is to ensure that subclasses of this class will include an implementation of this method.
  3. Any concert class must implement all abstract methods it has inherited.which is class that is not abstract and therefore capable of being instantiated.

What is access modifier?

Answer:
Access Modifier is basically defined as :

  1. The only modifier that can be applied to local variables in final.
  2. A top level interface can have public and abstract as access modifier
  3. A top level class can have public, abstract and final as access modifiers. To make the class default do not specify any access modifier.
  4. The string class is a final class. Final classes can improve performance as the methods are expanded inline.
  5. All the methods of final class are also final.
  6. Transient keyword can only be applied to member variables and it makes those variable non-persistable while serializing the object.
  7. Java interfaces cannot have transient variables.
  8. 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.
  9. The only modifier that can be applied to local variables in final.

What is anonymous inner classes?

Answer:
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.

What do you know about API?

Answer:
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.

What is Array?

Answer:
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.

What is Automatic variables?

Answer:
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.

What is Base class?

Answer:
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.

What is blocked state?

Answer:
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. 

What are boolean primitives values?

Answer:
A primitive boolean value represents only the true or false.

Explain Call stack.

Answer:
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 .

What is Casting?

Answer:
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.

Primitive Instance Variables

Answer:
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

What is Character literals?

Answer:
Character literals are represented by a single character in single quotes.

What is Class?

Answer:
A char is a basically a datatype its have a 16-bit unsigned primitive data type that holds a single Unicode character.

What is Class methods?

Answer:
A Class method is similar like a static method, which may be accessed directly from a class, without instantiating the class first.

What is Class variable?

Answer:
Class variable is basically similar as static variable .its all property as like as static variable 

What is Collection?

Answer:
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 :
  1. HashMap
  2. ArrayList

What is Collection interface?

Answer:
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.

What is Constructor?

Answer:
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.

What is continue statement?

Answer:
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.

What is Deadlock?

Answer:
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 statement

Answer:
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.

What is Declaration?

Answer:
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.

What is default access?

Answer:
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.

What is derived class?

Answer:
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.

What is do-while loop?

Answer:
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.

Explain Encapsulation?

Answer:
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.

What is Exception?

Answer:
Exception has two common meanings in Java.

  1. An Exception is an object type.
  2. An exception is shorthand for exceptional condition,which is an occurrence that alters the normal flow of an application.

What is Exception handling?

Answer:
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.

Explain Extensibility?

Answer:
Extensibility is basically a type of condition. Its a term that describes a design or code that can easily be enhanced without being rewritten.

What is final class?

Answer:
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.

What is final method?

Answer:
final method is basically a method. 

The final keyword applied to a method prevents the method from being overridden by a subclass.

What is final variable?

Answer:
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.

What are finalizer?

Answer:
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 :
  1. performing whatever cleanup is appropriate to the object,
  2. 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.

What is floating-point literals?

Answer:
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.

What is floating-point numbers?

Answer:
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.

What is for loop?

Answer:
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
  1. the declaration
  2. initialization of variables
  3. The boolean test expression and the iteration expression.

Each of the sections are separated by a semicolon.

What is Garbage collection?

Answer:
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.

What is Guarded region?

Answer:
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.

What is HashMap class

Answer:
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.

What is Heap?

Answer:
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.

What is Hexadecimal literals?

Answer:
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.

What is Identifiers?

Answer:
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.

What is if statement?

Answer:
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.

What is import statement?

Answer:
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 :
  1. import statements do not make classes accessible;
  2. 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.

What is Inheritance?

Answer:
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.

What is Inner classes?

Answer:
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.

What is Instance?

Answer:
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.

What is Instance variable?

Answer:
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.

What is instanceof comparison operator?

Answer:
The instanceof comparison operator is basically a type of operator which is available for object variables.

The purpose of this operator is deafined as :
  1. To determine whether an object is of a given class or interface type 8 Glossary :
  2. This comparison may not be made on primitive types and will result in a compile time error if it is attempted.

What is interface?

Answer:
An Interface defines as :

  1. Group of methods, or a public interface.
  2. Its must be implemented by any class that implements the interface.
  3. An interface allows an object to be treated as a type declared by the interface implemented.

What is Iterator?

Answer:
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.

What is java source file?

Answer:
A File that contains computer instructions written in the Java programming language:

  1. A java source file must meet strict requirements.
  2. 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 (JVM)

Answer:
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       
  1. memory management,         
  2. network access,         
  3. 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.

What is javac?

Answer:
JAVAC basically stands for the java compiler program JAVAC. 

This Java compiler processes the source file to produce a bytecode file.

What is Keywords?

Answer:
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.

What is Local inner classes?

Answer:
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.

What is Local variable?

Answer:
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.

What is Members types in java?

Answer:
Members are defined as : 

  1. Elements of a class
  2. Including methods
  3. Variables
  4. Nested classes

What is Method?

Answer:
A Method is the basically a type of the source code its mainly use : 

  1. For the specific function has a name,
  2. May be passed parameters.
  3. Its also may return a result.
  4. Methods are found only with in classes.

What is modifier?

Answer:
A modifier is basically a type of keyword, It is basically a modifies a different  type of elements : 

  1. class
  2. method
  3. variable declaration

What is notify() method?

Answer:
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.

What is Object?

Answer:
Object is basically blue print of a class at a runtime. It means Once the class is instantiated it becomes an object 

What is Overloaded methods?

Answer:
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.

What is Overridden methods?

Answer:
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.

What is package?

Answer:
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.

What parent class?

Answer:
A parent class is a class which is derived from the another class.

What is primitive literal?

Answer:
A primitive literal is basically represents a primitive data types , it is a type of source code.

What is private members?

Answer:
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.

What is primitives?

Answer:
primitives are basically as a fundamental concepts its mainly defined as a : 
  1. Instruction
  2. Operation
  3. Statement

They must be initialized before we attempt to use them or Its not necessarily onthe same line of code.

What is transient variables?

Answer:
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.

What is public members?

Answer:
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 .

What are shift operators?

Answer:
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.

<<
>>

What are SortedMap interface?

Answer:
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 :
  1. Here no duplicate keys and
  2. The objects themselves may be duplicated.
  3. The key may not be a null value. That\'s the main difference.

What is Source file?

Answer:
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.

What is stack trace?

Answer:
If we could print out the state of the call stack at any given time, We would reduce a stack trace.

What is static nested classes?

Answer:
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 : 
  1. Its classes are defined as within the scope of another class, Which name is like enclosing class.
  2. Its have not any implicit references to instances of the enclosing class.
  3. It can access only static members and methods of the enclosing class.
  4. These classes are often used to implement small helper classes such as iterators.

What is static methods?

Answer:
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.

What is static variable?

Answer:
static variable is a similar like a class variable. Its defined as :

  1. Its similar as static method.
  2. Its accessed from a class directly, even though the class has not been instantiated.
  3. Its value will be the same in every instance of the class.

What is string literal?

Answer:
A string literal is a source code representation of a value of a string.

What is String objects?

Answer:
String object basically defined as :

Its provides string manipulation capabilities.
  1. The String class is final.
  2. Its may not be subclassed.

What is super class?

Answer:
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. 

What is switch statement?

Answer:
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 : 

  1. byte
  2. short
  3. char
  4. 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.

What is Synchronized methods?

Answer:
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.

What do think about Thread?

Answer:
Thread is basically defined as : 

  1. Its an independent line of execution.
  2. Its a type of mini program .
  3. Multiple line of execution method is also used in multiple threads.
  4. Its executes instructions, any variables that are declares within the method, Its also called automatic variables.
  5. 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.

What is Time-slicing?

Answer:
time slicing is basically a technique ,Its use for the thread execution, I this scheme for scheduling thread execution.

What is variable access?

Answer:
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.

What is Visibility?

Answer:
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 :

  1. public
  2. protected
  3. package
  4. default

Writing Code Using if statement

Answer:
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;

legal arguments for if Statements

Answer:
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\");
}

Writing Code Using Switch Statement

Answer:
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\");
}

Legal Arguments to switch and case

Answer:
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 statement final 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;
}

default, break, and fall-through in switch blocks

Answer:
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;
}
}

The Default Case

Answer:
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 Keywords

Answer:
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.

Error Handling

Answer:
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

Answer:
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.

Primitives

Answer:
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.

Class, Method, and Variable Modifiers

Answer:
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.

Flow Control

Answer:
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.

void Return Type Keyword

Answer:
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.

Literals and Ranges of All Primitive Data Types

Answer:
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.

Range of Primitive Types

Answer:
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

Literal Values for All Primitive Types

Answer:
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

Answer:
Integer Literals are basically we have three ways for representation :

  1. Decimal (base 10)
  2. Octal (base 8)
  3. 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 Literals

Answer:
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 Literals

Answer:
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);
}
}

Hexadecimal Literals

Answer:
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

Answer:
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

Answer:
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

Answer:
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

Literal Values for Strings

Answer:
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 \"

Array

Answer:
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 :

  1. How to make an array reference variable (declare)
  2. How to make an array object (construct)
  3. How to populate the array with elements (initialize)

Declaring an Array

Answer:
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[];

Constructing an Array

Answer:
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

Answer:
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 .

Initializing Elements in a Loop

Answer:
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.

Declaring, Constructing, and Initializing on One Line

Answer:
We have a two diff array-specific syntax shortcuts:
  1. Initialize
  2. Construct

We can do the both steps in the single statements .Firstly use to declare,create,and initialize in one statement :
  1. int x = 9;
  2. int[] dots = {3,6,x,8};

Line 2 is preceding code , it does four things :

  1. Declares an int array reference variable named dots.
  2. Creates an int array with a length of four (four elements).
  3. Populates the elements with the values 3, 6, 9, and 8.
  4. 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;

Constructing and Initializing an Anonymous Array

Answer:
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};




Arrays of Primitives

Answer:
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

Arrays of Object References

Answer:
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
}
}

Array Reference Assignments for One-Dimensional Arrays

Answer:
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 

Array Reference Assignments for Multidimensional Arrays

Answer:
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

Using a Variable or Array Element That Is Uninitialized and Unassigned

Answer:
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 .

  1. Instance variable
  2. 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.
        

Object Reference Instance Variables

Answer:
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.

Array Instance Variables

Answer:
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 Primitives

Answer:
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);
}
}

Local Objects

Answer:
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

Answer:
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 Arguments to Main

Answer:
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 .

  1. The length of the args array will always be equal to the number of command-line arguments.
  2. args.length is one, meaning there is one element in the array, and it is at index zero.
  3. 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\");
}
}

Declarations and Modifiers

Answer:
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 : 
  1. Public
  2. Final
  3. Static
  4. 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.

Class Declarations and Modifiers

Answer:
When we would like to declare the class and modifiers it then we use nested or inner class . some rules are there : 

  1. each source code file have a one public class only.
  2. file name and class name should be same .
  3. package should be first line in the source code if class is a part of package .
  4. import and package statements apply to all classes within a source code file.

Modifiers fall into two categories :
  1. Access modifiers: public, protected, private
  2. Non-access modifiers (including strictfp, final, and abstract.

Class Access

Answer:
When one class access to the another class , It means first class can do one of three things : 
  1. Create an instance of class B
  2. Extend class B (in other words, become a subclass of class B).
  3. Access certain methods and variables within class B, depending on the access control of those methods and variables.

Default Access

Answer:
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.

Public Access

Answer:
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 {
}

Other (Nonaccess) Class Modifiers

Answer:
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 Classes

Answer:
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 Classes

Answer:
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

Creating an Abstract Superclass and Concrete Subclass

Answer:
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.

Method and Variable Declarations and Modifiers.

Answer:
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

Answer:
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 :
  1. public
  2. protected
  3. default
  4. 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

Answer:
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

Answer:
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
}

Local Variables and Access Modifiers

Answer:
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


Nonaccess Member Modifiers

Answer:
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 : 
  1. transient
  2. synchronized
  3. native
  4. strictfp

But preferably we are using static.in this function first at modifiers applied to methods, we are using modifiers applied to instance variable.

Final Methods

Answer:
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.\");
}
}

Final Arguments

Answer:
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 Methods

Answer:
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.

Native Methods

Answer:
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

Answer:
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

Answer:
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 Operators

Answer:
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.

Properties of main()

Answer:
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.


java.lang.Runnable

Answer:
Its a interface , which is single method for the implement :
                  public void run {}.

Primitive Assignments

Answer:
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;
^

Assigning Floating-Point Numbers

Answer:
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;

Assigning a Literal That Is Too Large for the Variable

Answer:
 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 precision

found : 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 to

byte 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.

Assigning One Primitive Variable to Another Primitive Variable

Answer:
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

Reference Variable Assignments

Answer:
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 :

  1. Makes a reference variable named b, of type Button.
  2. Creates a new Button object on the heap.
  3. 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
}
}

Assigning One Reference Variable to Another

Answer:
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 Operators

Answer:
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 :

  1. > greater than
  2. >= greater than or equal to
  3. < less than
  4. <= less than or equal to

instanceof Comparison

Answer:
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 Operators

Answer:
equality is basically use for the tested operators are equal or not : 

  1. == equals (also known as \"equal to\")
  2. != 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 :
  1. Numbers
  2. Characters
  3. Boolean primitives
  4. Object reference variables

Equality for Primitives

Answer:
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
              

Equality for Reference Variables

Answer:
We already know about two reference variables can refer to the same object, we have a example 

Button 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

Arithmetic Operators

Answer:
We know that the basic operators : 

  1. + addition
  2. - subtraction
  3. × multiplication
  4. / 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.

String concentration Operator

Answer:
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);

Increment and Decrement

Answer:
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 (--) : 

  1. ++ increment (prefix and postfix)
  2. -- 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

Shift Operators

Answer:
The following are shift operators:
  1. >> right shift
  2. << left shift
  3.  >>> unsigned right shift (also called zero-filled right shift)
         

Conditional Operator

Answer:
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);
}
}

Bitwise Operators

Answer:
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:
  1. && & AND
  2. | inclusive OR
  3. ^ exclusive OR

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.

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

Bitwise Complement Operator

Answer:
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

Primitive Casting

Answer:
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

Casting Primitives

Answer:
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;

Logical Operators

Answer:
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 : 
  1. &
  2. |
  3. && short-circuit AND
  4. || short-circuit OR

Short-Circuit Logical Operators

Answer:
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

Logical Operators (not Short-Circuit)

Answer:
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.

Passing Variables into Methods

Answer:
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.

Passing Object Reference Variables

Answer:
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

Does Java Use Pass-By-Value Semantics?

Answer:
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();
}

Passing Primitive Variables

Answer:
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
        

creating a switch-case statement.

Answer:
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 : 
  1. Make sure a char variable is declared before the switch statement.
  2. Each case statement should be followed by a break.
  3. The default value can be located at the end, middle, or top.

Writing code using loops.

Answer:
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 :
  1. while,
  2. do-while
  3. for

Using while loops

Answer:
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

Using do-while Loops

Answer:
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.

Using for Loops

Answer:
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 : 
  1. Declaration and initialization of variables.
  2. The boolean expression (conditional test)
  3. The iteration expression

Declaration and Initialization

Answer:
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);

Conditional (boolean) Expression

Answer:
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.

Iteration Expression

Answer:
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

for Loop Issues

Answer:
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.
-------------------------------------------------

Using break and continue in for Loops

Answer:
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
}

Unlabeled Statements

Answer:
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 statement

while (!EOF) {
//read a field from a file
if (there was a problem) {
//move to the next field in the file
continue;
}
}

Labeled Statements

Answer:
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

Creating a Labeled while Loop

Answer:
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.

  1. The outer label should appear just before the while loop begins. It does not matter if it is on the same line or not.
  2. Make sure age is declared outside of the while loop.

Handling Exceptions

Answer:
Exception handling is basically use for the proper code and declare method and overriding methods that throw exceptions.

Catching an Exception Using try and catch

Answer:
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.

Using finally

Answer:
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) { }

Propagating Uncaught Exceptions

Answer:
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.

Propagating and Catching an Exception

Answer:
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 :
  1. Create an enclosing class called Propagate and a main() method, which will remain empty for now.
  2. Create a method called reverse(). It takes an argument of a string and returns a String.
  3. 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.
  4. 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.

Defining Exceptions

Answer:
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.

Exception Hierarchy

Answer:
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().

Handling an Entire Class Hierarchy of Exceptions

Answer:
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

Answer:
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.

Exception Declaration and the Public Interface

Answer:
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 the Same Exception

Answer:
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
}
}

Creating an Exception

Answer:
 We will call it BadFoodException. 
  1. Create an enclosing class called MyException and a main() method, which will remain empty for now.
  2. 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.
  3. 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,

Working with the Assertion Mechanism

Answer:
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.

Assertions Overview

Answer:
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\");
}

Assertion Expression Rules

Answer:
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

Enabling Assertions

Answer:
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;
--------------------------------------------------

Compiling with Assertions

Answer:
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!

Compiling Assertion-Aware Code

Answer:
If we \'were using this keyword then we must explicitly enable assertion awareness at compile time.

Compiling with Code That Uses Assert as an Identifier

Answer:
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.

Running with Assertions

Answer:
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.

Enabling Assertions at Runtime

Answer:
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

Disabling Assertions at Runtime

Answer:
We must also know the command-line switches for disabling assertions.
java -da com.geeksanonymous.TestClass
or
java -disableassertions com.geeksanonymous.TestClass

Selective Enabling and Disabling

Answer:
The command-line switches to enable and disable assertions can be used in various ways :
  1. With no arguments
  2. With a package name
  3. 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
--------------------------------------------------


Using Assertions Appropriately

Answer:
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. 

Do not use assertions to validate arguments to a public method.

Answer:
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.

Do use assertions to validate arguments to a private method.

Answer:
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.

Do not use assertions to validate command-line arguments.

Answer:
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.

Do use assertions, even in public methods, to check for cases that you know are never, ever supposed to happen

Answer:
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!
}

Do not use assert expressions that can cause side effects!

Answer:
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!

Benefits of Encapsulation

Answer:
Two benefit are there for the Encapsulation : 
  1. flexibility
  2. 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.

IS-A Relationships

Answer:
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:
  1. Vehicle is the superclass of Car.
  2. Car is the subclass of Vehicle.
  3. Car is the superclass of Subaru.
  4. Subaru is the subclass of Vehicle.
  5. Car inherits from Vehicle.
  6. Subaru inherits from Car.
  7. Subaru inherits from Vehicle.
  8. Subaru is derived from Car.
  9. Car is derived from Vehicle.
  10. Subaru is derived from Vehicle.
  11. Subaru is a subtype of Car.
  12. Subaru is a subtype of Vehicle.

Returning to our IS-A relationship, the following statements are true :
  1. Car extends Vehicle means Car IS-A Vehicle.
  2. Subaru extends Car means Subaru IS-A Car.

HAS-A Relationship

Answer:
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.

Overridden Methods

Answer:
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 :
  1. The argument list must exactly match that of the overridden method.
  2. The return type must exactly match that of the overridden method.
  3. The access level must not be more restrictive than that of the overridden method.
  4. The access level can be less restrictive than that of the overridden method.
  5. 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.
  6. 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. 
  7. Bottom line: An overriding method doesn\'t have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
  8. We cannot override a method marked final.

Invoking a Superclass Version of an Overridden Method

Answer:
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 Methods

Answer:
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 :
  1. Overloaded methods must change the argument list.
  2. Overloaded methods can change the return type.
  3. Overloaded methods can change the access modifier.
  4. Overloaded methods can declare new or broader checked exceptions.
  5. A method can be overloaded in the same class or in a subclass

Give the list of Illegal Override Code

Answer:

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.
--------------------------------------------------

Legal Overloads

Answer:
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 { }

Invoking Overloaded Methods

Answer:
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?
}
}

Polymorphism in Overloaded and Overridden Methods

Answer:
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);
}
}

Give the list of Method Invocation Code

Answer:
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.
---------------------------------------------------

Give the list of Overloaded Method

Answer:

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.
---------------------------------------------------

Constructor Basics

Answer:
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.

Constructor Chaining

Answer:
Constructors are invoked at runtime when we say new on some class type as follows : 
Horse h = new Horse();

  1. But what really happens when we say new Horse() :
  2. Horse constructor is invoked.
  3. Animal constructor is invoked (Animal is the superclass of Horse).
  4. 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.
  5. Object instance variables are given their explicit values (if any).
  6. Object constructor completes.
  7. Animal instance variables are given their explicit values (if any).
  8. Animal constructor completes.
  9. Horse instance variables are given their explicit values (if any).
  10. Horse constructor completes.

Rules for Constructors

Answer:
Rules are there : 
  1. 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.)
  2. The constructor name must match the name of the class.
  3. Constructors must not have a return type.
  4. 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.
  5. If we don\'t type a constructor into our class code, a default constructor will be automatically generated by the compiler.
  6. The default constructor is always a no-arg constructor.
  7. 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
  8. 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 !
  9. Every constructor must have as its first statement either a call to an overloaded
  10. constructor (this()) or a call to the superclass constructor (super()).
  11. 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.
  12. A call to super() can be either a no-arg call or can include arguments passed to the super constructor.
  13. 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.

determine if a default constructor will be created.

Answer:
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() { }
}

What happens if the super constructor has arguments?

Answer:
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
}
}

Overloaded Constructors

Answer:
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.

Legal Return Types

Answer:
This objective covers two aspects of return types : 
  1. What we can declare as a return type, and
  2. 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.

Return Types on Overloaded Methods

Answer:
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;
}
}

Overriding and return types

Answer:
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.

returning a value

Answer:
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
}
}

Strings Are Immutable Objects

Answer:
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\";

Important Facts About Strings and Memory

Answer:
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.

Creating New Strings

Answer:
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

Important Methods in the String Class

Answer:
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\"

The StringBuffer Class

Answer:
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.

Important Methods in the StringBuffer Class

Answer:
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\"

Using the Math Class

Answer:
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

Methods of the java.lang.Math Class

Answer:
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();

abs()

Answer:
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)

ceil()

Answer:
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

floor()

Answer:
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

max()

Answer:
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)

min()

Answer:
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)

random()

Answer:
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( )

round()

Answer:
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)

sin()

Answer:
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)

cos()

Answer:
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)

tan()

Answer:
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)

sqrt()

Answer:
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)

toDegrees()

Answer:
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)

toRadians()

Answer:
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)

Give me a list of Static Math Methods

Answer:
The many methods are there : 
  1. double ceil ( double a )
  2. double floor ( double a )
  3. double random ( )
  4. double abs ( double a )
  5. float abs ( float a )
  6. int abs ( int a )
  7. long abs ( long a )
  8. double max ( double a, double b )
  9. float max ( float a, float b )
  10. int max ( int a, int b )
  11. long max (long a, long b )
  12. double min ( double a, double b )
  13. float min ( float a, float b )
  14. double sqrt ( double a )
  15. int min ( int a, int b )
  16. long min ( long a, long b )
  17. double toDegrees ( double angleInRadians )
  18. double toRadians ( double angleInDegrees )
  19. double tan ( double a )
  20. double sin ( double a )
  21. double cos ( double a )
  22. double sqrt ( double a )
  23. int round ( float a )
  24. long round ( double a )
                These are static methods .

Miscellaneous Math Class Facts

Answer:
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 edge

double 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\"

Using Wrapper Classes

Answer:
The wrapper classes in the Java API serve two primary purposes : 

  1. 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.

  2. 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.

An Overview of the Wrapper Classes

Answer:
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.

Creating Wrapper Objects

Answer:
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 Constructors

Answer:
The wrapper class xcept character provide constructors, two constructors are main which is flowing here :

  1. 1st that takes a primitive of the type being constructed.
  2. 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

Answer:
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

Using Wrapper Conversion Utilities: xxxValue()

Answer:
When we would like to convert the value of a wrapperd numeric to a primitive. 

Using Wrapper Conversion Utilities : parseXxx() and valueOf()

Answer:
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
  1. parseXxx() returns the named primitive.
  2. valueOf() returns a newly created wrapped object of the type that invoked the method.

toString()

Answer:
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"

toXxxString() (Binary, Hexadecimal, Octal)

Answer:
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\"

Using equals()

Answer:
equals() 
> java.lang.String
> java.lang.Boolean all wrappers
> java.lang.Object.

Comparing Variables : (==)

Answer:
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.

Comparing Objects

Answer:
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 equals() Method Revealed

Answer:
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.

Overriding hashCode() and equals()

Answer:
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

The toString() Method

Answer:
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);}
}

Overriding equals()

Answer:

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.

What It Means if we Don\'t Override equals()

Answer:

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.

Implementing an equals() Method

Answer:
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;
}
}
}

The equals() Contract

Answer:
Pulled straight from the Java docs, the equals() contract says : 
  1. It is reflexive
  2. It is symmetric
  3. it is transitive.
  4. It is consistent
  5. For any non null reference value.

Overriding hashCode()

Answer:
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

Answer:
Collections is basically a framework in the java programming language.The Collections Framework in the java.util package is loaded with interfaces and utilities.

Implementing hashCode()

Answer:
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.

The hashCode() Contract

Answer:
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.

So What Do we Do with a Collection?

Answer:
There are a few basic operations you will normally use with collections:

  1. Add objects to the collection.
  2. Remove objects from the collection.
  3. Find out if an object (or group of objects) is in the collection.
  4. Retrieve an object from the collection (without removing it).
  5. Iterate through the collection, looking at each element (object) one after another.

Key Interfaces and Classes of the Collections Framework

Answer:
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:

  1. Collection
  2. Set
  3. Sorted Set
  4. List
  5. Map
  6. 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.

Sorted

Answer:
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

Ordered

Answer:
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.

List

Answer:
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

Answer:
Arraylist is basically give us a fast iteration and fast random access.its a growable array .

Vector

Answer:
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.

LinkedList

Answer:
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.

Set

Answer:
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:

  1. Hash Set
  2. LinkedHashSet
  3. TreeSet

HashSet

Answer:
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.

LinkedHashSet

Answer:
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.

TreeSet

Answer:
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

Answer:
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.

HashMap

Answer:
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

Answer:
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.

LinkedHashMap

Answer:
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.

TreeMap

Answer:
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

Answer:
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.

Overview of Memory Management and Garbage Collection

Answer:
Memory management : .Java\'s garbage collector provides an automatic solution to memory management.

Overview of Java\'s Garbage Collector

Answer:
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.

When Does the Garbage Collector Run?

Answer:
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.

How Does the Garbage Collector Work?

Answer:
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.

Nulling a Reference

Answer:
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.

Reassigning a Reference Variable

Answer:
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.

Isolating a Reference

Answer:
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.

Forcing Garbage Collection

Answer:
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.

Cleaning Up Before Garbage Collection the finalize() Method

Answer:
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.

Tricky Little finalize() Golgotha\'s

Answer:
We have two concepts for the finalize() method  which is following here:
  1. For any given object, finalize() will be called only once by the garbage collector.
  2. 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

Answer:
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.

Coding a Regular Inner Class

Answer:
Regular is basically use for the inner class..
  1. static
  2. method local
  3. 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.

Instantiating an Inner Class

Answer:
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.

Instantiating an Inner Class from Within Code in the Outer Class

Answer:
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);
}
}

Creating an Inner Class Object from Outside the Outer Class Instance Code

Answer:
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();
}

Referencing the Inner or Outer Instance from Within the Inner Class

Answer:
  1. The keyword this can be used only from within instance code. In other words, not within static code.
  2. The this reference is a reference to the currently-executing object. In other words, the object whose reference was used to invoke the
  3. currently-running method.
  4. 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
}

Member Modifiers Applied to Inner Classes

Answer:
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 : 
  1. final
  2. abstract
  3. public
  4. private
  5. protected
  6. static
except static turns it into a top-level nested class rather than an inner class.

Method-Local Inner Classes

Answer:
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

What a Method-Local Inner Object Can and can\'t Do

Answer:
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

Anonymous Inner Classes

Answer:
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.

Plain Old Anonymous Inner Classes, Flavor One

Answer:
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 :
  1. here two classes are mentioned maggie and food.
  2. maggie has one method mag()
  3. Food has one instance variable, declared as type maggie.
  4. That\'s it for Food. Food has no methods.
           here most impotent thing is  :
Maggie reference variable refers not to an instance of Maggie, but to an instance of an anonymous subclass of Maggie.

Plain Old Anonymous Inner Classes, Flavor Two

Answer:
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\");
}
};
}

Argument-Defined Anonymous Inner Class

Answer:

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) { }
}

Static Nested Classes

Answer:
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 { }
}

Instantiating a Static Nested Class

Answer:
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
}
}

Defining, Instantiating, and Starting Threads

Answer:
for the writing code to define , its instantiate , and start for new threads we are using two threads which are following as :
  1. java.lang.Thread
  2. 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
             

Making a Thread

Answer:
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 :
  1. start()
  2. yield()
  3. sleep()
  4. run()

We can define and instantiate a thread in one of two ways :
Extend the java.lang.Thread class
Implement the Runnable interface

Defining a Thread

Answer:
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 :
  1. Extend the Thread class.
  2. 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\");
}
}

Instantiating a Thread

Answer:
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.

Starting a Thread

Answer:
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:
  1. A new thread of execution starts.
  2. The thread moves from the new state to the runnable state.
  3. When the thread gets a chance to execute, its target run() method will run.

Starting and Running More Than One Thread

Answer:
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

The Thread Scheduler

Answer:
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.

Methods from the java.lang.Thread Class

Answer:
We can see the some methods are follows the rules of influence thread scheduling, we can see in the following code

public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join()
public final void setPriority(int newPriority)

Methods from the java.lang.Object Class

Answer:
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 :

  1. public final void wait()
  2. public final void notify()
  3. public final void notifyAll()

The wait() method has three overloaded versions.which are following here  :
> new
> runnable
> dead

Thread States

Answer:
In the java programming language we have a 5 thread stages . in this list we can see all thread stages :
  1. new
  2. runnable
  3. running
  4. waiting/blocked/sleeping
  5. dead

Preventing Thread Execution

Answer:
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  :
  1. Sleeping
  2. Waiting
  3. Blocked because it needs an object\'s lock

Sleeping

Answer:
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) { }

Thread Priorities and Yield

Answer:
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:

  1. Pick a thread to run, and keep it there until it blocks or completes its run() method
  2. Time slice the threads in the pool to give everyone an equal opportunity to run.

Setting a Thread\'s Priority

Answer:
A thread gets a default priority that is the priority of the thread of execution that creates it. 

For example, in the code
public 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();

The join() Method

Answer:
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

Answer:
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.

Preventing the Account Overdraw

Answer:
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.

Synchronization and Locks

Answer:
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.

So What About Static Methods? Can They Be Synchronized?

Answer:
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.

Synchronizing a Block of Code

Answer:
About synchronized the block of code .here many steps for that :
 
  1. Create a class and extend the Thread class.
  2. Override the run() method of Thread. This is where the synchronized block of code will go.
  3. 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.
  4. The synchronized block of code will obtain a lock on the StringBuffer object from step 3.
  5. Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer.
  6. 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.

What Happens if a Thread Can\'t Get the Lock?

Answer:
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.

Thread Deadlock

Answer:
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 Interaction

Answer:
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:
  1. wait()
  2. notify()
  3. 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 :
  1. wait()
  2. notify()
  3. 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.

Using notifyAll() When Many Threads May Be Waiting

Answer:
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

Answer:
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 Thread State

Answer:
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.

Running Thread State

Answer:
In this state thread is now ruining state and also thread scheduler select it for there the running state.

Waiting/blocked/sleeping Running thread stage

Answer:
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.

Dead Thread State

Answer:
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 rules.

Answer:
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.

default access

Answer:
When a lass is in the default access then that time when we are declaration time we don\'t have an. 

public access

Answer:
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 classes

Answer:
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.

Abstract Classes

Answer:
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.

Creating an abstract super subclass concrete Subclass

Answer:
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{.......}


Declaring an Interface

Answer:
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.

Declaring Interface Constants

Answer:
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

final argument

Answer:
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.

synchronized method

Answer:
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.

native methods

Answer:
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

strictfp methods

Answer:
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.

Using the fragment below , complete the following code so its compiles . Note , we may not have a fill all of slots :

Answer:

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

Answer:
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 : 

  1. Instances variable are kept protected.
  2. Getter and setter methods mainly provide the access to instance variable.

Inheritance

Answer:
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

Answer:
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.

Reference variable Casting

Answer:
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.

Implementing an interface

Answer:
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

Answer:
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.,

Constructors and Instantiation

Answer:
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.

statics

Answer:
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 and Cohesion

Answer:
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 and heap

Answer:
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 and primitive Casting

Answer:
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

Answer:
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 : 
  1. static variables live basically as long as their class lives.
  2. instances variable live as long as their object lives.
  3. local variable live as long as their method is on the stack; however ,if their method invokes another method.they are temporarily unavailable.
  4. block variables live until the block completes.

Basic Assignments

Answer:
We have a some important basic assignments are thee which is mainly recognize there :
  1. Literals integers are implicitly int.
  2. Integer expression always result in the int-sized result never smaller.
  3. Here we know also that the Floating point numbers are implicitly doubles.
  4. Compound assignment perform an automatic cast.
  5. Reference variable holds the bits that are used to the refer to an object.

using a variable or array Element That Is Uninitialized and Unassigned.

Answer:
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.

passing variables into methods

Answer:
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 Declaration, construction and initialization

Answer:
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.

Initialization Blocks

Answer:
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.

Using Wrappers

Answer:
The wrapper classes correlated tot he primitive types.Its have a two main functions :
  1. Its wrap primitives so that they can be handled like objects.
  2. To provide utility methods for primitives.
    Wrappers are using most importance families method whch is three are there :
  3. xxxValue()
  4. parseXxx()
  5. valueof()

Advanced Overloading

Answer:
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.

Garbage Collection

Answer:
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 .

Relational operator

Answer:
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 :
  1. There are two equality operators : == and !=.
  2. Four types of things can be tested: number , characters,booleans,and reference variable.

Instance of Operator

Answer:
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.

Arithmetic Operator

Answer:
There are four primary math operator which called arithmetic operator :
  1. Add
  2. Substact
  3. multyply
  4. 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

Answer:
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/ Decrement Operator

Answer:
Increment operator or decrement operator basically suing the two operators this is called : 
  1. Prefix (-- or ++)
  2. 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.

Ternary Operator

Answer:
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 :

  1. returns the value after the ? if the expression is true.
  2. returns the value after the : if the expression is false.

Logical Operator

Answer:
Logical operator basically 6 are there which is following here : 
  1. &
  2. |
  3. ^
  4. !
  5. &&
  6. ||
 
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,