Thursday, July 25, 2013

System Class - I



In Java default package(java.lang) System class is defined as final and cannot be instantiated. All its member fields and methods are static. System class t is an utility class. Facilities provided by the System class are standard input, standard output, and error output streams.  PrintStream.println and PrintStream.print display binary data as a stream of human-readable characters. The formatting is primitive.

Following are the fields for java.lang.System class:

    static PrintStream err -- This is the "standard" error output stream.
    static InputStream in -- This is the "standard" input stream.
    static PrintStream out -- This is the "standard" output stream.

out – is a member field declared as  static in System class and type is PrintStream.

println / print – prints the argument passed to the standard console. System.out.println will print on a new line where System.out.print will print and the same line.

printf - used to send formatted numerical output to the console. It uses  java.util.Formatter objects. It follows the printf() function in C.

Some Format Specifiers like %d use for Integer Data type and  %f is use for Floating point.


System.out.print()

//Output Statement - println()
    class Sys_Print
        {
            public static void main(String args[])
                {
                    int num1,num2,prod;
                    num1=50;
                    num2=45;
                    prod=num1*num2;
                    //Both the output will print in same line
                    System.out.print("Result  : ");
                    System.out.print("Product of "+num1+" and  "+num2+" = "+prod);
                }
        }


System.out.println()

//Output Statement - println()
    class Sys_Println
        {
            public static void main(String args[])
                {
                    int num1,num2;
                    double avg;
                    num1=50;
                    num2=45;
                    avg=(num1+num2)/2.0;
                    System.out.println("Average of "+num1+" and  "+num2+" = "+avg);
                }
        }


System.err

    public class Sys_Err
        {
            public static void main(String args[])
                {
                    System.err.println("There is nothing to do!");
                }
  
        }





Thursday, July 18, 2013

Java Note (Beginner) - Java


Introduction
Java is a programming language and environment invented by James Gosling and others in 1994. Java was originally named Oak and was developed as a part of the Green project at the Sun Company.
About JAVA
Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in the 1990s.
Java is influenced by C, C++ and borrowed some advanced features from some other languages. It is platform independent, you can “Write Once Run Anywhere” that means it can develop and run on any device equipped with Java Virtual Machine (JVM). This language is applicable in all kinds of operating systems including Linux, Windows, etc.
Procedure Oriented Programming
The procedure oriented programming (POP) focuses on creating and ordering procedures of the code keeping in mind to achieve a specific job. The key features of this kind of use procedures, sequencing of procedures and sharing global data.
Object Oriented Programming
A type of programming in which programmers define not only the data type of a data structure, but also the types of operations that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another. For example, objects can inherit characteristics from other objects.
One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added. A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.
To perform object-oriented programming, one needs an object-oriented programming language (OOP). Java, C++  is the object-oriented programming language.
JVM (Java Virtual Machine) – Program written in java are compiled into java byte code, which is then interpreted by a special java interpreter for any specific platform and this java interpreter is known as Java Virtual Machine.
Byte Code – is a machine instruction for a java processor chip called JVM. The byte code is independent of the computer system it has to run upon.
OOP’s Principle
Object Oriented programming follows the following principle also known as OOPs Principle.
Encapsulation - Conceals the exact details of how a particular class works from objects that use its code or send messages to it.  Encapsulation is achieved by specifying which classes may use the members of an object. The result is that each object exposes to any class a certain interface — those members accessible to that class.
Polymorphism  - Polymorphism is an object-oriented programming term. The ability to have methods with the same name, but different content, for related classes. The procedure to use is determined at run time by the class of the object. Function overloading, constructor overload is one of the example.
Abstraction  - Identifying the distinguishing characteristics of a class or object without having to process all the information about the class or object.. Represent essential features of a system without getting involvement with the complexity of the entire system.
InheritanceInheritance is where in some cases, a class will have "subclasses," more specialized versions of a class.  Subclasses inherit attributes and behaviors from their parent classes, and can introduce their own. A class can inherit methods and properties from another class. This is known as inheritance. The class that your subclass is inheriting from is known as the superclass.
Interface : An interface is a named collection of method definitions without implementations. An interface can also include constant declarations. Often interfaces are touted as an alternative to multiple class inheritance.
Binding : Associating a name with its referent. Specifically, locating the object named by a signature, putting it into its running state if it isn't already, and returning an interface pointer to it. Objects can be bound at run time also called late binding or dynamic binding or at compile time also called static binding. See also Moniker and Running state.

Characteristic, Structures and Miscellaneous
Class  - A class is a model that defines the variables and the methods that common to all objects of a certain kind. A class is an abstract type. A class defines the abstract characteristics of an object, including its attributes, fields or properties and also its behaviors or methods or features. For example, the class Dog would consist of quality shared by all dogs, for example breed, fur colour etc. In other way, a class is a collection of methods and properties. A class file also can contain inner private classes. A java source file is allowed only one public class per file. A class either can be standalone or be extended from another class (inheritance) or can implement one or more interfaces (interfaces). A subclass can access both protected and public members of the superclass.
Object  - An object means an instance. An object is a software bundle of variables related methods. An object is a particular instance of a class.  The set of values of the attributes of a particular object is called its state.
Instance - It’s an object-oriented programming term. An object created from a class definition. Unlike a class, which is just a definition, an instance actually exists as an object that can be used to perform tasks.
Modularity - The source code for an object can be written and maintained independently of the source code for other object and an object can be used easily by someone else in the system.
Comment - A comment is a remark from programmer to explain some aspect of the code to who is reading the source code. Comments can be anything including or excluding programming syntax as compiler ignore it.
a) Single line comments -  Comments followed the // symbols
b) Multiline Comments – The are used for comments spread over many line. They begin with /*  and end with */.
Type Casting - A type cast provides a method for explicit conversion of the type of an object in a specific situation. The compiler treats cast-expression as type type-name after a type cast has been made. Casts can be used to convert objects of any scalar type to or from any other scalar type. Explicit type casts are constrained by the same rules that determine the effects of implicit conversions.
Implicit conversion : Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:
   short a=2000;
   int b;
   b=a;
Explicit conversion : Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:
  double a=2000.566;
  int b;
  b = (int) a;   // c-like cast notation
statements consist of tokens, expressions, and other statements. A statement that forms a component of another statement is called the “body” of the enclosing statement. Each statement type given by the following syntax is discussed in this chapter.
Compound Statements (Blocks) - A compound statement consists of zero or more statements enclosed in curly braces ({ }). A compound statement can be used anywhere a statement is expected. Compound statements are commonly called “blocks.”
Multithreading - The ability of an operating system to execute different parts of a program, called threads, simultaneously. The programmer must carefully design the program in such a way that all the threads can run at the same time without interfering with each other.
Wrapper Classes - In order to convert from external numeric format to internal format, Java uses the parseInt() method of the Integer class, Double class and Float class. The method requires a standard Java string as parameter. The Integer class is sometimes called a wrapper class
Array - An array is a group of same typed variables that are referenced by a common name. Arrays can be any typed and one or more dimensions. A particular element can be addressed by array name and index of the array enclosed in third bracket ([]). Array can be declared with its initial values or can be defined with the size and can input the values latter. An array index start from 0 by default. Length of single dimension array can get using a function – array. length
int a[]={1,2,3,4};
double a[]=new double[10];
Method  - A method is an object's abilities. Methods or functions are the modules from which java program is built. Method can be declared with - access-specifier, modifier, type,   method-name(parameter list), where access specifer is optional. Methods also known as functions. access-specifier – private/ public/protected.
protected keyword is a modifier that can be used in the declaration of methods or variables. A protected variable or method is only visible within its class, within its subclasses, or within the class package.
private keyword is a modifier that can be used in the declaration of methods or variables. Using the private modifier in the declaration for either of these types hides the methods and variables so they cannot be directly referenced outside of the class they're declared in. One exception to this rule is that private methods or variables declared within a class can also be used by inner classes.
public keyword is a modifier that can be used in the declaration of classes and interfaces. The public keyword can also be used as a modifier in the declaration of methods and variables. Classes or interfaces declared as public are visible everywhere. Methods and variables declared as public are visible everywhere their corresponding classes are visible.
(Note that the protected, public, private  keyword cannot be used in the declaration of local variables.)
type – Type is compulsory for a method declaration. Type declaration indicates that what types of values going to be returned. void (no return) or   int / float / double / Boolean / char –(if a function return a value it not compulsory to accept a parameter form caller method).
Information hiding – An object has a public interface that other objects can communicate with it. The object can maintain private information and methods that can changed at any time without affecting the other objects that depend on it.
parameter list – are variables or objects that receive the value of argument.
actual parameter—the actual value that is passed into the method by a caller. Actual arguments (those supplied by the caller) are evaluated. Caller – sum(a, b)
formal parameter—the identifier used in a method to stand for the value that is passed into the method by a caller. Receiver – int sum(int x, int y)
Message passing  - "The process by which an object sends data to another object or asks the other object to invoke a method. Also known to some programming languages as interfacing
Function Call by value – When a simple type passed to a method, as a copy of the argument is being made and passed to the function is known as call by value, any changes made to the parameter inside the function do not affect the original. A functions parameter list also known as signature.
     void test()
          {
              int a=10,b=20;
              int s=sum(a, b);
          }
Function call by reference – When an object is passed as an argument to a method it is passed by reference. A reference to an argument is passed as parameter, the value of the argument is not passed. This method is called call by reference.
     class testing
          {
              int a, b;
              void test()
                   { 
                             a=10,b=20;
                             testing t=new testing();
                             int s=sum(t);
                        }
                   }
Pure function – Pure function or accessor methods return information to the caller about a state of an object without changing the state.
Impure function –  Pure function or mutator methods return information to the caller about a state of an object by changing the state.
Function overloading - In Java its possible to define two or more methods or functions within the same class can have same name, however their parameter declarations have to differ form one another its known as Functions overloading. Functions overloading is one of the ways where polymorphism principle implemented.
signature - A signature is a list that specifies a class constructor, an instance method, or a static method, thereby distinguishing it from other constructors, instance methods, or static methods. Two forms of signatures are accepted: simple and full. A simple signature is a single element list containing the name of the method or constructor.
Constructors - The central player in object initialization is the constructor. In Java, constructors are similar to methods, but they are not methods. Like a method, a constructor has a set of parameters and a body of code. Unlike methods, however, constructors have no return type. Like methods, you can give access specifiers to constructors, but unlike methods, constructors with public, protected, or package access are not inherited by subclasses.  If you don't define the any constructors, Java will generate a default no-argument constructor for you. 
When a new instance (object) of a class created using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables of an object. Constructors are similar to methods, but with a few important differences.
Differences between methods and constructors. 
1.     Constructor must have the same name as the class
2.     There is no return type given in a constructor signature (header). 
3.     There is no return statement in the body of the constructor.
4.     The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super).
5.     An access specifier can be use but Constructor can not be typed (int, float etc.).
There are three types of constructor
Default constructor -  A default constructor does not have any parameters. It is not necessary to create a default constructor, it is automatically created by the compiler. The default constructor initializes all instance variables to default value.  If you define any constructor for your class, no default constructor is automatically created.
Parameterize Constructor - A parameterize constructor which can take arguments (parameter) of any types are termed as parameterized constructors.
copy constructor – A copy constructor which can have a formal parameter that is the type of the class, which also can refer as object. It is used to create a copy of an existing object of the same class.
Example :
          class ComplexAdd
                   {
                             double re, im;
                             //Default Constructor
                             ComplexAdd()
                                      {
                                                re=im=0;
                                      }  
                             //Parameterize Constructor
                             ComplexAdd(double r, double m)
                                      {
                                                re = r;
                                                im = m;
                                      }
                             //Copy Constructor    
                             ComplexAdd(ComplexAdd CA)
                                      {
                                                re = CA.re;
                                                im = CA.im;
                                      }

Data Types, Literals and Identifier
Data Type - A variable is a symbolic name for a computer memory location, while declaring a variable the program must keep track of the type of data or information to be stored in the variable. The type in java is defined by the data type.  Primitive data types are those are not composed, it also known as fundamental data types. Following are the eight primitive data types which are supported by Java languages:
int - It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647. This data type is used for integer values. However for wider range of values use long.
byte - The byte data type is an 8-bit integer. It ranges from -128 to127 , byte can be used instead of int.
short -The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is used to save memory in array declaration.
long - The long data type is a 64-bit integer. It ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values.  
float - The float data type is a single-precision 32-bit  floating point. It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38. Use a float (instead of double) to save memory in large arrays.  
double -  This data type is a double-precision 64-bit floating point. It ranges from 4.94065645841246544e-324d to 1.79769313486231570e+308d . This data type is generally the default choice for decimal values. 
boolean - The boolean data type is 1-bit  and has only two values: true and false.
char - The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
Composite Data Types  - In addition to the elementary data types Java supplies, you can also assemble items of different types to create composite data types such as arrays, and classes. You can build composite data types from elementary types and from other composite types.
Identifiers & Literals
Constant or Literals – A data item does not change during execution of a program is called a constant or literals. Constant or literals can be numeric – Integer (int) type or fractional (float or double), character or string.
e. g. 200, “hello”, 45.0F, 444.4545, TRUE, FALSE
Identifiers or variables – Symbolic names used for various data items in programs known as identifiers. Identifiers also can be defined as user defined name given to memory boxed to store data or information.
Rules for naming identifiers.
  1. Must start with an alphabet.
  2. A numeric digit allowed.
  3. No space or symbols are allowed except an underscore.
  4. No java keyword can be use as identifiers.
Instance variable - Instance variables are any variables that are defined in a constructor function and that are copied into each object instance of that constructor. All object instances have their own copies of instance variables. The significance of an instance variable is that every object instantiated from that class contains its own copy of all instance variables.
global variable - A variable whose value can be accessed and modified by any statement in an application, and not merely within a single routine in which it is defined.  Variables declared just in side the class known as global variable.
     class testing
          {
              int a, b; //global variable
          }
Local variable - A variable that is accessible only within a function or procedure. Other procedures or functions cannot access this variable's data. Their lifetime is from entry to their definition to exit from their block / function. Use global variables to share data across many procedures and functions, or private variables to share data with the functions you call.
Scope and Lifetime of variables : It is common to find confusion between scope and lifetime - though they are in cases related, they are entirely different notions: lifetime is to do with a period of time during the execution of a program, scope is to do with which parts of a program text. In Java, lifetime is dynamic - you must execute the program (or do so in a thought experiment) in order to determine it. Scope is static - determinable at compile time, or by reading the program text. The lifetime of a variable is the interval of time for which the variable exists; i.e. the time from when it is created to when it is destroyed; duration, span, or extent are equivalent terms for the same thing.
Temporary variables  : Used in evaluation of an expression, e.g.  for(int i=0;i<10;i++)
Operators An operator is a symbol or letter, which makes the computer perform specific operation in a programming statement.
arithmetic operator - Operators that perform numeric calculations. In Java, the arithmetic operators are: + (addition), – (subtraction), * (multiplication), / (division) and % (modulus).
Relational operator - An operator that manipulates numeric and other values to produce a logical result. In Java, the relational operators are <, >,= =, <=, >=, and !=.
unary operator - The unary assignment operators, use two operand instead of one, for the increment (++) and decrement (– –) operators. Its also call increment/decrement operator. a++, a--, a+=10.
Ternary Operator – Can be used to replace certain of if – else-if statement. Its require three operands to work on. It represent by the ? and : symbols. Expression1?Expression2:Expression3
e.g. tax = salary>10000?salary*0.05 : 0; (if variable salary stored more than 10000 then tax variable will calculated 5% of salary otherwise tax will be).
logical operator - An operator that produces a logical result (true or false); sometimes called a Boolean operator. The logical operators in Java  are used for expression grouping, NOT or ! (negation), AND (Creates a Boolean behavior that represents the logical AND of the given behaviors. The behavior's value is true when both b1 and b2 are true; otherwise, it is false, OR (Creates a Boolean behavior that represents the logical OR of the given behaviors. The behavior's value is true when either b1 or b2 are true; otherwise it is false).
Binary Operator (Bitwise Operators) – This operator do the binary operations between two or more variables. Also known as bits operator. The bitwise operators perform bitwise-AND (&), bitwise-exclusive-OR (^), and bitwise-inclusive-OR (|) operations. E.g. 101 & 100 = 100 (Multiplication). 101 ! 100 = 101 (Addition). 101 ^  100 = 001(If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0). Right shift >> Left shift << (The value of a right-shift expression e1 >> e2 is e1 / 2e2, and the value of a left-shift expression e1 << e2 is e1 * 2e2).


JAVA Keywords
Keyword – Java reserved words that convey meaning to the computer. Used to write programming syntax. A programming syntax or statement should have at least one keyword. e. g. class, int, if, for.
The static keyword is used as a modifier for methods and variables. When the static keyword appears in a method or variable declaration, it means that there will be only one copy of the method or variable that each class object may reference, regardless of the number of instances of the containing class that are created.
A variable that is declared with the keyword final value can not be updated. This is handy for setting up constants. Constants are usually written in all uppercase. The final keyword can also be used with a method to keep a extended subclass from overriding the method.
Example:  private final int counter = 5;
If – else if – else - The if keyword is used to execute a statement or block of statements when its associated expression evaluates to true. An if statement may also have an alternative else if  or else clause. If the expression defined by the if statement evaluates to false, then control transfers to the statement (or block of statements) following the else if or else  keyword. If the expression defined by the if statement evaluates to true, then control transfers to the first statement following the if keyword. Multiple conditional expression can be written in if or else if statement separated by logical operator but there is no expression written in else.
if ( num < 1000 ) //when num is below 1000
            t=0;
  else if ( num<5000) // When num is equal or over 1000 but below 5000
       t=100;
else   t=200;       // When num is equal or over 5000

switch - The switch keyword is used along with the keyword case, and sometimes the keyword default, to create a conditional statement. In a switch statement, the switch keyword is followed by an expression within parentheses. Once the expression has been evaluated, its value is compared against the label following each case statement within the switch statement body. When a label has the same value, the lines following that case statement are executed. An optional default label is included within the body of a switch statement when there is no guarantee that the labels provided by each case statement are the only values the switch expression may evaluate to.
switch ( someExpression )
          {
                   case 1  :   System.out.print(“Switch-case”);  break;
                   default : System.out.print(“Not a Value”);
           }
The break keyword is also, at times, used within the body of a switch statement. Once the lines following a case statement have executed, the break statement is included to jump over the remaining body of the switch condition. Without a break statement, subsequent case statements would continue being evaluated, and eventually the default statement, if one were included, would execute.
Difference between switch-case and if-else if-else
switch-case
  1. switch can only check of equality
  2. switch only looks for match between the values of the expression with one of its case constant values. No two case constant can have identical values. Use of switch is more convenient than multiple nested if.
  3. When the case constant match with criteria given computer start from that point continue performing each case even its not satisfied the condition, so its required jump statement like break to jump from the table. Thus its run faster than if construct.
  4. In switch-case no floating point constant allowed, only integer and character allowed.
if-else-if-else
  1. if can evaluate any type
  2. if-else statement uses series of expression involving unrelated variables.
  3. No jump statement can be given for if statement. It check each condition even after it’s found its match, so it’s slower than switch-case.
  4. In if-else-if-else floating point constant can be used as a condition.
for - The for keyword is used to create a loop construct. An initialization section, an expression section, and an update section immediately follow the keyword. A semicolon separates each section, and all appear together within at least one set of parentheses. The initialization section allows the programmer to declare one or more local loop variables with initial values. The expression or final value section contains an expression that is evaluated to determine whether the loop should continue or how long it should continue. A true result allows the loop to continue; a false result allows control to transfer to the statement following the loop body. The update section allows to increment loop counters or perform other updates. Typically, the update section is used to increment or decrement whatever loop counters the programmer defines.
for ( int i = 0; i < 10; i++ )
while - The while keyword is used to create a loop construct. In a while loop, the expression in parentheses immediately following the keyword is evaluated, and if the result is true, the statements appearing within the loop body are executed. If multiple statements make up the body of the loop, they must be enclosed with curly braces. Once the loop body has executed, control transfers back to the top of the loop where the test is performed again, and the execution of the loop body is repeated until the value of the expression evaluates to false.  While is a entry centered loop as it check the condition and then perform the body.
while ( i < 10 )
          {   
                   System.out.println("Printing in loop");
                }
do-while - The do keyword is used as part of a do/while loop. Unlike the other, more commonly used loop constructs, a do/while loop expression is evaluated only after the block of code within its body has been executed. Thus, you are ensured that the code within the loop body is executed at least once, even if the expression tested causes the loop to end. .  Do-while is an exit centered loop as it does not check any condition but perform the body once and then check the condition. A semicolon is required after the condition (while) in a do/while loop.
          do 
                    {     
                   System.out.println("Printing at least once");
                    } while ( i <= 10 );
while – do-while Difference
while
  1. while is entry centered loop.
  2. while check its condition and if satisfied then it performed the body else it comes out of the loop statement and proceeds further.
do-while
  1. do-while is a exit centered loop.
  2. do-while, start with do and does not check any condition when computer performed the loop body first time, but check the condition at the below, which given in while, so even condition is not satisfied.
Jump Statement – Jump statement used to transfer control to another part of the program. break, continue worked as jump statement in java.
break - statement used to terminate a sequence in switch statement. Also exit a loop depend on programmer wish.
while(a<10)
          {
                   if(a==5) break;
          }
continue – can be used only in loop to terminate that particular process and transfer control to the loop conditional expression.
while(a<10)
          {
                   if(a==5) continue;
          }
break and continue Difference
break can be used a jump statement in any type of loops and switch-case.
break jump directly out of the body of the loop or switch-case statement and follow the next statement onwards.
continue can be used in loop but not in switch-case

continue transfer control to conditional expression not quite the loop.
new -  The new keyword is used as an operator for creating a new object or array. The new operator can be used to allocate dimensional arrays for any numeric or object type. Once an array has adequate space allocated, all the elements of the array are initialized to a default value, and it is then up to the programmer to supply values other than the defaults. Using the new keyword to create an array typically looks like this:
int array[] = new int[10];
When new is used to create an object, it first creates an instance of the specified class, then initializes all of the instance variables to their default values, and last invokes the appropriate constructor for the class, depending on the arguments provided in the argument list. Using the new keyword to create a class object typically looks like this:
ClassTest ct=new ClassTest();
this - Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class. The keyword this may be used only in the body of an instance method or constructor, or in the initializes of an instance variable of a class. If it appears anywhere else, a error will occur. e.g.
     class test
          {
               int a;
              test(int a)                     //Parameterize Constructor
                   {
                        this.a=a;
                   }
          }
super(). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the superclass, there is no need to make a call to it because it will be supplied automatically.
System class - The System class provides access to the native operating system's environment through the use of static methods. The System class also provides very basic IO streams for console read, write and error operations. System.in.read() reads a keystroke and returns an integer value. System.out.println(string) displays a string to the current output device.
escape sequence
         An escape sequence is a series of characters that represents a special character
         An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way
\n
newline
\t
Tab
\b
Backspace
\f
form feed
\r
Return
\"
"   (double quote)
\'
'    (single quote)
\\
\    (back slash)
The package keyword is used by Java to specify which package the code in the file is located in. Java code that is part of a particular package has access to all classes in the package, and all non-private methods and variables in those classes. E. g. java.lang (is a package name), java.lang.Math (here Math is a class and when we use a function of these class like Math.pow(), pow() is a method of class Math from package java.lang. We can create our own package and can import to a program in need.
IO package - The program uses various classes (such as BufferedReader and InputStreamReader) that are defined in the java.io package. It is, thus, necessary to import this package to use these classes.
Exceptions - One of the important characteristics of any program designed to be used there  are likely to be a mistakes while entering data into the program. The professional must attempt to detect or catch user input errors. The Java try/catch mechanism is a very good way of doing this. The statement throws IOException also does the same purpose. Specific types of errors can be handled by specific type of exception.
Java have two types of exceptions, checked and unchecked. where Exception which requires being catches and handled during compile time and unchecked exception catches during runtime.
Some example of Checked and Unchecked Exception
Exception
Reason
ArrayIndexOutOfBoundsException
When Array index is out of bounds
ArrayStoreException
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
ArithmeticException
Throws an Arithmetic error, such as divide-by-zero.
ClassCastException
attempted to cast an object to a subclass of which it is not an instance.
IllegalArgumentException
Illegal argument used while invoking a method.
IllegalThreadStateException
Requested operation not compatible with current thread state.
IndexOutOfBoundsException
Some type of index is out-of-bounds.
NegativeArraySizeException
Array created with a negative size.
NullPointerException
Invalid use of a null reference.
NumberFormatException
Invalid conversion of a string to a numeric format.
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
Following is the list of Java Checked Exceptions Defined in java.lang.
Exception
Reason
ClassNotFoundException
Class not found.
CloneNotSupportedException
When attempted to clone an object but the does not implement the Cloneable interface.
InterruptedException
One thread has been interrupted by another thread.
NoSuchFieldException
A requested field does not exist.
NoSuchMethodException
A requested method does not exist.


finally() - When a value is thrown from the try statement and the try has one or more catch  that catches it and transfer the control to the first such catch clause. However, the finally block always executes when the try block exits and even there is no exception is thrown.
BufferedReader - Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
InputStreamReader - is a bridge from byte streams to character streams: It reads bytes and translates them into characters according to a specified character encoding. The encoding that it uses may be specified by name, or the platform's default encoding may be accepted.
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader; for example,
BufferedReader br    = new BufferedReader(new InputStreamReader(System.in));
readLine() method belongs to the class BufferedReader and accept a data stream from input device as a form of String. A BufferedReader object must be associated with an InputStreamReader which in turn must be associated with an InputStream object.
Example
BufferedReader br    = new BufferedReader(new InputStreamReader(System.in));
          System.out.println("Enter a Name : ");
          String name=br.readLine();
          System.out.println("Enter a age : ");
          int age =Integer.parseInt(br.readLine();
          System.out.println("Enter a Salary : ");
          double age =Double.parseDouble(br.readLine();
          System.out.println("Enter Male or Female  (M/F): ");
          char mf =(char)br.readLine().charAt(0);

FILE
What are Files?
Output of the programs that we had written are temporary so the results derived after running the programs are lost after execution.  Java allows data to be stored permanently in a data file with the help of an extensive set of library functions for handling these data files
Opening and Closing a Data file:
To store data in a file, the data needs to be transferred from the computer's memory to the data file in the storage media like the hard disk.  However the data that is output does not go directly to the disk when an output command is issued.  Instead it goes to a temporary storage area in memory called a buffer.  Even if the buffer is not full, the data in the buffer can be forcibly transferred to the file, if required. 
Example
FileWriter fr=new FileWriter("name.txt");
BufferedWriter br1=new BufferedWriter(fr);   // open a file “name.txt” for writing
FileReader fr=new FileReader("name.txt");
BufferedReader br=new BufferedReader(fr);   // open a file “name.txt” for Reading
Byte Streams : The package java.io provides two set of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the root of inheritance hierarchies handling reading and writing of bytes respectively.
Reader and Writer classes - Similar to the InputStream and OutputStream class hierarchies for reading and writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes for reading and writing characters.
Scanner class
read data from standard input device - The Scanner class is a class in java.util, which allows the user to read values of various types.  Read different type of values from either the keyboard or file without having to convert them from strings and determine if there are more values to be read.
separate the tokens - The Scanner class also looks for tokens in the input. A token is a series of characters that ends with what Java calls whitespace.  To read a line that has a series of values separated by blanks, the scanner will take each values as a separate token.
Used for File operationIn example below, if the file "emp.txt" is not found, a FileNotFoundException is thrown. This checked for exception, so "throws FileNotFoundException" can be used on the header of the method.
Scanner read = new Scanner(new FileReader("emp.txt"));
Example :
Reading Data from Keyboard :
          Scanner sc = new Scanner(System.in); 
          System.out.print("Enter your full name: "); 
          String name = sc.nextLine();                           // Read a Line
          System.out.print("Enter Designation: "); 
          String desi = sc.next();                                   // Read a Word
          System.out.print("Age : "); 
          int age = sc.nextInt();                                              // Read a Integer Value
          System.out.print("Enter Salary : "); 
          double sal = sc.nextDouble();                          // Read a double Value
For Separating the Tokens
           Scanner sc =  new Scanner("1, 2, 3, 4, 5, 6, 7, 8, 9, 10").useDelimiter(", "); 
          while (sc.hasNext())
            { 
               String num = sc.next(); 
               System.out.println(num);
                   }
PrintWriter -PrintWriter prints formatted representations of objects to a text-output stream. In other words, you can say it enables to write formatted data to a writer. It implements all of the print methods found in PrintStream and does not contain methods for writing bytes. For instance, writing int, long and other primitive data formatted as text.
Example
      PrintWriter PR=new PrintWriter(System.out,true);
      PR.println("Hello");
      double a=4.5e-7;
      int x=123;
      System.out.println(a);
      PR.println(a);
      PR.println("%1$"+x);
String and StringBuffer() - String is immutable that once the value assigned to object cannot be modified. Suppose if we want to perform concatenation another string object will be prepared and the value is going to assign for that object. In total we are having 2 objects
StringBuffer is Mutable we can change the value of the  object even the value is assigned to the object.
Example :
Assign the following
String st = "Hello";
StringBuffer st = new StringBuffer("Hello");
When we use the following statement :
st= st + "to Java World" - It will allocate a new memory space.
st.append("to Java World") - simply allocate a new memory space to only 2nd statement and add to link to previous name.
StringBuffer
StringBuffer - is mainly used for the dynamic string concatenation which enhances the performance. Some of its class members :
append() - This is the append() function used for the concatenate the string in string buffer. str1.append(str2)..
insert() - This is the insert() function used to insert any string or character at the specified position in the given string.
reverse() - This is the reverse() function used to reverse the string present in string buffer.
charAt() : This is the charAt() function which is used to get the character at the specified position of the given string.
length() - This is the length() function is used to finding the length of the buffered string.

StringTokenizer
StringTokenizer : The string tokenizer class allows an application to break a string into tokens. The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.
Example
StringTokenizer st = new StringTokenizer("this is a test");
       while (st.hasMoreTokens())
          {
                    System.out.println(st.nextToken());
          }
prints the following output:
     this
     is
     a
     test

String Functions – String class from package java.lang have some methods which can manipulate string literals.
String.length() – to find the length of a string value.
String.charAt(int) – extract a character from the said string from given position.
String1.equals(String2) – check equality between two string and return a Boolean value as result.
String1.equalsIgnorecase(String2) - check equality between two strings while ignoring he case difference and return a Boolean value as result.
String1.compareTo(String2) – Compare between two string( relevant to the ASCII values of each character), if both equal it return 0, if String1 is smaller than String2 then it will return -1 and if  String1 is bigger than String2 then it will return 1.
String.substring(int) – Extract all the string from given position until end.
String.substring(int,int) - Extract all the string from starting position up to left of end position.
String1.concat(String1) – Join String2 to the right of String1. This can be done by: String1=String1+ String2.
String.indexOf(char/string) - Returns the index within this string of the first occurrence of the specified character.
String.indexOf(char/string, int) - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
String.lastIndexof(char/String) - Returns the index within this string of the last occurrence of the specified character.
String.firstIndexof(char/String) - Returns the index within this string of the first occurrence of the specified character
String.startswith(String) -Tests if this string starts with the specified prefix.
String.endsWith(String) - Tests if this string ends with the specified suffix.
String.trim() - Removes white space from both ends of this string.
String.replace(char, char) - Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String.toLowerCase() / String.toUpperCase() - Converts this String to lowercase / Converts this String to upper case.
String.valueOf(String) - Returns a new Integer object initialized to the value of the specified e.g. String.String x="12";  int y=Integer.valueOf(x);
String.toCharArray() -Converts this string to a new character array.

Math Functions - The class Math from package java.lang contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
Math.abs(double) - Returns the absolute value of a double value.
Math.sqrt(double) - Returns the square root of a double value.
Math.pow(double, double) - Returns of value of the first argument raised to the power of the second argument.
Math.min(double, double) – Returns the smaller of two double values.
Math.max(double, double) – Returns the larger of two double values.
Math.sin(double) / Math.cos(double) / Math.tan(double) - Returns the trigonometric sine, cosine and tangent of an angle.
Math.exp(double) - Returns the exponential number e (i.e., 2.718...) raised to the power of a double value.
Math.ceil(double) - Returns the smallest  (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer. Math. ceil(12.5) = 13, Math.ceil(-12.5) =  -12
Math.floor(double) - Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer. Math.floor(12.5) = 12, Math.floor(-12.5) = -13.
Math.random(double) - Returns a random number between 0.0 and 1.0.
Math.round(double) - Returns the closest long to the argument.
Math.rint(double) - Returns the closest double value that is equal to a mathematical integer.. e.g. double d=56.678; will give 57.0 and double d=56.478 will give 56.0.