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

So James Gosling developed a new language, which he called Oak. A

study showed that there already was a programming language called
Oak. So they changed the name to Java. • In 1994, the Internet and the World Wide Web became popular. The people at Sun realized that Java was suitable to develop applications for the Internet.
• They wanted fundamentally a new way of computing, based on the power of networks and wanted the same software to run on different

computers, consumer gadgets and other devices

with this people on different types of machines and operating systems started accessing the applications available on the web. and the operating system.• During that time Mosaic the First Graphical Browser was released. . • Members of the Oak team realized that java would provide the required cross-platform independence from the hardware network. Java became an integral part on the web. Very soon. which they later renamed as Hot Java. • Patrick Naughton and his colleague Jonathan Payne developed a browser in Java called WebRunner.

The New Era of Java • • • • • Java is new programming language from Sun Microsystems The elements from C. C++. identical to those of C or C++. and other languages. in most cases. . The libraries highly tuned for the Internet Environment. The statements and expressions are similar to those in many languages and. Java is quickly recognizable to many programmers.

Comparison with C – Java does not have: 1. Pointer Manipulation 2. Preprocessor . Global functions variables 5. Type definitions aliases (typedefs) 6. The goto statement 3. Automatic type conversion 4.

Compared with C++ – Java does not have • Operator overloading .

Java Virtual Machine (JVM) (Platform Independent) 3. Java-Enabled Web Browser .Java System 1. Software Libraries accompanying the system (API) 2.

The Java Platform M/C code 01001 Java Program JVM Interpreter Computer Compile intermediate Byte Code .

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 .

sql java. event java. security java.(Application Programming Interface) Java API — Applet classes • • • • • • • • java. awt. window. lang java. awt java. io java. beans java. and GUI classes — Event processing classes & interfaces — Java Beans component model API — Various types of input/output classes — Networking classes — Remote method invocation classes — Security classes — JDBC SQL API for database access — Various useful data classes • • • java. applet java. rmi — Core language classes — Graphics. net java. util .

the Interpreter.used to test applets on machines which does not have java enabled web browser .the complier. checks for syntactical error and converts syntax free java program into bytecode. Java .Java Development Kit (JDK) javac . executes the bytecode Appletviewer .

An Applet – (Platform Independent Programming) . An Application Programming language 2.Type of Java Programs Java is of two things: 1.

Java Fundamentals Structure of a JAVA program: class <Class_name> { public static void main(String args[]) { statements. } } .

A Multiline Comment /*…*/ 3.Comments: 1. They are used to produce a HTML file that documents the program. 2. Documentation Comment /**…………… */. A Single Comment //. .

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 .

4. underscore and DollerSign and can contain only alphabets. . underscore and DollerSign($). 2. 3. No space between Identifier name Java Keywords cannot be used as Identifier names. a Identifier name with upper case letters is different from the same name with lower case letters.Identifiers 1. number. The Identifier name must start with an alphabet. Java is a case-sensitivity.

Declaration of Variable and Constants Syntax : datatype <identifiername>.14f. Example : float radius. //(constant) . //(variable). final float PI=3.

• Constant in java are defined as Fully uppercase Eg: PI . StudentDetails 2. Variable or Method name: Begin with a lowercase letter followed by consecutive words begin with uppercase • • Eg: basicSalary. • Class Name: Begins with first letter uppercase letter. netSalary Eg: isVisible().Convention 1. Eg: Student. parseInt() 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) • Assignment Operator (Binary) • Increment / Decrement Operator (Unary) • Comma Operator (Binary) • Bit-Wise Operator (Binary) .

5 5%2=1 .Binary Operators Meaning + Addition Example a+b Result 5+2=7 * / % Subtraction Multiplication Division Modulo a-b a*b a/b a%b 5-2=3 5*2=10 5/2=2 or 2.Arithmetic Operator .

Expression • An Expression consists of variables and constants separated by operators. • Eg: a+b. a+b/c. .

/.% • +.- .(Right to Left) • *.Operator Priority • Left to Right • ( ) • ++.-.

Type Casting • Converting from one data type to another data type – Implicit Type Casting (Automatic) – Explicit Type Casting (Programmer) .

Implicit Type Casting Conversion is taking place automatically during program execution and is referred to automatic type or implicit conversion Operand1 int int Operand2 int long Result int long float float int double float double .

Explicit Type Casting • Variable declared in specific data type can be converted into the required data type • Syntax: – Variable = (typecast) expression. f= (float) (a+b)/c. • Example: int a.c. . float f.b.

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 .

b=5 True True False False != == Not equal to Equality a!=b a==b True False .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.

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 .

If Exp1 is true. Exp3 will execute . • Which is used to make a decision • Syntax: – Exp1 ? Exp2 : Exp3. • This operator is used to check either one only true or false statement. Exp2 will execute If Exp1 is false .Conditional Operator • The operator that act upon three operands are called as Conditional Operator or Ternary Operator.

b=3. big=(a>b) ? a : b . } • Output: – Biggest of two nos = 5 .Example { int a=5.big.big). printf(“Biggest of two nos = %d”.

Assignment Operator (=) • The operator that is used to assign the result of an expression to a variable is called as an Assignment Operator. . a=a+b. Syntax: Variable= constant. Variable=expression. Example a=10. Variable1=variable. a=b.

(fast) Invalid Assignment Const=var Exp=var 10=a a+b=a . • Short Assignment – a+=b.Types of Assignment Operator • Normal Assignment – a=a+b.

• Types – Post Increment and Decrement – Pre Increment and Decrement .Increment(++)/Decrement (--) Operator • Increment by 1 or Decrement by 1 with current value.

Output: 11 Decrement Var--.Post Increment and Decrement operator Syntax: Increment Var++. a++. Output: 19 . b--. Example int a=10. Example int b=20.

int a=10.Pre Increment and Decrement operator Syntax: Increment Example Decrement Example ++Var. Int b=20. Output: 19 . ++a Output: 11 --Var. --b.

y. ( The value of x is assign to y ie: y=10. y=x++. then x will be increment x=11) • Pre Increment int x. ( The value of x will be increment x=11 then assign to y ie: y=11) Output: x=11 y=10 Output: x=11 y=11 .y. x=10. x=10.Difference between Post and Pre increment • Post Increment int x. y=++x.

a+b).c. int c. . c=(a=10. b=20 c=a+b • Example: with comma int a.) • Which is used to link the related Expressions together  Example: without Comma int a. int b. a=10.Comma Operator(.b=20.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 .

• The control statements alter the execution of statements depending upon the conditions • Which are used to make a decision for real world problems . the statements in the program are executed sequentially.Control Statements • By default.

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

Execute block of statements; -----------------;

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

Multiple else if Statements
• Used to evaluate Series of Conditions • If we have to use more than one if-else statement, we have to create Multiple else if statements.

} else if(condition 2) { Execute 2nd block statements.Syntax: if(condition 1) else if(condition 3) { Execute 3rd block statements. } final block statements. } . } else { { Execute 1st true block statements.

} else { Inner else statements.Nested If statements • One condition followed by another condition • Syntax: if(condition1) { if(condition2) { Inner if statements. } } else { Outer else statement. } .

Note for else statement • Else should be followed by if statement • Else should not take condition • Else will execute only if the immediate if statement false • Else is optional .

} . case constant3 : statement(s). default: default statement(s). • 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). -----------.Switch Statement • Switch statement allows us to make a decision from a number of choices. case constant2 : 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 . double.Points to be noted for switch statement • Only one variable can be tested with the available case statements • It should be either integer or character variable • Float. long type variables cannot be used as cases.

.while loop – for loop . • Types – while loop – do.Loop Control Structures • A block of statements are executed repeatedly until a condition false is called as a loop.

Three steps of looping process • Initialization of the counter • Test for a specified condition for execution of the statements in the loop • Increment or Decrement the counter .

Increment or decrement loop counter.While loop • Syntax: – Initialize loop counter. } . while(condition) { Statement(s).

while loop is similar to while loop except that the dowhile loop test the condition at the end of the loop.while loop • The do.. the loop will be executed at least once if the condition not satisfied.. .do. • While loop will executed only if the condition is satisfied. • Hence.

}while(condition).Syntax: do { Statements(s). -------------. .

otherwise the loop will become infinite loop .increment/decrement) { Statements(s).For loop • For loop allows us to specify three steps about the loop in a single line • Syntax: for(initialization. } Note: The condition specified in the loop should eventually become false at one point.condition.

The break keyword exit from switch or inner loop of a program 2.Break and Continue 1. Continue is similar to break. . it continue the next iteration. except that instead exit from loop.

. •Each array element is referred by specifying the array name. followed by a number within the square braces[].referred as an index or subscript. An array is used to store data continuously in the memory of the computer.Arrays An array is an object that stores a list of items continuously of same data type. •The individual values in the array are called as elements.

Types of Arrays • Single Dimension Array • Multi Dimension Array .

67.20.50.77} .Single Dimension Array Declaration Array Initialization: Syntax : data-type array-name[] = {value1... }... Eg: int a[]= {10. value2..

or 3) int a[]. a[]= new int[5]. -------------------. -------------------.Creating array with size Syntax: datatype array-name [] = new datatype[size]. or 2) int[] a = new int[5]. Eg: 1) int a[] = new int[5]. new keyword creates an instance of an array .

Eg: int a[][]= new int[3][3].Two Dimension Array: Declaration : Syntax: datatype array_name[][] = new datatype[rowsize][col.size]. .

} .Methods Method Declaration access-specifier static returntype methodName(argument list) { Local variable declaration. Executable part. return (expression).

2.Type of Declarations 1. 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 . 3. 4.

.Object Oriented Programming (OOPs) • It simplifies the development of large and complex software systems and helps in the production of software’s. Reusable. Scalable and Security. • • Which is Modular. The object oriented approach centers around modeling the real world problems in terms of objects.

Inheritance and 3. Encapsulation.OOP's Concept The object-oriented model is based on three important concepts namely 1. Polymorphism . 2.

A mechanism that binds together code and the data where code manipulates the data. The information about the engine is hidden from the user. Eg: Consider an Automobile. Encapsulation is a protective wall that prevents the code and data from being randomly accessed by other code defined outside the wall. . 2.Encapsulation 1. The concept of hiding the non-essential details from the user is called Encapsulation. and keep both safe from outside interference and misuse. 3.

along with the additional characteristics unique to the new class. .Inheritance Is a process of creating a New Class with the properties of an Existing Class. The new class obtains the properties of the existing class.

This means one common name for a method with different parameters.Polymorphism Is a feature that allows one Interface to be used for a general class of action. More generally. Method Overriding (Runtime) . the concept of polymorphism is often expressed by the phrase "one interface. there are two types of polymorphism: 1. Method Overloading (Compile) 2. multiple methods". In Java .

The elements of a class are called members. A class defines the structure and behavior of the objects. .Class A class is a prototype that defines the Data and Code common to all objects of a particular kind. The data defined by the class is called variables. The code that acts on the data is called method.

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 .

Syntax: class-name Objectname=new class-name( ).new Operator The new operator creates a single instance of a named class and returns a reference to that object. . Eg: Box mybox = new Box().

//declare reference to object mybox = new Box(). //allocate memory for a box object .Reference Variable Box mybox.

<variable name> <objectReference> . <object Reference> . <method name> Eg: obj. obj.Dot Operator The dot notation is used to obtain the value of the instance variable.sum().a=10. .

not a public . can be accessed by any method in the outside of the class.Access Specifier • Public: The members. • Private : • Protected: Note: The protected access specifiers have been deal with Inheritance and packages in java. In Java. default access specifies is NoAccessSpecifier. A Member Data or Methods can only be accessed by the methods of the same class. which are declared as a public. The private instance variable is not accessible from the outside of the class.

methods and even to a strange kind of code that is not a part of a method. Static features are associated with a class rather than being associated with an individual instance of a class .Static Keyword The static modifier can be applied to variables.

eg: objectname.var=value. .var=value. classname.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. 3. Types of argument should be distinct. . The number of arguments should be distinct. 1. Sequence of argument should be distinct. 2.

constructor will be invoke automatically. When we create an object of the class. Constructors can also be Overloaded . Constructor should be in public 3. Constructor has no return type. But it may be have argument. Constructor name and class name must be equal. 2.Constructor A Constructor is a special kind method that determines how an object is initialized when created. 4. 5. Rules for constructing Constructor:1.

Types • Default Constructor: • Parameterised Constructor • Overloading Constructors .

The newly as ―subclass or . The existing class is called as ―Base class (or) super class‖. created class is called derived class‖.Inheritance It is a process of creating new class from an existing class.

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

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. You can require that certain method to be overwrite in the future To declare an abstract method.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.

} } Note: Abstract Class Cannot be instantiate (cannot create object.) .Syntax abstract class A { abstract public int arith(int a.int b) { return (a+b). int b). public int sum(int a.

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 this keyword can be used where a reference to an object of the current class type is required Note: Methods declared with the keyword static (class methods) cannot use this. . The value of this refers to the object on which the current method has been called.

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

Note: An interface cannot be instantiate

Points to be Note for classes and Interfaces
• A class can extends another class • A interface can extends another interface • A class can implements more than one interfaces Note:
– An interface cannot extends or implements a class

Error handling becomes necessarily when you develop applications that need to cause of unexpected situations . 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.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.

try .. -----------------. } . -----------. } catch(Exception object) { Exception code. catch block • try { Statements. ------------------.