187
UNIT-I INTRODUCTION TO JAVA Java programming language was originally developed by Sun Microsystems, which was initiated by James Gosling and released in 1995. Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere JAVA FEATURES Object Oriented: In java everything is an Object. Java can be easily extended since it is based on the Object model. Platform independent: Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run. Simple: Java is designed to be easy to learn. Secure: With Java’s secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architectural- neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence Java runtime system. Portable: being architectural neutral and having no implementation dependent aspects of the specification makes Java portable. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multi-threaded: With Java’s multi-threaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere.

Java Notes

Embed Size (px)

Citation preview

UNIT-IINTRODUCTION TO JAVA Java programming language was originally developed by Sun Microsystems, which was initiated by James Gosling and released in 1995. Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere JAVA FEATURES

Object Oriented: In java everything is an Object. Java can be easily extended since it is based on the Object model. Platform independent: Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run. Simple: Java is designed to be easy to learn. Secure: With Javas secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architectural- neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence Java runtime system. Portable: being architectural neutral and having no implementation dependent aspects of the specification makes Java portable. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multi-threaded: With Javas multi-threaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process. High Performance: With the use of Just-In-Time compilers Java enables high performance. Distributed: Java is designed for the distributed environment of the internet.

BASIC CONCEPTS OF OOPS Object and classes Data abstraction and Encapsulation Inheritance Polymorphism Dynamic binding Message communication JAVA TOKENS Keywords

Identifiers Literals Operators Separators Identifiers All java components require names. Names used for classes, variables and methods are called identifiers. In java there are several points to remember about identifiers. They are as follows: All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, _1_value Examples of illegal identifiers: 123abc, -salary Keywords Keywords are reserved words that are predefined in the language. There are few keywords in Java programming language. Remember, we cannot use these keywords as identifiers in the program and all the keywords are in lowercase.

Example: number, $$abc, _xyx // Legal Identifiers 12cc, ss-he // Illegal identifiers Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators

Literals A literal is the source code representation of a fixed value; literals are represented directly in our code without requiring computation. Integer Literals Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. boolean result = true; char capitalC = 'C'; byte b = 100; Floating-Point Literals Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. EX: Standard notation: 2.0, 3.14159, and 0.6667 scientific notation: 6.022E23, 314159E05, and 2e+100 Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, true and false Character Literals o Characters in Java are indices into the Unicode character set. String Literals String literals in Java are specified like they are in most other languagesby enclosing a sequence of characters between a pair of double quotes. Examples of string literals are Hello World. JAVA STATEMENTS Statements in java are like sentences in natural languages. A statement is an executable combination of tokens ending with a semicolon mark. Java statements are classified into eight types. Empty statement Labelled statement Expression statement Selection statement

Iteration statement Jump statement Synchronization statement Guarding statement

VARIABLES The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. Declaring the variable In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value] ...] ; The type is one of Javas atomic types, or the name of a class or interface. The identifier is the name of the variable. We can initialize the variable by specifying an equal sign and a value. To declare more than one variable of the specified type, use a comma-separated list. int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing d and f. byte z = 22; // initializes z. Variables can be classified into three categories: Local variables: All the variables declared inside a method. Their scope is the

method. In other words, they can be accessed only from inside the method in which they are declared, and they are destroyed when the method completes. Local variables are also called stack variables because they live on the stack. Instances variables: The variables declared inside a class but outside of any method. Their scope is the instance of the class in which they are declared. These variables, for example, can be used to maintain a counter at instance level. Instance variables live on the heap. Static variables: The instance variables declared with the modifier static. Their scope is the class in which they are declared. These variables can be used to maintain a counter at class level, which is a variable shared by all the objects of the class. Their scope is the instance of the class in which they are declared. These Data Types Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups: Integers This group includes byte, short, int, and long, which are for wholevalued

signed numbers. Floating-point numbers This group includes float and double, which represent

numbers with fractional precision.

Characters This group includes char, which represents symbols in a character set,

like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). float: The float data type is a single-precision 32-bit of storage. It has an approximate range from 1.4e-045 to 3.4e+038 double: The double data type is a double-precision 64-bit of storage. It has an approximate range from 4.9e324 to 1.8e+308 boolean: The boolean data type has only two possible values: true and false. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. The following chart summarizes the default values for the above data types. Data Type Byte Short Int Long Float Double Char Default Value (for fields) 0 0 0 0L 0.0f 0.0d '\u0000'

String (or any object) Null Boolean False

Type Casting The process of storing a value of one data type into a variable of another data type is called as type casting. The syntax is Type variable1= (type) variable2; Examples: int m=50; byte n= (byte) m; There are two types of casting widening and narrowing. The process of assigning a smaller type to a larger one is known as widening or promotion. Java automatically does this. This is known as automatic type conversion. The process of assigning a larger type to a smaller one is known as narrowing. This may result in loss of information.

JAVA OPERATORS

Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators

Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and variable B holds 20 then: Operator Description + Addition - Adds values on either side of the operator Example A + B will give 30

* / % ++ --

Subtraction - Subtracts right hand operand from left hand operand Multiplication - Multiplies values on either side of the operator Division - Divides left hand operand by right hand operand Modulus - Divides left hand operand by right hand operand and returns remainder Increment - Increase the value of operand by 1 Decrement - Decrease the value of operand by 1

A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 B++ gives 21 B-- gives 19

Relational Operators: There are following relational operators supported by Java language. Operator Description == Checks if the value of two operands are equal or not, if yes then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes , becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Example (A == B) is not true.

!=

(A != B) is true.

>

(A > B) is not true.

=

(A >= B) is not true.

> 2 will give 15 which is 1111 A >> number of bits specified by the right A >>>2 will give 15 which is 0000 1111 operand and shifted values are filled up with zeros. Logical Operators: The following table lists the logical operators: Assume boolean variables A holds true and variable B holds false then: Operator Description Called Logical AND operator. If both && the operands are non zero then (A && B) is false. condition becomes true. Called Logical OR Operator. If any of || the two operands are non zero then then (A || B) is true. condition becomes true. Called Logical NOT Operator. Use to ! reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. Example

Assignment Operators: There are following assignment operators supported by Java language:

Operator Description

Example

Simple =

assignment

operator,

Assigns values from right side operands to left side operand Add AND assignment operator, It

C = A + B will assigne value of A + B into C

+=

adds right operand to the left operand and assign the result to left operand Subtract AND assignment

C += A is equivalent to C = C + A

-=

operator, It subtracts right operand from the left operand and assign the result to left operand Multiply AND It assignment right

C -= A is equivalent to C = C - A

*=

operator,

multiplies

operand with the left operand and assign the result to left operand Divide AND assignment operator,

C *= A is equivalent to C = C * A

/=

It divides left operand with the right operand and assign the result to left operand Modulus AND assignment

C /= A is equivalent to C = C / A

%=

operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

> 2 C &= 2 is same as C = C & 2

and C ^= 2 is same as C = C ^ 2

assignment operator |= bitwise inclusive OR and C |= 2 is same as C = C | 2

assignment operator

Misc Operators There are few other operators supported by Java Language. Conditional Operator ( ? : ): Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as : variable x = (expression) ? value if true : value if false instanceOf Operator: This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as: ( Object reference variable ) instanceOf (class/interface type) If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side then the result will be true. Expressions Arithmetic Expressions: An arithmetic expression is a combination of variables, constants, and operators arranged as per the syntax of the language. Example: (a*b)/(c+d)

Evaluation of Expressions: Exprssions are evaluated using an assignment statement of the form

Variable = expression; Example: x= : (a*b)/(c+d)

Precedence of Arithmetic operators: High priority: * / %

Low priority: + BRANCHING AND LOOPING Selection statements: 1. If Statement: This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed. Syntax: if(conditional_expression){ ; ...; ...; } Example: int n = 10; if(n%2 = = 0){ System.out.println("This is even number"); } 2. If-else Statement: The "if-else" statement is an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. Syntax: if(conditional_expression){ ; ...; ...; } else{

; ....; ....; } Example: int n = 11; if(n%2 = = 0){ System.out.println("This is even number"); } else{ System.out.println("This is not even number"); } 3. Switch Statement: This is an easier implementation to the if-else statements. The keyword "switch" is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed, if no case matches then the default statement (if present) is executed. Syntax: switch(control_expression){ case expression 1: ; case expression 2: ; ... ... case expression n: ; default: ; }//end switch Example:. int day = 5; switch (day) { case 1:

System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thrusday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default: System.out.println("Invalid entry"); break; } Repetition Statements: 1. while loop statements:

This is a looping or repeating statement. It executes a block of code or a statement till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop. Syntax: while(expression){ ; ...; ...; } Example:. int i = 1; //print 1 to 10 while (i