Java
Java
History of Java
Java was developed at Sun Microsystem in 1995. The history of Java can be traced back to a project called Green project in SUN. Patric Naughton, Bill Joy, James Gosling, Mike Sheridan were some of the people working on the Green project. The aim of this project was to develop software for smart consumer electronic devices such a complex remote controls.
At first developer tried using C++ to develop the software but they faced
a number of problems.
During that time Mosaic the First Graphical Browser was released, with this people on different types of machines and operating systems started accessing the applications available on the web.
Patrick Naughton and his colleague Jonathan Payne developed a browser in Java called WebRunner, which they later renamed as Hot Java.
Members of the Oak team realized that java would provide the required cross-platform independence from the hardware network, and the
operating system. Very soon, Java became an integral part on the web.
Comparison with C
Java does not have:
1. Pointer Manipulation 2. The goto statement
Java System
1. Software Libraries accompanying the system (API) 2. Java Virtual Machine (JVM) (Platform Independent) 3. Java-Enabled Web Browser
Compile
Platform Independent
Java Program
Compiler
Interpreter JVM
Interpreter JVM
Interpreter JVM
Windowss
Solaris
Lunix
Characteristics of Java
Simple and Powerful Architecture-Neutral Object-Oriented Portable
Distributed
High-performance Interpreted Multithreaded Robust Dynamic Security
Java API
Applet classes
java. lang java. applet java. awt java. awt. event java. beans java. io java. net java. rmi
Graphics, window, and GUI classes Event processing classes & interfaces
java. security
java. sql java. util
Java
- the Interpreter, executes the bytecode Appletviewer - used to test applets on machines which does not have java enabled web browser
Java Fundamentals
Structure of a JAVA program: class <Class_name> {
public static void main(String args[])
{
statements;
} }
Comments:
1. 2. A Single Comment //. A Multiline Comment /**/
3. Documentation Comment
/** */. They are used to produce a HTML file that documents the program.
Java Keywords
abstract do implements short
boolean
break byte case catch char class continue default
double
else extends final finally float for false if
import
int interface long new private protected public return
static
super switch this throw try true void while
Data Types
Keywords byte short int long Real Types float 4 Byte Size 1 2 4 8
Integer Types
double
Other Types char boolean
8
2 true or false
Identifiers
1. The Identifier name must start with an alphabet, underscore and DollerSign and can contain only alphabets, number, underscore and DollerSign($). 2. 3. 4. No space between Identifier name Java Keywords cannot be used as Identifier names. Java is a case-sensitivity, a Identifier name with
upper case letters is different from the same name with lower case letters.
Convention
1.
2.
3.
Operators
Operator is a Symbol which performs specific Operation
Classification of Operators
Unary Operator Operators that acts upon a single operand Binary Operator Acts upon two operand Ternary Operator Acts upon three operand
Operators
Arithmetic Operator (Binary) Relational Operator (Binary) Logical Operator (Binary) Conditional Operator (Ternary)
* / %
Expression
An Expression consists of variables and constants separated by operators.
Eg: a+b;
a+b/c;
Operator Priority
Left to Right ( ) ++,-- (Right to Left) *,/,% +,-
Type Casting
Converting from one data type to another data type Implicit Type Casting (Automatic) Explicit Type Casting (Programmer)
float float
int double
float double
Relational Operator
Which are used to compare the values of operands to produce a logical value either true or false Which is used make a decision for real world problem
True =1 False=0
Relational Operators
Operators < <= > >= Meaning Less than Less than or equal to Greater than Greater than or equal to Example a<b a<=b a>b a>=b Result If a=2,b=5 True True False False
!=
==
Not equal to
Equality
a!=b
a==b
True
False
Logical Operators
Which are used to evaluate more than one relational expressions Which is also used to make a decision either true or false
Operator
&& || !
Meaning
AND OR Not
Example
A&&B A||B !A
Logical Operator
Example
A True True B True False A&&B True False A||B True True
False
False
True
False
False
False
True
False
Conditional Operator
The operator that act upon three operands are called as Conditional Operator or Ternary Operator. This operator is used to check either one only true or false statement. Which is used to make a decision Syntax: Exp1 ? Exp2 : Exp3; If Exp1 is true, Exp2 will execute If Exp1 is false , Exp3 will execute
Example
{ int a=5,b=3,big; big=(a>b) ? a : b ;
a+=b; (fast)
Invalid Assignment Const=var Exp=var 10=a a+b=a
Increment
Var++;
Example
int a=10; a++; Output: 11
Decrement
Var--;
Example
int b=20; b--; Output: 19
++Var;
--Var;
Output:
x=11 y=10
Output:
x=11 y=11
Comma Operator(,)
Which is used to link the related Expressions together
c=(a=10,b=20,a+b);
Bitwise Operators
These operators are used to perform operations in terms of binary. Ex: int a=5, b=3
Operators
& |
Meaning
Bitwise AND Bitwise OR
Example
a&b a|b
Output
1 7
~
^ >> <<
Bitwise NOT
Exclusive OR (XOR) Right Shift Left Shift
~a
a^b a>>2 a<<2
65350
6 1 20
Control Statements
By default, the statements in the program are executed sequentially. The control statements alter the execution of statements
Types
Simple if if .. else Multiple else if or else if ladder Nested if switch break or continue
Simple if
It is used to execute block of statements if the condition is true, otherwise it will skip the if block Syntax: if(condition)
True
False
----------------;
} Normal statements;
If .. Else Statement
Used to Evaluate True block or False block statements If the if condition is true it will execute true block otherwise, execute else block statements Syntax: if(condition) True { Execute true block statements; -----------------; False ----------------; } else { Else block statements; }
Syntax:
if(condition 1)
Execute 1st true block statements; } else if(condition 2) { Execute 2nd block statements; }
Nested If statements
One condition followed by another condition
Syntax:
if(condition1)
{ if(condition2) { Inner if statements; } else { Inner else statements; } }
else
{ Outer else statement; }
Switch Statement
Switch statement allows us to make a decision from a number of choices. It is used to execute a block of statements depending on the value of a variable or an expression Syntax: Switch(int var or char var) { case constant1 : statement(s); -----------; case constant2 : statement(s); case constant3 : statement(s); default: default statement(s); }
Default statement will execute only none other than case is match
Default statement may appear any where inside the switch statement
Default is optional
for loop
While loop
Syntax: Initialize loop counter; while(condition)
{
Statement(s); Increment or decrement loop counter; }
do..while loop
The do..while loop is similar to while loop except that the dowhile loop test the condition at the end of the loop. Hence, the loop will be executed at least once if the condition not satisfied. While loop will executed only if the condition is satisfied.
Syntax:
do { Statements(s); -------------; }while(condition);
For loop
For loop allows us to specify three steps about the loop in a single line Syntax: for(initialization;condition;increment/decrement) { Statements(s); } Note: The condition specified in the loop should eventually become false at one point, otherwise the loop will become infinite loop
Arrays
An array is an object that stores a list of items continuously of same data type. An array is used to store data continuously in the memory of the computer.
The individual values in the array are called as elements. Each array element is referred by specifying the array name, followed by a number within the square braces[],referred as an index or subscript.
Types of Arrays
Single Dimension Array Multi Dimension Array
Eg:
Methods
Method Declaration
access-specifier static returntype methodName(argument list) { Local variable declaration; Executable part; return (expression); }
Type of Declarations
1. 2. 3. 4. Method with arguments and with return type Method without arguments and with return type Method with arguments and without return type Method without arguments and without return type
OOP's Concept
The object-oriented model is based on three important concepts namely
Encapsulation
1. A mechanism that binds together code and the data where code manipulates the data, and keep both safe from outside interference and misuse. Encapsulation is a protective wall that prevents the code and data from being randomly accessed by other code defined outside the wall. The concept of hiding the non-essential details from the user is called Encapsulation.
2.
3.
Eg: Consider an Automobile. The information about the engine is hidden from the user.
Inheritance
Is a process of creating a New Class with the properties of an Existing Class, along with the additional characteristics unique to the new class. The new class obtains the properties of the existing class.
Polymorphism
Is a feature that allows one Interface to be used for a general class of action. More generally, the concept of polymorphism is often expressed by the phrase "one interface, multiple methods". This means one common name for a method with different parameters. In Java , there are two types of polymorphism:
1. Method Overloading (Compile) 2. Method Overriding (Runtime)
Class
A class is a prototype that defines the Data and Code common to all objects of a particular kind. A class defines the structure and behavior of the objects.
Object
An instance of class Copy of class or Real time entity of a class. It is a variable, which is used to access the instance variables and methods of class
new Operator
The new operator creates a single instance of a named class and returns a reference to that object. Syntax:
Reference Variable
Box mybox; //declare reference to object
Dot Operator
The dot notation is used to obtain the value of the instance variable. <object Reference> . <variable name>
Access Specifier
Public:
The members, which are declared as a public, can be accessed by any method in the outside of the class. A Member Data or Methods can only be accessed by the methods of the same class. The private instance variable is not accessible from the outside of the class.
Private :
Protected:
Note:
The protected access specifiers have been deal with Inheritance and packages in java.
Static Keyword
The static modifier can be applied to
static Variable
Via a reference to any instance(object) of the class Via the classname.
Static Method
They can only call other static methods
They must only access static data. They cannot refer to this or super in any way
Method Overloading
In a class more than one method can have same method name.
All the methods distinct in three ways. 1. The number of arguments should be distinct. 2. Types of argument should be distinct. 3. Sequence of argument should be distinct.
Constructor
A Constructor is a special kind method that determines how an object is initialized when created.
Rules for constructing Constructor:1. Constructor name and class name must be equal. 2. Constructor should be in public 3. Constructor has no return type. But it may be have argument. 4. When we create an object of the class, constructor will be invoke automatically. 5. Constructors can also be Overloaded
Types
Default Constructor: Parameterised Constructor Overloading Constructors
Inheritance
It is a process of creating new class from an existing class. The existing class is called as Base class (or) super class. created class is called derived class. The newly
as subclass or
Syntax
class<sub-class-name> extends <super-class-name> { instance variable; + methods(); }
Types
Single Inheritance. Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance ( for Interfaces only)
Method Overriding
In a multilevel inheritance, when a method in a subclass as the same name and type signature as a method in its super class, then the method in subclass is said to override the method in the
superclass
Abstract Class
There are situations in which we will want to define a super class that declares the structure of a given abstraction without providing a complete implementation of every altered. You can require that certain method to be overwrite in the future To declare an abstract method, the function declaration should be preceded by abstract keyword. Any class that contains one or more abstract methods must also be declared as abstract class.
Syntax
abstract class A { abstract public int arith(int a, int b); public int sum(int a,int b) { return (a+b); } } Note: Abstract Class Cannot be instantiate (cannot create object.)
Final Modifiers
Final variable
cannot be modified
Final Class
cannot inherited
Final Method
cannot override
this keyword
The this keyword is used inside any instance method to refer to the current object. The value of this refers to the object on which the
Interfaces
An Interface is a collection of methods without implementation. An interface can also include variable declaration.
Defining an interface:
interface interface-name { variables+methods; }
Implementing interfaces
Once an interface has been defined, one or more classes can implement that interfaces. To implement the interface, include the implements keyword in a class definition and then create a method defined by the interface.
Syntax
class class-name implements interface-name { }
Exception Handling
An exception is an event that occurs during the execution of a program that disturbs the normal flow of instructions Exceptions are erroneous events like Division by Zero, Opening a File that Does Not Exist etc. A Java exception is an object describes an exceptional condition that has occurred in a piece of code. Error handling becomes necessarily when you develop applications that need to cause of unexpected situations