JAVA NOTES  

Posted by ROCKING GUY in

JAVA

What is Java? Why it is called Object Oriented?

Java is a computer language but with a difference. Java has adopted the best features of many existing languages such as C and C++ and added few new features to form a simple and easy to learn language. It has now emerged as the language of choice of the world, computing community due to its simplicity, portability and security. Java is used in almost all applications from simple home appliances control systems to compile space control statements. It has also revolutionised application development for intranet and the internet. 
Object oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of each module on demand. Java is a true object oriented language. All program codes and Java resides with an extensive set of classes, arranged in packages, that we can use in our programs by inheritance. The object model in Java is simple and easy to extend itself.

Explain Java. Explain the concept of Platform Independent.
(JAVA Virtual Machine)

 JVM stands for Java Virtual Machine. All language compilers translate source code into machine code for a specific computer. Java compiler also does the same thing. It provides an intermediate code known as BYTE CODE for a machine that does not exist. This machine is called Java Virtual Machine and resides only inside the computer’s memory.





The virtual machine code is not machine specific. The machine specific code (known as machine code) is generated by Java Interpreter by acting as intermediately between virtual machine and real machine as shown if fig. above.


Platform Independent
 Java is a platform independent language. Java programs can be easily moved from one computer system to another system anywhere and at any time. Changes and upgrades in operating system processes and system resources will not force any changes in the java programs. Therefore. Java has become a popular language for programming on internet which interconnects dif6ferent kinds of systems of world wide.


ByteCode:
Bytecode is the key that allows java to solve both security and portability problems. Bytecode is a highly optimisd set of instructions designed to be executed by java runtime system (i.e. JVM). In essence, JVM is an interpretor for Bytecode. As the Bytecode is highly optimized, the use of bytecode enables JVM to execute programs much faster than we expect.
Translating a java program into Bytecode makes it much easier to run a program in a wide variety of environments. Bytecode is also reffered to as Virtual Machine code.






Constants and Variables
A quantity, which may vary during a program execution, is called a variable.
A quantity whose value cannot be changed is called Constant.
e.g. in expression
c = a + b - 5;
In above expression a, b, c are variables and 5 is constant.

Rules for naming variables in JAVA
(i) A variable name is any combination of alphabets digits or underscore ( _ ). Some compilers allow variable names up to 40-characters in length.
(ii) The first character of the variable name must be an alphabet i.e. it must not be a digit.
(iii) There should not be any blank space or comma within variable name.
(iv) No special symbol other than ( _ ) underscore can be used within variable name e.g. ?,*,+,’ etc.
(v) It should not be a keyword.

Keywords:
Keywords are the words whose meaning has already been explained to the JAVA-Compiler. The keyword cannot be used as variable name because doing so will try to assign a new meaning to keyword, which is not allowed by the compiler. e.g. float, if, int, do, for, break, while, else, switch, class, private, public etc.

Tokens :
 Token is the smallest part of statement, it may be an operator, variable, constant, punctuation mark or keyword. E.g. the statement 
 if ( a >5)
Above statement has 6 tokens as 
if , ( , a , > , 5 , )

Identifiers :
 Identifiers refer to the names of variables, functions, arrays, classes etc. created by the programmer. Each language has its own rules for naming identifiers. The rules for naming identifiers in C / C++ has been given above with heading “Rules naming variables in JAVA”

Writing JAVA Program:
Each JAVA program defines a class. The name of class is same as that of name of .java file in which this source program is to be stored. For core java, there must exist a public function named “main”, receiving command-line-arguments as an array of String class. This member method will be executed when java program is executed. As every java program is definition of a class, therefore, during the execution an object of this class is automatically created and executed “main” method on that object. We cannot execute a java program without class which makes it “pure-object-oriented”. In C++, it supported the object-oriented techniques, but itself C++ was not a pure-object-oriented language because C++ used the procedure “main ( )” as startup method/function, which was not a member of any class. Therefore, it was a procedural language because the program starts from a procedure, now, objects can be declared and used within that procedure but the still it a procedure that invoked the code.
 In JAVA, a set of statements are written in a method of class, that are executed sequentially to accomplish the task.


Following rules are applicable on all JAVA statements
(i) Blank spaces may be inserted between two words/keywords to improve the readability of the statement. However no blank spaces are allowed within variable, constant or keywords.
(ii) Writing statements in Java language is case sensitive.
(iii) Any Java-Statement always ends with a semicolon
(iv) Remarks can be written using double backslashes ( // ) on the same line
Where ever // appears, whole line after that is ignored by the compiler
 If we want to add multi line remarks then we use /* ---------- */ to write remarks in between them
  e.g. /*…………………………………………………
  …………………………………………………
  …………………………………………………
  */


Types of Statements/instructions in JAVA
Now, let us see how constants, variables and expressions are combined together to form instructions
There are basically 4-types of instructions:
1. Type Declaration Instructions
2. Input / Output Instructions
3. Arithmetic and logical instructions (Expressions)

4. Control Instructions


Opertaors in JAVA
An operator is a symbol that specifies certain operation to be performed on data. The data on which operation is to be performed is/are called operand(s). operator specifies what operation is to be performed on data. There are following type of operators in JAVA.

1. Unary operators :
 Operators which operates on single data. i.e. operators which need only one operand to perform the operations e.g. ++, --
 ++ is also called increment operator and -- as decrement operator
 e.g. 
int a=5;
a++; // this statement will increment a by 1 i.e. add 1 to a i.e. a=a+1 
  System.out.println(“ ”+a); // this will display the value of a as 6

 Unary operator can be placed either before or after operand. 
When it is placed before operand then it may be called as pre-increment or pre-decrement.
When it is placed after operand then it may be called as post-increment or post-decrement.
It behaves differently in both cases

                                                                    int a=5;
 Pre-increment                                                                                     Post increment
  b = ++ a;                                                                                                    b = a++;

 First INCREMENT                                                                                       First USE
 Then USE                                                                                              Then INCREMENT

 System.out.println(b+” , “+a); // 6,6                                      System.out.println(b+” , “+a); // 5,6

2. Binary operators :
 Operators, which need two operands to operate, are called binary operators. These can be further categorized according to the type of operands they use or the result they produce
 (i) Arithmatic operators :
  +, - , * , / , %
 Above all operators can be used with int, char, float data types except % that cannot be used with float data type because it gives the remainder obtained by division between the operands. Arithmetic expression produces a numeric result.
 (ii) Relational operators :
  > , < , >= , <= . = =  
  These operators can work on any numeric / arithmetic expressions value as operands and 
Produce a result, which is logical value (true/false).
 (iii) Logical operators (AND , OR , NOT):
  && , || 
  these operators use logical values as operands, and result of && (AND) is True when both operands are True. Result of || (OR) is True any at least one operand is True.

 (iv) Bitwise logical operators:
  These operators are used to manipulate the bits levels of operands. Some of these operators are << (left shift), >> (right shift), & (bitwise AND), | (bitwise OR), >>>, <<<
3. Ternary Operaros:
 The operators which use 3 operands to operate on. E.g. ? :
  (test condition) ? (true-statement) : (false-statement);
 the operator above is also called conditional operator.


CONTROL STRUCTURES (Do yourself)

Conditional Control Structure

if statement:
The immediately next statement to if statement is bounded with the condition of if statement. This statement will be executed only if the condition is true or else it will be skipped and control is passed to next statement. It can be used with multiple (more than one) statements but these statements must be enclosed within curly brackets {}. 

if (condition)
   
statement1; //bounded with if statement, will execute only if the condition is True
statement a;
statement b;


ARRAY (LIST):

Array is a collection of homogeneous elements (elements of same data type) stored in continuous memory locations under one name. Each element of array can be accessed independently using its index number. This index number is sometimes also called subscript number and hence array elements are also called subscripted variables.
 
Declaration:
 int a[]=new int[10]; // 20 bytes will be reserved for A to store 10 integer values

  //  


 assigning value to an element
  a[3]=56; // element at index number 3 will contain value 57



 rray values can be initialised during declaration like
  int a[10]={5,8,4,5,9,3,2,1,5,7}; //
  or
  int a[]={2,5,8,4,6} // here length of array is automatically assumed to be 5


 Display array
  for(i=0; i<10; i++)
  System.out.println(“ “ + a[i]);

2-D ARRAY:

 

FUNCTIONS/METHOD of class

CLASS METHODS
INSTANCE METHODS

Function is a self-contained block of statements that perform a specific task. This task may be performed on a class object and class members may need to be modified. In other words, a function is a subprogram /subroutine which has all the properties of a program and is invoked whenever called. It must be called either with class name or object of class using DOT (.) operator.
It behaves like a child process/program and the program calling/invoking it is called parent of this child. After finishing the child program/process the control is returned back to the parent process. On the other hand, the parent process will be blocked and waiting for the child process to be finished, so that parent process may be continued after the return of control back to parent process who invoked this child process/function/subroutine.
JAVA also provide multithreading programming environment. With the help of Threads (class that provide multi threading implementations) we can create methods that executes simultaneously as different processes.
A function can have any name that is valid for a variable
A method/function is defined as 

Access-type return-type function-name (arg1, arg2, … , argn)
Access-type gives the visibility scope, it may be private, public or protected. Private methods of class can be used only within class or by other methods of class but cannot be used directly by class objects. Only public methods can be accessed outside the class by class objects.
Return-type represents the type of data that is returned by the function. The value returned by the function can be used where it will be called. If function does not return any value than keyword “void” can be use as return type, which may indicate that function will not return any value.

arg1, arg2, arg3, …. , argn are the arguments or parameters which are received by the function. This is also called massage passing. If function will not receive any arguments then ( ) may be kept empty.

Public void accept( )
Above declaration means that accept is the name of function which will not return any value and will mnot receive any value. Public indicates that it can be called by any object of this class, declared either outside or inside class.

Public void accept(int a,int b)
Above declarations means that function accept will not return any value but receive 2 int-type values and store them into local variables a and b respectively.
 Public fact(int n)
above declaration implies that function named fact will return an int-value and will receive an int-value which will be stores to variable named n.
 
Its not necessary that all functions receive or return values, function may or may not return value, function may or may not receive value(s).
 
RECURSION
 When a function calls itself with in its own body, the function is said to be recursive and technique is called recursion. There must be an approachable condition where recursive call must be stopped otherwise recursion may last infinitely, and every recursive call must approach towards that condition. The number of times function calls itself to approach that condition is called “Depth of Recursion”.

  Example: // to find factorial of number

int fact(int n)
{
int f;
if(n<=1)
  return(1);
f=n*fact(n-1);
return(f);
}

Example: // to find nth term of Fibonacci series

int fib(int n)
{
 if(n<2)
  return(n); 
 return(fib(n-2) + fib(n-1));
}
 
Garbage collection: 

 In Java objects are dynamically allocated by using new operator, how these objects can be destroyed? In C++, delete operator is provided to manually destroy dynamically allocated objects. If these objects are not destroyed and their memory is not de-allocated then memory occupied by them will be wasted. The memory space, which is allocated but is not referenced by any object and is supposed to be waste, is called garbage collection. In Java, there is no need to worry about such non-referenced memory space, it handles de-allocation automatically. When no reference to an object exists, that object is assumed to be no longer needed, and the memory occupied by that object can be reclaimed.



Static methods of class:
 Normally the methods of class can be called in conjunction with an object of this class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such members, static keyword is used before its declaration. When a member is declared static, it can be called without creation of any object of this class. We can declare both methods and variables to be static. 
 Instance variables declared as static acts as global variables for all the objects of class because when objects of class are declared, no copy of static members is created. All instances of the class share the same static variable.
Methods declared as static have several restrictions:
1. They can only call static methods
2. They can only access static data
3. They cannot refer to this or super is any way.
e.g.
class height
{
int feet,inch; 
static int c=0;
 
  height()
  {
 feet=0;
 inch=0;
 c++;
  }
 
finalize()
{
c--;
}
public static void showcount()
{
System.out.println(“counter is at “+c);
}
};

class testheight
{
public static void main()
{
height h=new height();
height q=new height();
height.showcount();
}
}


Final keyword:
 final keyword is provided in java to say “this cannot be changed”.
If data is declared as final then it cannot be changed. It tells the compiler that this piece of data is constant and will not ever change. Final variable must be initialized at the time of declaration.
If a method is declared as final then it cannot be overridden. It turns off dynamic binding i.e. it tells the compiler that dynamic binding is not necessary.
If a class is declared as final then it means that this class definition can never be changed and no subclasses can be defined from it. In other words it prevents inheritance and do not allow other classes to inherit final class. However, objects of final class may be created in other classes. In other words, final class cannot be subclassed.
Simply we can say that final indicates that class, variable or method is not changeable

e.g. final int max_pages=5;

OR 
  Final int max_pages;
  max_pages=5;  


finalize() method:
JAVA provides constructors for the initialization of class objects. Finalize method is used to destroy the object. Sometimes we want to execute a set of statements at the time when an object is being vanished or when an object loses its life/scope. This set of statements may be written in a special method named finalize(). Java run-time automatically frees up the memory resources used by the objects. But, the objects may hold other non-object resources such as file description or windows system fonts. The garbage collection cannot free these resources. In other words, to free these type of resources finalize() method is used and is also called destructor.

Super keyword:
Super keyword is used by subclasses constructors to invoke the constructor method of super class.
Use of super keyword subject to following conditions
- super may only be used within a subclass’s constructor mehod.
- The call to super class constructor must appear as the first statement within the subclass constructor.
- The parameters in the super class must match the order and type of the instance variable declared in super class.

Finally statement:
 Finally statement can be used to handle an exception htat is not caught by any of the previous catch statements. Finally statement can be used to handle any exception generated within try block. It may be added immediately after the try block or after the last catch block.
 When finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown. We can use it to perform certain necessary operations such as closing files and releasing system resources.


Constructors
 Constructor is one of the special type of methods which have the same name as that of class but with no-return-type. They cannot specify return-type, not even void. This is because it return the instance of class itself. Constructor enables an object to initialize itself when it is created. We can pass parameters to constructors and therefore sontructors can be overloaded.
CONTRUCTORS are of two types:
 1. Default constructor
 2. Parameterized constructor
1. Default constructor:
 constructor that do not receive any parameters are called default constructors. These type of constructors are used for default initialization of class objects.
2. Parameterized constructors:
 constructor that receive at least one parameter is called parameterized constructor. Mostly the initial values of object are passed to constructors so that object may be initialized with those values. By the technique of polymorphism, constructors can be designed to receive different number or type of parameters and hence can be overloaded.

Note : There may be many parameterized constructors but only one default constructor.

e.g.
 class rectangle
{
int length,breadth;

 rectangle() // default constructor
  {
length = 0;
 breadth = 0;
 } 

rectangle(int x,int y) // parameterized constructor
{
 length=x;
breadth=y;
}


 int area()
  {
  return(length*breadth);
}

}

class rectarea
{
 public static void main(String args[])
 {
 rectangle r=new rectangle(6,3);
 System.out.println(“Area = “ + r.area());
}
}

This entry was posted on Saturday, December 20, 2008 at 4:57 AM and is filed under . You can follow any responses to this entry through the comments feed .

0 comments

Post a Comment