• No results found

Java guide

N/A
N/A
Protected

Academic year: 2021

Share "Java guide"

Copied!
192
0
0

Loading.... (view fulltext now)

Full text

(1)

JAVA

JAVA

Features of java:

Features of java:

The features of any program language (or) their facilities (or) services provide by The features of any program language (or) their facilities (or) services provide by the language.

the language.

The various features of java language are The various features of java language are

1. Simple: 1. Simple:

The learning and implementation of java language is simple based on the The learning and implementation of java language is simple based on the following reasons.

following reasons.

* The syntax of java language is similar to other language like C, C++. * The syntax of java language is similar to other language like C, C++.

* The complex topics like pointers, templates of other languages are eliminated in java language * The complex topics like pointers, templates of other languages are eliminated in java language making it a simple program language. The pointer concept will head to confusion & they are making it a simple program language. The pointer concept will head to confusion & they are threat to the data.

threat to the data.

* In java language the deallocation of the memory is done automatically by garbage collector & * In java language the deallocation of the memory is done automatically by garbage collector & as a programmer we need not worry about memory deallocation.

as a programmer we need not worry about memory deallocation.

Object Oriented: Object Oriented:

Java language is an object oriented program language. Any object oriented Java language is an object oriented program language. Any object oriented  program language will develop an application with the help classes and objects.

 program language will develop an application with the help classes and objects.

* An object can be anything that exist physically in the real world which requires some memory * An object can be anything that exist physically in the real world which requires some memory (or) space.

(or) space.

* Every object will contain some properties & some actions. Using the properties we can * Every object will contain some properties & some actions. Using the properties we can describe the object & the actions represents task performed by the object.

describe the object & the actions represents task performed by the object. * A class can be con

* A class can be considered as a plan (or) a modesidered as a plan (or) a model (or) a blueprint for creating the objects.l (or) a blueprint for creating the objects. * A class doesn’t exist physical

* A class doesn’t exist physically but it provides a logical explanation to the objects. For a classly but it provides a logical explanation to the objects. For a class we can create any number of objects.

we can create any number of objects. * A class is a collection of common

* A class is a collection of common features of a group of objects.features of a group of objects. class: student

class: student

object: surendra, srikanth, venkat etc.(Ex) object: surendra, srikanth, venkat etc.(Ex) class: movie

class: movie

object: Gamyam, Bommarillu etc. object: Gamyam, Bommarillu etc.

(2)
(3)

Secured: Secured:

Security is one of the most important principle of any programming language. Security is one of the most important principle of any programming language. When we develop applications in java, we need not specially provide any security programs for When we develop applications in java, we need not specially provide any security programs for  protecting

 protecting the the data data from from unauthorized unauthorized usage usage because because the the java java language language comes comes with with by by defaultdefault security programs. But in C++, we have

security programs. But in C++, we have to write security program to protect the data.to write security program to protect the data.

Robust: Robust:

The java language is said to be a robust (or) strong program language based on The java language is said to be a robust (or) strong program language based on the following reasons.

the following reasons.

1. Memory Management: 1. Memory Management:

The memory management in java is very efficient because there will be no The memory management in java is very efficient because there will be no wastage of memory at the time of allocation and the unused memory will be deallocated wastage of memory at the time of allocation and the unused memory will be deallocated immediately by the garbage collector.

immediately by the garbage collector.

2. Exception Handling: 2. Exception Handling:

The errors that occur at the time of execution (Runtime Errors) are called The errors that occur at the time of execution (Runtime Errors) are called exceptions & the process of handling those errors is called as Exception Handling, which is very exceptions & the process of handling those errors is called as Exception Handling, which is very efficient in java.

efficient in java.

Distributed: Distributed:

The java language is said to be a distributed language. With the help of this The java language is said to be a distributed language. With the help of this distributed nature we can access the data available in multiple machines and provide it to the distributed nature we can access the data available in multiple machines and provide it to the user. Using the distributed nature we can improve the performance because of the more user. Using the distributed nature we can improve the performance because of the more availability and more accessibility of the data.

availability and more accessibility of the data.

Platform Independent (or) Architecture Neutral: Platform Independent (or) Architecture Neutral:

The java language is said to be a platform independent language because it can be The java language is said to be a platform independent language because it can be executed on any machine irrespective of the operating system, their architecture, their hardware executed on any machine irrespective of the operating system, their architecture, their hardware (or) s/w etc.

(or) s/w etc.

When a ‘C’ program is compiled, the compiler will convert the ‘C’ language When a ‘C’ program is compiled, the compiler will convert the ‘C’ language instructions into machine level instructions. The machine level instructions generated by ‘C’ instructions into machine level instructions. The machine level instructions generated by ‘C’ compiler can be executed only on that machine where it is compiled. If we want to execute on compiler can be executed only on that machine where it is compiled. If we want to execute on

(4)

another machine th

another machine then we have to compile it once again. This nature of ‘C’ language makes iten we have to compile it once again. This nature of ‘C’ language makes it ““machine dependentmachine dependent”.”.

When a java program is compiled, the compiler will generate byte code When a java program is compiled, the compiler will generate byte code instructions which are called as Special java instructions.

instructions which are called as Special java instructions.

The byte code instructions available in demo.class can be executed on any The byte code instructions available in demo.class can be executed on any machine with the help of JVM(Java Virtual Machine). This nature of java makes it machine machine with the help of JVM(Java Virtual Machine). This nature of java makes it machine independent (or) platform independent.

independent (or) platform independent.

Compiler: Compiler:

It will compile all the code, while compiling if we get any errors, it will store all It will compile all the code, while compiling if we get any errors, it will store all the errors in memory. Once the code the code gets compiled, then it will generated all the errors the errors in memory. Once the code the code gets compiled, then it will generated all the errors at a time.

at a time.

Interpreter: Interpreter:

It will compile line by line, it doesn’t has memory to store the value. While It will compile line by line, it doesn’t has memory to store the value. While compiling, if we get any error, they will throw the error & stops the execution at that line once compiling, if we get any error, they will throw the error & stops the execution at that line once error gets fixed, then continue execution with the next line.

error gets fixed, then continue execution with the next line.

The java language is said to be a portable language using which we can develop The java language is said to be a portable language using which we can develop applications which is a collection of small reusable and replacable components.

applications which is a collection of small reusable and replacable components.

Interpreted: Interpreted:

The java

The java language contains an language contains an interpreter interpreter along with along with the compiler the compiler which iswhich is responsible for executing the code & therefore called as interpreted language.

responsible for executing the code & therefore called as interpreted language.

Other language like C, C++ etc has Other language like C, C++ etc has compiler (or) Interpreter only.compiler (or) Interpreter only.

High Performance: High Performance:

In language the execution of a program is done by both compiler & interpreter In language the execution of a program is done by both compiler & interpreter which reduce the execution time & thereby improving the performance of the application.

(5)

Multi Threaded:

A language that supports multiple threads will be called as multi threaded language. Every thread can be considered as a part of a program which is controlling the application. The multi thread concept will reduce the waiting time & improves the performance of the application.

Dynamic:

The location of the memory in java language will be done at the time of execution.

 In C, memory allocation will be done at the time of compilation.

 Every java program will have the extension has [.java].

 The [.java] file developed by the programmer will be provided to the compiler. The compiler will take the (.java) file and verifies whether the java code is valid (or) not, if valid the compiler will generate a (.class) file containing byte code instructions (Special java instructions)

(6)

JVM Architecture:

The .class file will be provided as input to the class loader subsystem. The class loader subsystem will perform the following operations.

* The class loader subsystem will load the (.class) file into the JVM.

* Before loading the (.class) file it will verify whether the bytecode is valid (or) not with the help of bytecode verifier.

* If the bytecode is valid then it will load bytecode in different locations called as Runtime Data Areas.

The various Runtime Data Areas are:

1. Method Area:

This area can be used for storing all the class code and the method code.

2. Heap:

This area can be used for storing the objects.

3. Java Stack:

This area can be used for storing all the methods that are required for execution. The java stack can be considered as a collection of frames where each frame will contain the information of one method.

(7)

4. PC Register (Program Counter):

This register will contain the address of the next instruction that has to be executed.

5. Java Native Stack:

This area can be used for storing all the non-java code (Native code).

Execution Engine:

The execution engine is responsible for executing the byte code available in runtime data areas. The execution engine contains two parts:

1. Interpreter.

2. JIT compiler (Just In Time).

Both the pass of the execution engine are responsible for executing the code simultaneously which reduces the execution time & there by improves the performance of the application.

The bytecode available in the runtime data areas will be shared by the interpreter and JIT compiler. Most of the code will be used for executing the code whenever required.

The code executed by the JIT compiler is called as HOTSPOTS.

Native Library:

This interface will help the JVM to load the native library into the runtime data errors.

OS:

The JVM has to interact with the operating system so that it can use the resources available in that machine.

Note:

The bytecode available in (.class) file can be executed on any machine with the help of JVM.

Comments:

The comments are used for explaining the code or they make the code more understandable. The comments in a program will improve the readability of the code. Comments are not part of the logic, they are non-executable statements.

(8)

In java language we have different types of comments. They are

1. Single Level Comments:

The single level comment can be used for writing a comment in a single line. The single line comments begins with”//” symbols & end in the same line.

Ex: //this is a single line comment.

2. Multiline Comment:

Multiline comments can be used for writing the comments in multiple lines. The multiple comments begins with “/*” ends with “*/”.

Ex:

/* this is a line one comment this is a line two comment this is a line three comment */

These comments can begin in a line & end in any other line.

 Single line & multiple comments are used purely for explaining the code only.

Multiple Comments:

These comments can be used for creating a document (Manual) for the software that is developed i.e., using these comments we can create an API (Application Programming Interface). These comments will begin with”/**” & ends with “*/”. These comments can begin & end in any line.

Syntax: /**

Author: Srikanth Created on: Last modified on: */

(What are the classes & methods are used everything will  be describing about prg (or) software)

(9)

DATA TYPES

Data types will represent the type of data that can be stored into a memory location. The data types in java can be classified into three types

1. Primitive Data Types:

These data types are predefined and they are designed to store a single value. Ex: int char

2. Derived Data Types:

These data types are predefined and they are designed to store multiple values. Ex: array

3. User Defined Data Types:

These data types are created by user or programmer according to the application requirement. The user defined data type can contain any no of values and they can be of any type.

Ex: class

1. Primitive Data Types:

These data types are predefined and they are used for sharing basic inputs required for a program. These data types are also called as fundamental data types which can be used for storing a single value.

The java language provides eight primitive data types classified into 4 categories. i. Integer Category

ii. Floating point Category iii. Character Category iv. Boolean Category

i. Integer Category:

This category is used for storing numbers which can be either +ve or  – ve without decimal point. Under the integer category we have four primitive data types. They are

a)  byte  b) short

(10)

c) int d) long

The purpose of all the 4 types under integer category is to store same kind of data but their size and ranges are different so that the memory can be utilized efficiently.

Data Type Size Range

 byte 1byte -128 to 127

short 2bytes -32768 to 32767

int 4bytes -2147483648 to 2147483648 long 8bytes -9223372036854775808 to

9223372036854775807

 byte  1 byte  8 bits

ii. Floating point Category:

This category is used for storing numbers which can be either +ve or  – ve with decimal point. Under the floating point category we have two primitive data types. They are

a) Float  b) Double

The purpose of both the primitive data types floating point category is to store same kind of data  but their size and ranges are different so that the memory can be utilized efficiently.

(11)

float 4bytes -1.4e -45 to 3.4e 38 7 double 8bytes 4.9e-324 to 1.8e308 15

iii. Character category:

This category is used for storing single character. A character can be represented  by either an alphabet (lowercase or uppercase) or digit or special symbol.

* Under character category we have only 1 primitive data type. a) char

Data Type Size Range

char 2bytes 0 to 65535 * In C 1byte because of ASCII.

* Here all languages can be used.

***Why size of char 1byte in C & 2byte in java?

The application that are developed in C language and to store that characters of only english language and to store that characters 1byte of memory is sufficient. The C language uses ASCII character set.

The application developed java language use character of all foreign languages. To store the characters of all the foreign languages 1byte of memory is not sufficient. Size of char is increased to 2bytes. Java language uses UNICODE set.

iv. Boolean Category:

This category can be used for storing only 2 values and they are true & false. Under the boolean category we have only one primitive data type and it is boolean.

Data Type Size Range

 boolean JVM dependent true false **Why it is JVM dependent?

The JVM that is used for executive java program can be implemented by any organization. The size of the boolean will be decided by the organization that develops the JVM. Therefore boolean size JVM dependent.

(12)

Variables

Variable is a name given to the memory location in which we can store some data or value.

Ex:

Variable Declaration:

The process of specifying what type of data is to store into the memory is called as variable declaration. Syntax: datatype variablename; datatype var1,var2,var3,….; Ex: int age; int rollno,accno; double marks; char grade;  boolean result;

When a variable is declared, the memory for the variable will be allocated and it can contain some data. The amount of memory allocated to a variable will depend upon the data type that is specified.

Once the memory for the variable is allocated it can hold some data. If we do not  provide any value to a variable then the memory location will automatically contain default value

(13)

Default Values  byte - 0 short - 0 int - 0 long - 0 float - 0.0 double - 0.0 char - space  boolean - false string - null student - null Any class –  null

If a variable is declared and if we do not provide any value then the variable will be automatically initialized with their default value. If we do not want default values then we can initialize the variable with our own values at the time of declaration.

Syntax:

datatype variablename; datatype var1,var2,var3,….;

Initialization:

Process of providing value to a variable for the first time is called initialization. The value of a variable can be changed any no of times during the execution of the program.

Assignment:

Process of providing value to a variable for the second time is called assignment.

Syntax:

int age = 20; Initialization age = 21; Assignment age = 22; Assignment

(14)

int rollno = 123;

double marks = 98.76; char grade = ‘A’;  boolean result = false;

Keyword:

Words that are predefined meaning in java are whose meaning is already reserved are called as keywords.

Literal:

Value that we store in the variable are called literals.

Identifier:

Any name that is used for the purpose of identification will be called as identifier.

Rules for identifier:

* The identifier is combination of _, $, alphabets, digits. * Identifier should not begin with digit, alphabets, _, $. * Identifier cannot have any space.

* Keywords of java cannot be used as identifiers.

* There is no restriction on the length of the identifier but recommended not to use more than 16 characters.

* The names of the identifier must be meaningful & appropriate to the application.

Ex:

int x = 25; Valid but not recommended int age = 25; Valid & recommended

(15)

Structure of java program:

 package statement import statement class<className> { Variables Methods

Public static void main(String[] args) {

Statements }

}

* The package statement is an optional statement. A java program can contain atmost one  package statement. The package statement should be first executable statement in a java  program.

* The import statement is an optional statement. A java program can contain any no of import statements. The import statement must be specified after the package statement before the class. * Java program can contain any no of classes. Every class can contain variables & methods which are together called as members of the class. A class can contain any no of variables & any no of methods.

(16)

* The main method can contain any no of statements. A java program can have any no of commands and they can be specified anywhere in the program. The comments are non-executable statement of java program.

Procedure to Develop, Save, Compile & Execute java program:

Step1: Develop a java program. We require an editor like notepad, wordpad, vi editor etc. Class FirstProgram{

Public Static Void Main(String[] args){

System.out.println(“Welcome to java@inetsolv”); }

}

Step2: Saving a java program.

* A java program can be saved with any name but extension of java program must be java. Syntax: Firstprg.java

Step3: Compiling a java program.

To compile a java program we require a command prompt and we use javac command. Syntax: javac filename/programme with extension

Ex: javac firstprogram.java

When a java program is compiled the compiler will check whether java code is valid or not, if valid then compiler generates .class file which contains byte code.

Step4: Executing a java program.

To execute a java program we require a command we use java command .class file generated by compiler will be provided to the JVM for execution.

Syntax: java classname without extension Ex: java Firstprogram

(17)

 To develop a java application we need to install java s/w. The java language is an open source & freeware which can be downloaded free of cost.

 Once the java s/w is installed then we need to set the path. The path is called as an environment variable. The operating system variables are called as environment variables.

 The path variable should contain address or the location where the java is installed.

Syntax:

Set PATH = java installation folder

Set PATH = c:\program files\java\jdk1.6.0_12\bin;

* Setting the path means proving the address to java installation to OS.

Program 2:

Class secondprogram{

Public static void main(String[] arg){ System.out.println(“this is my second”); System.out.println(“java program”); System.out.println(“at inetsolv”); }

}

Java Coding Conventions (Hungarian Notations)

Every predefined class, predefined method, variable follow java coding conventions and we are also recommended to follow the same coding conventions. It is always a good programming practice for developing applications following the conventions.

1. Conventions for a Class:

A class name can contain any no of words. The first letter of every word should  be specified in uppercase.

(18)

2. Conventions for a Interface:

Interface name can contain any no of words. The first letter of every word should  be specified in uppercase.

Ex: Runnable WindowListener MyInterface.

3. Conventions for a Method:

A method name can contain any no of words. The first letter of every word should  be specified in lowercase. The first letter of remaining words if available should be specified in

uppercase.

Ex: main() tocharArray() areaOfTheCircle()

4. Conventions for a Variable:

The variable name should be any no of words. The first letter of every word should be specified in lowercase. The first letter of remaining words if available should be specified in uppercase.

Ex: length breadthOfRectangle numberOfStudents

5. Conventions for a Constant:

The constant name should be any no of words. All the letters of all words should  be specified in lowercase. It contains multiple words separated them by underscore.

Ex: MAX_VALUE MIN_PRIORITY

6. Conventions for a package:

The package name can contain any no of words. It should be specified completely in lowercase.

Ex: java.lang java.io pack1.pack2

Note: The keywords of java should be specified in lowercase.

(19)

Operators

* Any symbol that is used for performing an operation will be called as an operator. * The values on which the operator performs the operations will be called as operands.

* Based on the no of operands the operator considers they are classified into following categories.

1. Unary Operators:

These operators will perform operations on single operand. 2. Binary Operators:

These operators will perform operations on two operands. 3. Ternary Operators:

These operators will perform operators on three operands.

* The operators of java language are classified into various categories based on task they  perform.

1. Arithematic Operators:

These operators can be used for calculating mathematical operations. The various arithematic operators are

i. Addition (+) ii. Subtraction (-) iii. Multiplication (*) iv. Division (/)

v. Modulus (%)

* If both operands are of integer type the result will be integer. * If any one of operand is of float type the result is float.

(20)

Ex: 7 + 2 = 9 7 - 2 = 5 7 * 2 = 14

7 / 2 = 3 or 7 / 2.0 = 3.5 7 % 2 = 1

* An arithematic expression will be evaluated from left to right. int x=10; O/P : 10

int y=x * 3 – 2; O/P : 28

* We can change order of evaluation by changing pair of parenthesis. int x=10; O/P : 10

int y=x * (3 – 2); O/P : 10

* The arithematic expression will be evaluated from left to right. If operators have same  precedence otherwise evaluate the higher precedence operators first and then lower precedence

operators.

* The arithematic operators

* / %  higher precedence + -  lower precedence Ex: int x=10; O/P: 10

int y=x * 5 / 2; O/P : 25 Ex: int x=10; O/P: 10

int y=x - 5 / 2; O/P : 8

2. Unary Operators:

These operators will perform operations on single operand. The various unary operators are -, ++, --.

i.Unary Minus (-):

Converts positive to negative & negative to positive. Ex: int temp=23;

int temp= -23; int temp= -(-23);

(21)

ii. Increment Operator (++):

This operator will increment value by 1.Based on the position of increment operator the increment operator is classified into two types.

a) Pre-increment operator:

If increment operator is placed before the variable is called pre-increment operator (++x). The pre-increment value will use the value after increasing it.

b) Post-increment operator:

If increment operator is placed after the variable is called post-increment operator (x++). The post-increment value will use the value before increasing it.

ii. Decrement Operator (++):

This operator will decrement value by 1.Based on the position of decrement operator the decrement operator is classified into two types.

a) Pre-decrement operator:

If decrement operator is placed before the variable is called pre-decrement operator (--x). The pre-decrement value will use the value after decreasing it.

b) Post-decrement operator:

If decrement operator is placed after the variable is called post-decrement operator (x--). The post-decrement value will use the value before decreasing it.

Ex:

Class Operators {

Public static void main(String[] args){

int a=7; //8 9 int b=++a; //8 7 6 int c=b--; //8 7 int d=a++ + --b - --c; //8 + 6 - 7 7 System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } }

(22)

* The increment & decrement operators can be applied to all numeric data types. The numeric data types are byte, short, int, long, double, float and char.

* Increment & decrement operators can be applied to only variables. * Increment & decrement operators cannot be nested.

Ex: (++(++a));

3. Assignment Operators:

This operator is used for assigning value to a variable. The assignment operator is =. * This operator will copy value from right to left.

* On the right side we can specify either a value (or) variable (or) an expression but left side we can specify only variable.

x=5 y=x z=x + y

* If the assignment operator is combined with other operator it is called compound assignment operators.

+= , -= , *= , /= , %= . Ex: x=x+3 x+=3

y=y-2 y-=2

4. Relational Operators:

These operators can be used for comparing the values. These operators are also called as comparision operators.

The various relational operators are >, >=, <, <=, ==,! =. * Using the relational operators we can create conditions.

** The result of all relational operators is of boolean type. If the condition is satisfied the result is true otherwise false.

Rules:

* The relational operators <, <=,>,>= can applied to any combination of only numeric types. * The relational operators ==,!= are also called equality operator .The equality operator are applied to any combination of integer or boolean type.

(23)

5. Logical Operators:

These operators are used for combining or complementing result of a condition. The various logical operators are &, &&,|, ||, ^, !.

* The result of all logical operators is of boolean type. i.e. Either true (or) false.

& (Single Ampercent)

This operator is used for combine multiple conditions.

Syntax: cond1 & cond2

* The result of & operator will be true only when all the conditions are true. * The & operator will evaluate all the conditions then decide the result.

&& (Double Ampercent)

This operator is used for combine multiple conditions.

Syntax: cond1 && cond2

* The result of && operator will be true only when all the conditions are true.

** The && operator will evaluate first condition. If result of first condition is false then it will skip the evaluation of remaining conditions and provide result as false.

** If the result of first condition is true then it will evaluate remaining conditions and then decide the result.

** The double ampercent(&&) operator can be used to improve performance of application only when result of first condition is false.

(24)

| (Single Pipe)

This operator is used for combining multiple conditions

Syntax: cond1 | cond2

* The result of single pipe operator will be true if atleast one of the condition is true. * The single pipe operator will evaluate all the condition and then decide the result.

|| (Double Pipe)

This operator is used for combining multiple conditions.

Syntax: cond1 || cond2

* The result of double pipe operator will be true if atleast one of the condition is true.

* The single pipe operator will evaluate the first condition if the result of first condition is true then it will skip the evaluation of remaining conditions provides the result as true.

* If the result of the first condition is true then it will evaluate the remaining conditions.

* The double pipe operator will improve the operator sometimes when the result of first condition is true.

^ (Exclusive OR)

Used for combining multiple condition.

Syntax: cond1 ^ cond2

* The result of ^ operator will be true if the result of the condition are different.

! (Not)

This operator will complement the result of condition.

(25)

6. Bitwise Operators:

These operators will perform operations on bits of an number. The various bitwise operators are ~, &, |, ^, >>, <<, >>>.

~ (Tilde):

This operator will convert bits from one to zeros and 0’s to 1.

Ex: ~ (Negation operator) (Tilde)

2’s compliment = 1’s compliment + 1

 ~x = - (x + 1)

& (Bitwise &):

This operator will perform operation on bitwise of a number.

| (Bitwise |):

(26)

^ (Bitwise ^):

This operator will perform operation on bits of a number.

<< (Left Shift)

This operator will shift bits of a number towards left side by the specified no of  positions.

Ex:

(27)

>> (Right Shift)

This operator will shift bits of a number towards right side by the specified no of  positions.

Ex:

* Shifting the bits of a number towards right side by 1 position dividing number by 2.

>>> (Unsigned Right Shift):

This operator will shift bits of a number towards right side by the specified no of  positions.

Diff between >> and >>>?

*When the bits of a number are shifted towards right side by using >>,the sign bit will be copied as it is into the resultant.

i.e., the positive input will give positive output & negative input will give negative output.

* When we shift bits of a number towards right side by using >>>,we always insert bit 0 into the signed bit.

(28)

Rules for logical operator:

* Logical operators can be applied to combination of boolean type.

* Bitwise operators can be applied to an combination of numbers without decimal point. (Byte, Short, int, long, char)

* The operators &, |, ^ can be applied any combination of boolean types or any combination of numeric types with decimal points.

7. Conditional Operator: (?:)

This operator can perform task based on result of a condition. The condition operator is ?:

Syntax: cond ? exp1 : exp2

This operator will be called as ternary operator. If the result of condition is true then it will evaluate exp1 & if result of condition is false then it will evaluate exp2.

Ex: max = (x > y)? x : y

Diff = x > y ? x –  y : y –  x

* Conditional operator can be nested.

Ex: System.out.println(2<3?(2>3?:”hai”:”hello”):”bye”);

8. New Operator:

 New operator is used for creating an object of a class means allocating memory for members of class in the heap memory.

Ex: Class Sample{ }

Sample s = new sample();

* For every class in java language we can create any no of objects.

* Using new operator we can create object for any predefined or user defined class. * S is called reference variable because they point to refer to object of the class. * The name of the reference variable can be any valid java identifier.

(29)

9. Dot (.) Operator:

The dot operator can be used for accessing the members(variables,methods) from a class from a package.

className.variable reference.variable

className.method reference.method

(30)

Control Statements

The statements of a java program will always be executed in sequential order. If we do not want to execute the statements in a sequential order then we need to take the help of control statements.

The control statements will help the programmer to decide the flow of execution in a program.

The control statements are classified into following categories. 1. Conditional Statements 1.1 if-else statement 1.2 Switch statement 2. Iterating Statements 2.1 for loop 2.2 while loop 2.3 do-while loop 2.4 for-each loop 1. Conditional Statements:

These statements can execute a group of statements based on a condition or a value.

1.1 If else statement:

The if-else stmt can be used for executing a group of statements based on condition. Syntax: if(condition){ Stmt1 } else { stmt2 }

* If the condition is satisfied then if block will be executed and if the condition is not satisfied then execute else block.

(31)

Ex:

Class IfElseDemo {

Public static void main (String [] args) { int n=2; if (n%2=0) { System.out.println(“Even Number”); } else { System.out.println(“Odd Number”); } } } Rules:

* Specifying condition to the if statement is mandatory and it should be only Boolean type. * Specifying an else block is optional.

* Specifying flower braces is optional. If we do not specify flower braces then it will consider only one statement and that one statement is mandatory. If we want to consider multiple stmts then specify the flower braces is mandatory and within the flower braces we can specify any no of stmts (0 or more).

* In if-else stmt we can execute exactly one block either if block or else block. There is no chance of slipping both the blocks and no chance of executing both the blocks.

1.2 Switch statement:

(32)

Syntax:

Switch (argument) {

Case label 1: statement1;  break; Case label 2: statement2;

 break; Case label 3: statement3;

 break; default: statement; }

* If an application contains less no of options then use if else. But if an application contain multiple options then recommended to use switch statement because it improves the readability of the code.

Ex:

Class SwitchDemo{

Public static void main(String[] args){ int ch=3;

Switch(ch){

Case 1: System.out.println(“first choice”);  break;

Case 2: System.out.println(“second choice”);  break;

Case 3: System.out.println(“third choice”);  break;

Case 4: System.out.println(“fourth choice”);  break;

default: System.out.println(“wrong choice”); }

} }

(33)

Class SwitchDemo {

Public static void main (String[] args) { int ch=3; if(ch==1){ System.out.println(“first choice”); } elseif(ch==2){ System.out.println(“second choice”); } elseif(ch==3){ System.out.println(“third choice”); } elseif(ch==4){ System.out.println(“fourth choice”); } else{ System.out.println(“wroong choice”); } } } Rules:

* Specifying the argument to switch stmt is mandatory and it should be either byte type, short type, char type or int type.

* Specifying the case & default both are optional.

* Specifying the flower braces to the switch stmt is mandatory.

* The default stmt can be specified within the switch block. Generally the default stmt will be specified after all the cases.

(34)

* A switch stmt can contain atmost one default stmt.

* The case labels must be unique. Most not be empty and must not be repeated.

PROGRAM: To read data from keyboard. import java.io.*;

class ReadData{

Public static void main (String[] args) Throws IOException{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter first number:”);

String s1=br.readline(); int a=Integer.parseInt(s1);

System.out.print(“Enter second number:”); String s2=br.readline();

int b=Integer.parseInt(s2);

System.out.print(“sum:”+(a+b)); }

}

Ex:Program to write the biggest number using If Else condition. class IfElseDemo

{

 public static void main(String[] args) { int a=10, b=30, c=20, d=8; if((a>b)&(a>c)&(a>d)) { System.out.println("a is big); } elseif((b>c)&(b>c)&(b>d)) {

(35)

System.out.println("b is big); } if((c>a)&(c>b)&(c>d)) { System.out.println("c is big); } else { System.out.println("d is big); } } } O/P: b is big

Ex: Write a program to perform mathematical calculations using switch statement. Class SwitchDemo{

Public static void main(String[] args){ int a=8, b=4, c; int ch=3; Switch(ch){ Case 1: c=a+b; System.out.println(“sum is:”+c);  break; Case 2: c=a-b; System.out.println(“subtraction is:”+c);  break; Case 3: c=a*b; System.out.println(“multiplication is:”+c);  break; Case 4: c=a/b; System.out.println(“division is:”+c);

(36)

  break; } }

}

O/P: multiplication is: 32

* Switch argument & continues until it encounters a break statement (or) teachers end of the switch statement.

* The break statements is a transfer statement which will transfer from inside switch to outside. So that it stops (or) skips the execution of remaining cases. So that remaining statements are not executed.

* Replacing switch with else if ladder.

Class SwitchDemo{

Public static void main(String[] args){ int ch=2; if(ch==1){ System.out.println(“first choice”); } if(ch==2){ System.out.println(“second choice”); } if(ch==3){ System.out.println(“third choice”); } if(ch==4){ System.out.println(“fourth choice”); } else{ System.out.println(“wrong choice”); }

(37)

} }

O/P: Second choice

Replacing switch with else if ladder is not recommended to reduce the readability of the  program.

Iterating statements:

The iterating statements can be used if we want to execute a group of statements repeatedly multiple times.

1. For Loop:

Purpose: A for loop has to be used if we want to execute a group of statements multiple times & it should be used when we know the exact number of iterations.

Syntax:

* Program to write multiplication table using for loop: Class forDemo{

 public static void main(String[] args) {

int n=6;

for(int i=1; i<=10; i++){

System.out.println(n+"*"+i+"="+(n*i)); }

} }

(38)

Rules:

* All the three sections (initialization, condition, inc/dec) of for loop a re optional. * Specifying the section seperators (semicolons) is mandatory.

Ex: for(;;)

* If we do not specify initialization, inc/dec then the compiler will not provide any initialization & will not provide inc/dec, but if we do not specify any condition then compiler will provide a  boolean value “true”.

for(;true;)

* for(;;) –  infinite loop.

* The initialization & inc/dec section can contain any valid java statement but the condition section must be of only boolean type.

* The initialization section can contain multiple initializations separated by comma, and all the initializations must be of the same type & the datatype must be specified only one time.

* The inc/dec section can contain multiple inc/dec separated by comma.

* The condition section can contain multiple condition which has to be combined using logical operators. Use only 5 operators (&, &&, |, ||, ^) but not use (!) operator this is complementing not combining the condition.

* All the three sections of for loop are independent. For(i=1; j<=6; k++)

* Specifying the flower braces is optional. If we do not specify the flower braces, it will consider only one(first) statement & that statement is mandatory. If we want to consider multiple statements specifying the flower braces is mandatory & within the flower braces we can specify any number of statements.

* The variable that is declared inside a for loop can be used in for loop.

Even Numbers from 1 to 100:

class EvenMumbers {

 public static void main(String[] args) {

for(int n=2; n<=100; n++) {

(39)

  if(n%2==0) { System.out.println(n); n++; } else { System.out.println(“odd numbers”); } } } } 2. while loop:

While loop can be used for executing a group statements responsibility multiple times. The while loop should be used when we don’t know the exact no of iterations.

Syntax: while(condition) {

Statements }

*Multiplication table using while loop: Ex: class WhileDemo

{

 public static void main(String[] args) {

int n=8, i=1; while(i<=10) {

(40)

  i++; } }

} Rules:

* For a while loop, specifying the condition is mandatory and it must be of boolean type.

* In a while loop, specifying the flower braces is optional. If we donot specify the flower braces, will consider only one statement & that one statement is mandatory.

* If we want to consider multiple statements then specifying the flower braces is mandatory. Within the flower braces, we can specify any number of statements.

** Every statement in a java program has to be executed at some point of time. If the control is unable to reach any statement in the program then the compiler would raise an error called “unreachable statement”.

do-while loop:

The loop can be used for executing a group of statement repeatedly multiple times. This loop should be used when we donot know the exact no of iterations.

Syntax:

do {

Statements } while(condition);

Program: To write multiplication table using do while loop. class DoWhileDemo

{

 public static void main(String[] args) {

int n=8, i=10; do

(41)

  System.out.println(n+"*"+i+"="+(n*i)); i--;

}while(i>=1); }

}

Difference between while & do-while loop?

* In a while loop, the statements will be executed after the condition is checked. Where as in a do-while loop, the statements will be executed before the condition is checked.

* In a while loop, if the condition is false for the first time then the statements will not be executed where as in a do-while loop, if the condition is false for the first time then the statements will be executed for one time.

* In a while loop, the statements will be executed for 0 (or) more times. In a do-while loop, the statements will be executed for 1 (or) more times.

The loops can be nested:

class NestedloopDemo {

 psum(String[] args) {

for(int i=1; i<=5; i++) { for(int j=1; j<=5; j++) { System.out.println("*"); } System.out.println(); } } }

(42)

O/P: * * * * * * * * * * * * * * * * * * * * * * * * * *ASSIGNMENT * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Transfer Statement:

The transfer statement can be used for transferring the control from one location to another location.

1. Break Statement:

The break statement can be used either in switch (or) in loops. The purpose of  break statement in switch is to transfer the control from inside the switch to outside the switch.

So that it skips the execution of remaining cases.

The purpose of break statement in a loop is to transfer the control from inside the loop to outside the loop so that it skips the execution of remaining iterations.

Ex:

class BreakDemo {

 psum(String[] args) {

(43)

int sum=0, capacity=234; for(int i=1;i<=10;i++) { System.out.println(i); sum=sum+i; if(sum>=capacity)  break; } System.out.println(sum); } } O/P: 1 2 3 ' ' ' 13

sum=--Alternative code for previous ex using while loop:

class BreakDemo {

 psum(String[] args) {

int sum=0, capacity=234; while(sum<capacity) {

System.out.println(i); sum=sum+i;

(44)

}

System.out.println(sum); }

}

ASSIGNMENT:

Print 100 prime numbers from using loops.

Sum of digits of an number

Reverse of a number  * * * * * * * * * * * * * * * class pyramid1 {  psum(String[] args) {

for(int i=1; i<=5; i++) { for(int j=1; j<=i; j++) { System.out.println("*"); } System.out.println(); } } }

(45)

 * * * * * * * * * * * * * * * class pyramid2 {  psum(String[] args) {

for(int i=1; i<=5; i++) { for(int j=1; j<=5; j++) { if(i<=j) System.out.println("*"); } else { System.out.println("-"); } System.out.println("-"); } System.out.println(); } } }

(46)

2. Continue Statement:

The continue statement can be used for skipping the current iteration & continuing with the next iteration.

Ex:

class continueDemo {

 psum(String[] args) {

for(int i=1; i<=10; i++) { if(i==7|i==3) continue; System.out.println(i); } } } O/P: 1 2 4 5 6 8 9 10

(47)

ARRAYS

Array:

If an application requires multiple values then we can store those multiple values  by declaring multiple variables in a program. If the no of variables are increased in the program

then the code size will increase & it will reduce the readability of the code.

* To reduce the code size & to improve the readability of the code, we take the help of the concept called an “Array”.

* An array is a derived data type using which we can store multiple values. The arrays are classified into two types.

1. Single Dimension Array 2. Multi Dimension Array

1. Single Dimension Array:

Single Dimension Array can be used for representing a group of values either a single row (or) single column.

Syntax:

datatype arrayname[];

* To represent an array we take the help of square braces[]. Each pair of square braces represents one-dimension.

Rules:

* The pair of square braces can be specified either before the array name (or) after the array name.

int rollNo[]; float[] percent; char [] grade;  boolean result[];

* We must not specify the size of the array at the time of array declaration  boolean result[5];

* Percent is an array name where we can store multiple values of float datatype. * The name of the array can be any valid java identifier.

(48)

* Syntax for creating an array. We can use any way of both the two types. 1. datatype arrayname[] = new datatype[size];

or 2. datatype arrayname[];

arrayname = new datatype[size]; Ex: 1. int arr[] = new int[5];

or 2. int arr[];

arr = new int[5];

* At the time of array creation, specifying the size of the array is mandatory & it should be of either byte (or) int (or) char type.

Ex: byte x = 10; int y = 10; long z = 10;

int[] arr1 = new int[x]; //valid because of byte type int[] arr2 = new int[y]; //valid because of int type int[] arr3 = new int[z]; //invalid because of long type int[] arr4 = new int[10]; //valid because of int type

int[] arr5 = new int[-10]; //invalid [ Negative array size exception] int[] arr6 = new int[1.0]; //invalid because of float

int[] arr7 = new int[‘z’]; //valid because of char int[] arr8 = new int[0]; //valid but no result

int[] arr9 = new int[]; //invalid because of boolean

int[] arr10 = new int[]; //invalid because of size is missing

(49)

arrayname[index] = starting address of array + index * size of array type

arr[0] = 1000 + 0 * 4 = 1000 arr[1] = 1000 + 1 * 4 = 1004 arr[6] = 1000 + 6 * 4 = 1024

* When an array is created, the memory for that array will be allocated in continuous memory locations. The allocation of the memory will be based on type of the array & size of the array. * An array is a collection of multiple elements & to access those elements we take the help of index positions.

* The index of an array always starts with ‘0’.

* The range of the index will be 0 to [size-1] why starts with ‘0’ means to reduce the wastage of memory of ‘0’ if they starts with “1”.

* Once the memory for the array is allocated, all the elements in that array will be initialized automatically with default values of the array type.

* Every array is internally an object which provides a variable called “length” which will specify the size of the array.

Syntax for accessing the array elements:

arrayname[index]

Syntax for assigning the array elements:

arrayname[index] = value;

(50)

Note:

If we specify an index position which is outside the range of the array index then we get a runtime error called as “ArrayIndexOutOfBandsException”.

for each loop (or) Enhanced for loop:

This loop is designed to work on arrays(collections). It is introduced in 1.5 version of java.

Syntax:

for(Variable declaration : arrayname) {

Statements }

Rules:

* The declaration of the variable in for each loop must be same as that of the array type. Class ArrayDemo{

Psum (String[] args){ Int[] arr;

arr = new int[5];

System.out.println(arr[0]); System.out.println (arr[1]); System.out.println (arr[2]); System.out.println (arr[3]); System.out.println (arr[4]); arr[0] = 12; arr[1] = 23; arr[2] = 34; arr[3] = 45; arr[4] = 56;

for(int i=0; i<arr.length; i++){ System.out.println (arr[j]); }

(51)

for(int x : arr){ System.out.println (x); } } } Example: Class Student{ Psum(String[] args){ int marks[];

marks = new int[5];

marks[0] = 99; marks[1] = 100; marks[2] = 94; marks[3] = 39; marks[4] = 90; int total = 0;

 boolean result = true;

for(int i=0;i<marks.length;i++){

System.out.println("subject"+(i+1)+"marks:"+marks[i]);

total = total + marks[i]; if(marks[i]<35)

 boolean = false; }

System.out.println("Total:"+total); int avg = total/marks.length;

(52)

  if(result) { if(avg>=75){ System.out.println("grade:"+Distinction); } else if (avg>60){ System.out.println("Grade:"First class); } else if (avg>50){ System.out.println("Grade:"Second class); } else { System.out.println("Grade:"Third class); } } else { System.out.println("Welcome Again"); } } }

Declaring Creating & Initializing the array elements in a single line: Syntax: datatype[] arrayname = {list of values};

Ex: int[] arr = {11,45,21,38,43,25};

With in the flower braces, we can specify any no of values separated by a comma.

* When we are declaring, creating & initializing the array elements in a single line then we must not specify the size of the array. The size of the array will be decided automatically based on number of elements specified within the flower braces.

(53)

int[] arr = {11,45,21,53,72,81}; 1

double[] arr = {10.5,4.8,3.9,11.5,13.3}; char[] ch = {‘a’, ‘b’, ‘c’,’d’};

Int[] arr; 2

arr = new int[6]; 3

arr[0] = 11; 4 arr[1] = 45; 5 arr[2] = 21; 6 arr[3] = 53; 7 arr[4] = 72; 8 arr[5] = 81; 9

* Instead of using 2 to 9 we can directly use 1.

Multi Dimension Arrays:

Multi dimension arrays in java are represented as array of arrays.

Syntax for declaring & creating a 2-D array:

datatype arrayname[][] = new datatype[size1][size2]; (or)

datatype arrayname[][];

arrayname = new datatype[size1][size2];

Rules:

* At the time of array declaration we can specify the pair of square braces either before array name (or) after the array name.

int arr1[][]; int []arr2[];

int [][]arr3; //All are valid. int[] arr4[];

(54)

` int[][] arr5; int[][] arr6;

* At the time of array declaration, we must not specify the size of the array.

* At the time of array creation, specifying the first dimension is mandatory & the remaining dimensions are optional.

int [][]arr = new int[3][4]; (or)

int [][]arr;

arr = new int[3][4];

* In multi dimensional array, the top level arrays will contain address of bottom level arrays. * In a multi dimensional array, only the last level will contain values & remaining all top levels will contain addresses.

* The bottom level arrays can contain either same number of elements (or) different number of elements.

int arr[][] = new int[3][4]; (or)

int[][] arr = new int[3][]; arr[0] = new int[4]; arr[1] = new int[4]; arr[2] = new int[4];

(55)

 int[][] arr = new int[3][]; arr[0] = new int[3]; arr[1] = new int[2]; arr[2] = new int[4];

 int [][][] arr;

arr = new int[3][][]; arr[0] = new int[2][]; arr[0][0] = new int[2]; arr[0][1] = new int[3]; arr[1] = new int[3][2]; arr[2] = new int[2][1];

(56)

Declaring Creating & Initializing the array elements in a single line:

int [][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; double [][] arr = {{1.1,2.2,3.3},{4.4,5.5,6.6,7.7}}; Ex:

Class Test{

Psum (String[] args){

int[][] arr = {{1,2,3},{4,5,6},{7,8,9}}; for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[i].length;j++){ System.out.println(arr[i][j]+""); } System.out.println(); } for(int[] x:arr){ for(int y:x){ System.out.println(y+""); } System.out.println(); } } }

Command Line Arguments:

The values that we pass into the program at the time of execution(runtime) are called as command line arguments. The command line arguments can be used for passing the values dynamically into the program & they can be used for avoiding “hardcoding”.

Hardcoding is the process of passing values to the variables with in the program. It is recommended not to use hardcoding in a program.

(57)

class Addition {

 public static void main(String[] abc){ int a = Integer.parseInt(abc[1]); int b = Integer.parseInt(abc[1]); System.out.println(a+b); } }  Java Addition.java Java Addition 11 22 o/p: 33 Java Addition 33 44 o/p: 77 Java Addition 55 66 o/p: 121

* The command line arguments will be passed at the time of execution, at the command prompt & after the class name.

* We can pass any no of values & any type of values separated by a space.

* The command line arguments that we pass will be stored into the string array of the main method.

* As a programmer, we are supposed to declaring the array i.e., we specify the array type & array name.

* The creation of the array is done by JVM & array size will be decided by JVM based on the no of arguments passed. Once the array is created, the arguments will be assigned into the array elements.

String abc[]; //Done by the programmer in main method abc = new String[2];

abc[0] = “11”; abc[1] = “22”;

* If we do not pass any arguments then JVM will create an array of size “0”. abc = new String[0]; //Where we can store ‘no’ values

(58)

* The creation of the array & the assignments of the values will be performed by the JVM just  before calling the main method.

* We can pass any type of values as command line arguments which will be stored in string format. If we want to use those values in our program then we can convert the values from string type to all primitive types except character, which is called as “parsing”.

Ex: Integer.parseInt() Float.parseFloat() Double.parseDouble() Long.parseLong() Boolean.parseBoolean() Short.parseShort() Byte.parseByte()

Why should the main method take string array as the parameter?

If we pass int array to the main method then we can pass only integers, if we pass double array to the main method, then we can pass only double, floating point values, if we pass boolean array then we can pass boolean values but if we pass string array then we can pass integers, floating points, boolean, character values. We can convert all values except character.

Program to read data from keyword:

import java.io.*;

class Addition {

 public static void main(String abc[])throws IOException {

BufferReader br = new BufferReader(new InputStreamReader(System.in)); System.out.println("Enter First Number"); string fno = br.readline();

(59)

int

int a a = = Integer.parseInt(fno);Integer.parseInt(fno);

System.out.println("Enter Second Number"); System.out.println("Enter Second Number"); string sno = br.readline();

string sno = br.readline(); int b =

int b = Integer.parseInt(sno);Integer.parseInt(sno);

System.out.println("sum:"+(a+b)); System.out.println("sum:"+(a+b)); } } } }

(60)

String

String

* The string is a predefined used

* The string is a predefined used for storing group of characters.for storing group of characters. * The string class objects can be created in two ways.

* The string class objects can be created in two ways. i. by using new operator

i. by using new operator

String str = new String(“hello”); String str = new String(“hello”);

ii. by enclosing group of characters directly within double

ii. by enclosing group of characters directly within double codes.codes. String str = “hello”;

String str = “hello”;

* The string objects created by both the mechanisms are immutable objects. Once the string * The string objects created by both the mechanisms are immutable objects. Once the string object is created which we cannot modify the content of the object, but the reference of the string object is created which we cannot modify the content of the object, but the reference of the string object can be modified.

object can be modified.

String s1 = new String(“hai”); String s1 = new String(“hai”); s1 = new String(“bye”); s1 = new String(“bye”);

Difference between two mechanisms of creating string object?Difference between two mechanisms of creating string object?

1. String object created by new operator 1. String object created by new operator

i. location:

i. location: The string object are created by using new operator then they are used in newThe string object are created by using new operator then they are used in new memory.

memory.

ii. Allocation:

ii. Allocation: If we are storing string objects in heap memory then it will never verifyIf we are storing string objects in heap memory then it will never verify whether the heap contains objects with same content or not, it will always create a new object. whether the heap contains objects with same content or not, it will always create a new object.

String s1 = new String(“hai”); String s1 = new String(“hai”); s1 = new String(“bye”); s1 = new String(“bye”); String s2 = new String(“bye”); String s2 = new String(“bye”);

(61)

Unreferenced Object: Unreferenced Object:

If object does not have any live reference i.e., if an object is not pointed or If object does not have any live reference i.e., if an object is not pointed or referenced by any vtariable then that object will be called as Unreferenced Object.

referenced by any vtariable then that object will be called as Unreferenced Object.

iii. Deallocation:

iii. Deallocation:  If the heap memory contains unreferenced object then it will contain  If the heap memory contains unreferenced object then it will contain garbage collector.

garbage collector.

2. String object created by placing directly in “ ”: 2. String object created by placing directly in “ ”:

i. location:

i. location: If the string content is placed directly within “ ” then they are stored in stringIf the string content is placed directly within “ ” then they are stored in string content pool.

content pool.

ii. Allocation:

ii. Allocation: If string object are placed in string content pool then it will always verify If string object are placed in string content pool then it will always verify whether the string constant pool contains objects with same content or not. If available then refer whether the string constant pool contains objects with same content or not. If available then refer to the existing object otherwise create a new object.

to the existing object otherwise create a new object. String s1 = “hai”; String s1 = “hai”; s2 = “bye”; s2 = “bye”; String s2 = “bye”; String s2 = “bye”;

(62)

iii. Deallocation: If string constant pool contains unreferenced object then it will be deallocated by string constant pool when it is completely filled.

* If a string object is created by using new operator then the string object will be stored in both heap memory location & string memory poll.

* But the reference will point to the object available in heap memory. String str = new String(“hello”);

* If we create a string object b y enclosing group of characters directly within “ ” then we store only in string constant pool.

Methods of String Class: 1. int length():

This method will return the count of no of char available in a string.

Ex:

String str = new String(“java program”); System.out.println(str);

(63)

2. char charAt(int index):

This method will return a character available at specified index position.

Note: The index of a string begins from zero.

Ex:

String str = new String(“java program”); System.out.println(str.charAt(1));

System.out.println(str.charAt(12));

3. String Concat(string):

This method can be used to append the contents of one string to another string.

Ex:

String s1 = new String(“java”); String s2 = new String(“program”); System.out.println(s1.concat(s2)); System.out.println(s1);

System.out.println(s2);

O/P: java program  java

 program

4. int CompareTo(String):

This method can be used for comparing the unicode values of the characters available in the string. This method will do the comparision by considering their case.

S1 < S2 -ve S1 > S2 +ve S1 == S2 0

(64)

5. int CompareToIgnoreCase(String):

This method can be used for comparing the unicode values of the characters available in the string. This method will compare by ignoring their case.

Ex:

String s1 = new String(“A”); String s2 = new String(“a”);

System.out.println(s1.compare(s2));

System.out.println(s1.compareToIgnoreCase(s2));

O/P: -32 0

6. boolean equals(String):

This method can be used for comparing contents of the strings by considering their case.

7. boolean equalsIgnoreCase(String):

This method can be used for comparing contents of the strings by ignoring their case.

Ex:

String s1 = new String(“ABCD”); String s2 = new String(“abcd”); System.out.println(s1.eqals(s2));

System.out.println(s1.equalsIgnoreCase(s2));

O/P: false True

8. boolean startswith(String):

This method can be used to check whether a string begins with specified string or not.

(65)

9. boolean endswith(String):

This method can be used to check whether a string ends with specified string or not.

Note: start with method & ends with methods are case sensitive.

Ex:

String s = new String(“java program”); System.out.println(s.startswith("jav")); System.out.println(s.startswith("JAV")); System.out.println(s.endswith("ram")); O/P:  true false true 10. int indexOf(char):

This method will return the index of the first occurrence of the specified character.

11. int lastindexOf(char):

This method will return the index of the last occurrence of the specified character.

Note: The index of method & last index of method will return -1, if specified character is not available in the string.

Ex:

String s = new String(“java program”); System.out.println(s.indexOf('a')); System.out.println(s.indexOf('p')); System.out.println(s.indexOf('t')); System.out.println(s.lastindexOf('a')); System.out.println(s.lastindexOf('p')); System.out.println(s.lastindexOf('z'));

(66)

O/P:1 5 -1 10 5 -1

12. string replace(char old, char new):

This method can be used for replacing all the occurrence of specified character with new character.

Ex:

String s = new String(“java jug jungle”); System.out.println(s.replace('j','b'));

O/P: bava bug bungle

13. string substring(int index):

This method will retrieve a part of string beginning from specified ind ex position upto the end of the string.

14. string substring(int index, int offset):

This method can be used to retrieve a part of string beginning from specified index position upto the specified offset.

Note: The offset of a string represents a position of a character in a string. * The offset starts from 1.

Ex:

String s = new String(“java program”); System.out.println(s.substring(3)); System.out.println(s.substring(2,9));

O/P: va program ava prog

15. string toLowerCase():

This method can be used to converting contents of string completely to lower case.

References

Related documents

• BlackBerry Enterprise Server and BlackBerry smartphone user configuration • BlackBerry Enterprise Server administration.. • Securing the BlackBerry Enterprise Server environment

Pitch Echo Mono, Stereo Line 6 Original. Added with

Given the restricted use of e-signatures to include internal use only and the requirement that all users must be authenticated to the Authority domain for an e-signature to be

The direct return to Earth is possible with a Delta-launched spacecraft because the Delta and its lander only had to deliver the MAV's dry mass (perhaps 70

This database includes all in- formation publicly available through the CORDIS projects database (CORDIS search 2006) and is maintained by ARC systems research (ARC sys). For

We Treat The Open Group Member’s to be an invited ReGIS Member’s without fee.; We had published in 2014, 24 GIS FORUM Members News Letters “#415 to #438 (Mail

While this paper estimates the debt-service to income ratio for each household, and then, calculates the unweighted average for those households with some form of leverage, the

Chapter 1 Introduction The main objectives of this study are to i derive analytical expressions for the nonlinear Volterra series transfer function of an optical fiber, ii analyze