java basics

64
© 2011 MindTree Limited Slide 1 CONFIDENTIAL: For limited circulation only © 2011 MindTree Limited CONFIDENTIAL: For limited circulation only Programming with Java C2-Orchard

Upload: pendekanti-surendra-kumar

Post on 24-Mar-2016

224 views

Category:

Documents


0 download

DESCRIPTION

Java Basics

TRANSCRIPT

Page 1: Java Basics

© 2011 MindTree Limited Slide 1 CONFIDENTIAL: For limited circulation only © 2011 MindTree Limited CONFIDENTIAL: For limited circulation only

Programming with Java

C2-Orchard

Page 2: Java Basics

© 2011 MindTree Limited Slide 2 CONFIDENTIAL: For limited circulation only Slide 2

● Understand different Java environments

● Understand the Java architecture

● Understand variables, data types and identifiers

● Understand Java language constructs

Objectives

Page 3: Java Basics

© 2011 MindTree Limited Slide 3 CONFIDENTIAL: For limited circulation only Slide 3

Java Technology

Java technology is both a platform and a programming language.

A platform is the hardware or software environment in which a

program runs.

Most platforms can be described as a combination of the operating

system and underlying hardware.

The Java platform differs from most other platforms in that it's a

software-only platform that runs on top of other hardware-based

platforms.

Page 4: Java Basics

© 2011 MindTree Limited Slide 4 CONFIDENTIAL: For limited circulation only Slide 4

● The Java platform has two components:

● The Java Application Programming Interface (API)

● The Java Virtual Machine

Java Platform

Page 5: Java Basics

© 2011 MindTree Limited Slide 5 CONFIDENTIAL: For limited circulation only Slide 5

●Application Programming Interface (API):

●An application programming interface (API) is a particular set of rules and

specifications that software programs can follow to communicate with each

other.

●The Java API offers a wide collection of useful classes ready for use in

your own applications.

Java Platform

Page 6: Java Basics

© 2011 MindTree Limited Slide 6 CONFIDENTIAL: For limited circulation only Slide 6

Java Complete Picture

Page 7: Java Basics

© 2011 MindTree Limited Slide 7 CONFIDENTIAL: For limited circulation only Slide 7

Java Environment

Page 8: Java Basics

© 2011 MindTree Limited Slide 8 CONFIDENTIAL: For limited circulation only Slide 8

Java Runtime Environment

•The Class loader loads all the classes (byte code) : classes from program and

from Java API.

•For every class the type information is stored in Method Area.

•As the program runs the virtual machine places all the objects in heap area.

•The java method invoked will be placed on the stack .

•PC ( program counter) indicates the next instruction to execute.

JVM

Page 9: Java Basics

© 2011 MindTree Limited Slide 9 CONFIDENTIAL: For limited circulation only

Java Execution Process

● Java Source code having an extension “*.java” will be compiled using

Java Compiler.

● The Compiled byte code has “.class” extension.

● The byte code and library files (Java API) will be loaded into JVM by class

loader.

● The execution of byte code takes place in JVM

Page 10: Java Basics

© 2011 MindTree Limited Slide 10 CONFIDENTIAL: For limited circulation only

Variables

● A variable is a storage location and an associated symbolic name which

contains information, a value.

● A programmer can imagine a variable as being a box into which

information can be placed, and the shape of the box (the variables type)

determines what kind of information it can store

A Real world example of a variable:

Imagine a warehouse with lots of storage

bays, tables, shelves, special rooms etc.

These are all places where you can store

something.

Lets imagine we have a crate of Soft-Drinks

in the warehouse.

Where exactly is it located?

We wouldn't say that it is stored 25' 5"

from the north wall and 20' 6" from the

east wall.

Page 11: Java Basics

© 2011 MindTree Limited Slide 11 CONFIDENTIAL: For limited circulation only

Variables

● Another Real world example of a variable:

● Imagine that you are a postal worker. Your job is to sort mail into rows of

boxes

● Each box has an address and a space in which to put the mail.

● Every day the contents of the boxes change as you load and unload

the boxes. On Day 1 the 100 Main Street might contain a magazine.

On Day 2 to the same address it could be Internet-Broadband bill.

● The contents of the box vary frequently, but the addresses

themselves do not vary. 100 Main Street is always 100 Main Street, no

matter what its contents are.

100 Main Street

101 Main Street

102 Main Street

contents

Variables

Page 12: Java Basics

© 2011 MindTree Limited Slide 12 CONFIDENTIAL: For limited circulation only Slide 12

Variables

● Programming Example:

● Circle's circumference : c = 2

C for “circumference" and "r" for

"radius" ]

Given the radius “r” a non-negative number, we get to figure out what

the circumference “c” is. Both “r” and “c” are variables.

The value of “

● Identify the variables in Quadratic Formula:

Page 13: Java Basics

© 2011 MindTree Limited Slide 13 CONFIDENTIAL: For limited circulation only Slide 13

● Variables not only have a value, they have a “type”. All

programming languages have data types.

● Data types help the processor when storing variables or doing

operations on them.

● Strongly typed and Loosely typed:

● Some languages have strict rules about data types. These languages

are called "strongly typed". i.e. you declare a variable as a certain

type, and then cannot change the type

● For example, in Java:

String firstName = “Rahul";

byte age = 15 ;

● “Loosely typed” languages like “JavaScript” and “PHP” have few rules

about data types.

For example, in JavaScript:

var first = “Rahul”; <-- variable “first” is storing String

first = 15; <-- the same variable “first” is now storing integer

Data types

Page 14: Java Basics

© 2011 MindTree Limited Slide 14 CONFIDENTIAL: For limited circulation only Slide 14

● Data Types in Java Programming Language are classified into two main

groups

● Primitive Data Types

● Reference Data Types

● Primitive Data Types: Predefined by the Java language

Reserved keyword

Primitive values do not share state with other primitive values.

All Primitive Data Types have respective Wrapper Classes.

Data types

Page 15: Java Basics

© 2011 MindTree Limited Slide 15 CONFIDENTIAL: For limited circulation only Slide 15

● Integer data types

Data types

0 1 1 1 1 1 1 1

1 0 0 0 0 0 0 0

0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

byte

short

int

max

min

max

min

max

min

s

s

s

S - > Sign bit

Page 16: Java Basics

© 2011 MindTree Limited Slide 16 CONFIDENTIAL: For limited circulation only Slide 16

● The float/double data type

Data types

float double

Variables of this type can have values from -3.4E38 (-3.4 * 1038) to +3.4E38 (+3.4 * 1038) and occupy 4 bytes in memory. Values are represented with approximately 7 decimal digits accuracy.

Variables of this type can have values from -1.7E308 (-1.7 * 10308) to +1.7E308 (+1.7 * 10308) and occupy 8 bytes in memory. Values are represented with approximately 17 decimal digits accuracy.

Page 17: Java Basics

© 2011 MindTree Limited Slide 17 CONFIDENTIAL: For limited circulation only Slide 17

● The boolean type:

● The boolean data type is used for logical values.

● The boolean data type can have two possible values : true or false.

● The boolean is the type returned by all relational operators

● The boolean is the type required by the conditional expressions used

in control statements such as if and for.

● The char data type:

● Character is 16 bits wide in Java.

● Java uses Unicode to represent characters.

● The range of a char is 0 to 65,536.

Data types

Page 18: Java Basics

© 2011 MindTree Limited Slide 18 CONFIDENTIAL: For limited circulation only Slide 18

● Primitive types

● all primitive values can be stored in a fixed amount of memory

(between one and eight bytes, depending on the type)

● Java handles values of the primitive types directly, or by value.

● Reference types

● Array types and Classes are composite types; objects and arrays

contain other values, so they do not have a standard size, and they

often require quite a bit more memory than eight bytes.

● For this reason, Java does not manipulate objects and arrays directly.

Instead, it manipulates objects and arrays through its reference.

● Because Java handles objects and arrays by reference, classes and

array types are known as reference types.

Data types

Page 19: Java Basics

© 2011 MindTree Limited Slide 19 CONFIDENTIAL: For limited circulation only Slide 19

● Array References

● An array in itself is a reference variable. It points to a group of

elements on the heap

Reference type

int[] arr = new int[ ] {1,2,3};

Stack Heap

Page 20: Java Basics

© 2011 MindTree Limited Slide 20 CONFIDENTIAL: For limited circulation only Slide 20

● Identifiers are tokens that represent names of variables, methods,

classes, etc.

Examples of identifiers are: Hello, main, System, out.

● Java identifiers are case-sensitive.

This means that the identifier Hello is not the same as hello.

● Identifiers must begin with either a letter, an underscore “_”, or a

dollar sign “$”.

● Letters may be lower or upper case. Subsequent characters may

use numbers 0 to 9.

Java Identifiers

Page 21: Java Basics

© 2011 MindTree Limited Slide 21 CONFIDENTIAL: For limited circulation only Slide 21

MyVariable

_9pins

$myvariable

My Variable

9pins MindTree_&_Associates

testing1-2-3 _myvariable

This_is_an_insanely_long_variable_name_that_just_keeps_going_and_going

Can you identify legal identifiers from the list?

Page 22: Java Basics

© 2011 MindTree Limited Slide 22 CONFIDENTIAL: For limited circulation only Slide 22

● Keywords are the built-in vocabulary of a language.

● In Java all keywords are lowercase

● You cannot use keywords as identifiers, (names you make up and

then use to describe classes, objects, methods, and variables)

Java Keywords ( Reserved words )

Page 23: Java Basics

© 2011 MindTree Limited Slide 23 CONFIDENTIAL: For limited circulation only Slide 23

● Primitive declarations with assignments:

● int x;

● x = 456;

● byte b = 22;

● boolean exists = true;

● double salary = 52345.22;

● char ch = ‘J’;

● float temperature = 94.5f;

● int y = x;

Variables and data types

Page 24: Java Basics

© 2011 MindTree Limited Slide 24 CONFIDENTIAL: For limited circulation only Slide 24

● What happens when this code is executed?

char c = -1;

● Which of the following lines will compile without warning or error.

float f=1.3;

char c = "a";

byte b=257;

boolean b=null;

int i=10;

Quiz

Page 25: Java Basics

© 2011 MindTree Limited Slide 25 CONFIDENTIAL: For limited circulation only Slide 25

● What is the result of compiling and running the following code?

Quiz

public class Tester {

public static void main(String[ ] args) {

if (true) {

int x = 5;

System.out.print(x);

} else {

++x;

System.out.print(x);

}

}

}

Page 26: Java Basics

© 2011 MindTree Limited Slide 26 CONFIDENTIAL: For limited circulation only Slide 26

Scope of a variable.

package com.mindtree.sample;

public class Example{

/**

* @param args

*/

public static void main(String[] args) {

String str = “This is a local variable”;

}

}

class Employee {

private static int totalCount = 0;

private String firstName;

private int age;

}

•Declared outside methods

but inside class.

•Declared outside methods

but inside class. Denoted by

static keyword.

Class Variable

Instance Variables

•Declared inside methods.

•str is local to the method

main

Local Variable

Page 27: Java Basics

© 2011 MindTree Limited Slide 27 CONFIDENTIAL: For limited circulation only Slide 27

Java Source file structure

/*

* Created on June 1, 2011

*

* First Java Program

*/

package com.mindtree.sample;

import java.lang.System;

import java.lang.String;

/**

* @author Banu Prakash

* © 2011 MindTree Limited.

*/

public class Example{

public static void main(String[] args) {

// print a message

System.out.println("Welcome to Java!");

}

}

• Every Java program includes

at least one class definition.

The class is the fundamental

component of all Java

programs.

Class

Page 28: Java Basics

© 2011 MindTree Limited Slide 28 CONFIDENTIAL: For limited circulation only Slide 28

● Video: HelloWorld_example.swf

● Hello World Java application illustrating the basic java file structure.

● illustrates steps to carry out to run this application:

Setting path and classpath.

Example

Page 29: Java Basics

© 2011 MindTree Limited Slide 29 CONFIDENTIAL: For limited circulation only Slide 29

● IDE (integrated development environment)

● IDEs are designed to maximize programmer productivity.

● IDE typically provides many features for authoring, modifying,

compiling, deploying and debugging software.

● Example of IDE

● Eclipse

● NetBeans

● BlueJ

● JCreator

● Eclipse and Java for Total Beginners

● http://goo.gl/B1JVN (Using the Eclipse Workbench)

● http://goo.gl/ybPGi (Eclipse IDE tutorial)

IDE – An Introduction

Page 30: Java Basics

© 2011 MindTree Limited Slide 30 CONFIDENTIAL: For limited circulation only Slide 30

● Suppose a value of one type is assigned to a variable of another

type.

● Type1 t1;

● Type2 t2 = t1;

● Above statement is valid if

two types are compatible

destination type is larger then the source type

● Example:

int i;

double d = i;

Widening Type Conversion

Page 31: Java Basics

© 2011 MindTree Limited Slide 31 CONFIDENTIAL: For limited circulation only Slide 31

● Narrowing Type Conversion happens when

● two types are compatible

● destination type is smaller then the source type

● Example:

● Java will not carry out type-conversion:

int i;

byte b = i;

● Instead, we have to rely on manual type-casting:

int i;

byte b = (byte) i;

Narrowing Type Conversion

Page 32: Java Basics

© 2011 MindTree Limited Slide 32 CONFIDENTIAL: For limited circulation only Slide 32

● Example

int i = 257;

byte b = (byte) i;

System.out.println("Conversion of int to byte.");

System.out.println("i and b " + i + " ," + b); // i and b: 257, 1

double d = 123.456;

System.out.println("\ndouble to int.");

int value = (int) d;

System.out.println("d and value: " + d + " ," + value);

// d and value: 123.456 ,123

Narrowing Type Conversion

Page 33: Java Basics

© 2011 MindTree Limited Slide 33 CONFIDENTIAL: For limited circulation only Slide 33

● Program consists of many statements. Without control flow, the

interpreter would execute these statements in the order they

appear left-to-right and top-to-down.

● Control flow statements in the program determine in which order

the program should be executed.

Control Flow

Page 34: Java Basics

© 2011 MindTree Limited Slide 34 CONFIDENTIAL: For limited circulation only Slide 34

● IF STATEMENT

● In certain solutions, it may be necessary to write code to perform

various actions based on certain criteria. To perform these actions,

Java provides certain decision-making statements such as the if

statement

if-statement has the form:

Conditional Flow Control

if( boolean_expression) statement;

if( boolean_expression ) { statement1; statement2;

}

Page 35: Java Basics

© 2011 MindTree Limited Slide 35 CONFIDENTIAL: For limited circulation only Slide 35

Example:

int balance = 10000;

int amount ;

Scanner in = new Scanner(System.in);

System.out.println("Enter Amount: ");

double amount = in.nextDouble();

if (amount <= balance) {

balance = balance - amount;

}

System.out.print(“Balance: “ + balance);

The if Statement

Page 36: Java Basics

© 2011 MindTree Limited Slide 36 CONFIDENTIAL: For limited circulation only Slide 36

● If you want to perform two different statements depending on the

outcome of a boolean expression. if-else statement can be used

The if-else statement

if( boolean_expression) statement1;

else statement2;

if( boolean_expression ) { statement1; statement2;

} else { statement3; statement4;

}

Page 37: Java Basics

© 2011 MindTree Limited Slide 37 CONFIDENTIAL: For limited circulation only Slide 37

The if-else-if statement

Example:

Scanner scanner = new Scanner(System.in);

System.out.println("Enter magnitude on the Richter scale");

double richter = scanner.nextDouble();

String r = “”;

if (richter >= 7.0)

r = "Many buildings destroyed";

else if (richter >= 6.0)

r = "Many buildings considerably damaged, some collapse";

else if (richter >= 4.5)

r = "Damage to poorly constructed buildings";

else if (richter >= 3.5)

r = "Felt by many people, no destruction";

else if (richter >= 0)

r = "Generally not felt by people";

else

r = "Negative numbers are not valid";

System.out.println("for richter scale " + richter + " result : " + r);

Page 38: Java Basics

© 2011 MindTree Limited Slide 38 CONFIDENTIAL: For limited circulation only Slide 38

● Switch statements provides a better alternative than if-else-if

when the execution follows several branches depending on the

value of an expression

● Syntax:

switch (expression) {

case value1:

statement1;

break;

case value2:

statement2;

break;

case value3:

statement3;

break;

default: statement;

}

Switch Statement

Page 39: Java Basics

© 2011 MindTree Limited Slide 39 CONFIDENTIAL: For limited circulation only Slide 39

● Example:

int month = 4; String season;

switch (month) {

case 12:

case 1:

case 2: season = "Winter"; break;

case 3:

case 4:

case 5: season = "Spring"; break;

case 6:

case 7:

case 8: season = "Summer"; break;

case 9:

case 10:

case 11: season = "Autumn"; break;

default: season = “unknown";

}

Switch Statement

Page 40: Java Basics

© 2011 MindTree Limited Slide 40 CONFIDENTIAL: For limited circulation only Slide 40

● If y has the value 5 what will be the value of the variable y after the

following piece of code is executed?

if (y > 0)

y += 2;

● If p has the value 3 and max has the value 5, what will be the value of the

variable max after the following piece of code is executed?

if (p < max) max = p;

● If x has the value 5.0 what will be the value of the variable count after

the following piece of code is executed?

count = 0;

if (x < 0.0)

negsum = negsum + x;

count = count + 1;

Answer this

Page 41: Java Basics

© 2011 MindTree Limited Slide 41 CONFIDENTIAL: For limited circulation only Slide 41

● Java iteration statements enable repeated execution of part of a

program until a certain termination condition becomes true.

● Java provides the following iteration statements:

● while loop

● do while loop

● for loop

● Enhanced for loop [ for-each]

Iteration Statements

Page 42: Java Basics

© 2011 MindTree Limited Slide 42 CONFIDENTIAL: For limited circulation only Slide 42

● Syntax:

● Semantics:

● repeat execution of statement until expression becomes false

● expression is always evaluated before statement

● if expression is false initially, statement will never get executed

The while loop

while (boolean_expression) statement;

while (boolean_expression) { statement;

}

Page 43: Java Basics

© 2011 MindTree Limited Slide 43 CONFIDENTIAL: For limited circulation only Slide 43

● Example: while loop to calculate the factorial of the number 5

int counter = 5;

long factorial = 1;

while (counter > 1) {

factorial *= counter;

counter-- ; }

System.out.println(factorial);

The while loop example

Page 44: Java Basics

© 2011 MindTree Limited Slide 44 CONFIDENTIAL: For limited circulation only Slide 44

● If a component statement has to be executed at least once, the

do-while statement is more appropriate than the while statement

● Syntax:

do {

statement;

} while (condition);

● Example:

int counter = 5;

int factorial = 1;

do {

factorial *= counter;

counter--;

} while (counter > 0);

System.out.println(factorial);

The do while loop

Page 45: Java Basics

© 2011 MindTree Limited Slide 45 CONFIDENTIAL: For limited circulation only Slide 45

● When iterating over a range of values, for statement is more

suitable to use then while or do-while

● Syntax:

for (initialization; termination; increment)

statement;

● initialization statement is executed once before the first iteration

● termination expression is evaluated before each iteration to

determine when the loop should terminate

● increment statement is executed after each iteration

The for loop

Page 46: Java Basics

© 2011 MindTree Limited Slide 46 CONFIDENTIAL: For limited circulation only Slide 46

● The for statement may include declaration of a loop control

variable:

for (int counter = 0;

counter < 10;

counter++) {

Statements;

}

● The variable “counter” does not exist outside the for statement

The for loop

Page 47: Java Basics

© 2011 MindTree Limited Slide 47 CONFIDENTIAL: For limited circulation only Slide 47

● Find if the given number is a prime number.

int num = 14;

boolean isPrime = true;

for (int i=2; i < num/2; i++) {

if ((num % i) == 0) {

isPrime = false;

break; //exit an iterative statement

}

}

if (isPrime) {

System.out.println("Prime");

}

else {

System.out.println("Not Prime");

}

The for loop example

Page 48: Java Basics

© 2011 MindTree Limited Slide 48 CONFIDENTIAL: For limited circulation only Slide 48

● A for each-construct was introduced in JDK 1.5.0.

● It is also referred to as the "Enhanced for Loop"

● Sementics:

for each item in collection

do something to item

● The following method returns the sum of the values in an int array:

// Returns the sum of the elements of array arr

int sum(int[] arr) {

int total = 0;

for (int value : arr) {

total += value;

}

return total;

}

The For-Each Loop

Page 49: Java Basics

© 2011 MindTree Limited Slide 49 CONFIDENTIAL: For limited circulation only Slide 49

● Arrays are the simplest and most common type of structured data.

● An Array contains a group of items that are all of the same type

and that are directly accessed through the use of an array index.

● One-Dimensional array:

● A one-dimensional array is, essentially, a list of like-typed variables.

● To create an array, you first must create an array variable of the

desired type.

● The general form of a one dimensional array declaration is

type var_name[ ];

● For example, the following declares an array named months with the

type “array of int”:

int months[];

Arrays

Page 50: Java Basics

© 2011 MindTree Limited Slide 50 CONFIDENTIAL: For limited circulation only Slide 50

int months[];

● Although this declaration establishes the fact that months is an array

variable, no array actually exists.

● In fact, the value of months is set to null, which represents an array

with no value

Arrays

Stack

months null

Heap

Page 51: Java Basics

© 2011 MindTree Limited Slide 51 CONFIDENTIAL: For limited circulation only Slide 51

● To link months with an actual, physical array of

integers you must allocate one using new and assign it to months.

● This example allocates a 12-element array of integers and links them to months.

int months = new int[12];

● You can access a specific element in the array by specifying its index within square brackets.

● For example, this statement assigns the value 28 to the second element of months.

● months [1] = 28;

Arrays

Stack

months addr

Heap

12

0

28

0

0

0

0

0

0

0

0

0

0

length

addr: address of physical array of integers

0

1

2

11

3

4

5

6

7

8

9

10

Page 52: Java Basics

© 2011 MindTree Limited Slide 52 CONFIDENTIAL: For limited circulation only Slide 52

● Example:

int months[] = new int[12];

months[0] = 31;

months[1] = 28;

months[2] = 31;

months[3] = 30;

months[4] = 31;

months[5] = 30;

months[6] = 31;

months[7] = 31;

months[8] = 30;

months[9] = 31;

months[10] = 30;

months[11] = 31;

System.out.println("April has " + months[3] + " days.");

Arrays

Stack

addr

Heap

12

31

28

31

30

31

30

31

31

30

31

30

31

0

1

2

11

3

4

5

6

7

8

9

10

months

Page 53: Java Basics

© 2011 MindTree Limited Slide 53 CONFIDENTIAL: For limited circulation only Slide 53

● break

● The break statement causes a loop to terminate through the normal

exit channel; the program resumes execution at the first statement

following the loop.

● continue

● The continue statement rather than causing a loop exit, causes the

program to skip the loop body and continue executing at the beginning

of the next iteration of the loop.

● A continue statement is shorthand for an if-else clause that would

prevent the rest of the loop from being executed.

Exiting Loops early

Page 54: Java Basics

© 2011 MindTree Limited Slide 54 CONFIDENTIAL: For limited circulation only Slide 54

● Example:

int i = 0;

while(i < 100) {

if(i == 10) {

break; // terminate loop if i is 10

}

System.out.println("i: " + i);

i++;

}

System.out.println("Loop complete.");

Exiting Loops early

Page 55: Java Basics

© 2011 MindTree Limited Slide 55 CONFIDENTIAL: For limited circulation only Slide 55

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

System.out.print(i + " ");

if (i%2 == 0) {

continue;

}

System.out.println("");

}

● Output :

0 1

2 3

4 5

6 7

8 9

Continue example

Page 56: Java Basics

© 2011 MindTree Limited Slide 56 CONFIDENTIAL: For limited circulation only Slide 56

outer:

for (int i=0; i< 5; i++) {

for(int j=0; j< 5; j++) {

if(j > i) {

System.out.println();

continue outer;

}

System.out.print(" " + (i * j));

}

}

Output:

0

0 1

0 2 4

0 3 6 9

0 4 8 12 16

Using continue with a label.

Page 57: Java Basics

© 2011 MindTree Limited Slide 57 CONFIDENTIAL: For limited circulation only Slide 57

● A string is a sequence of characters.

● Unlike most of the other languages, Java treats a string as a single

value rather than as an array of characters.

● The String objects are immutable, i.e., once an object of the

String class is created, the string it contains cannot be changed.

● The String Constructors

● The String class supports several constructors. To create an empty

String, you call the default constructor.

For example: String s = new String();

● To create a String initialized by an array of characters, use the

constructor shown here:

● String(char chars[ ])

For example: char chars[ ] = { 'a', 'b', 'c' };

String s = new String(chars);

The String class

Page 58: Java Basics

© 2011 MindTree Limited Slide 58 CONFIDENTIAL: For limited circulation only Slide 58

● String class also provides constructors that initialize a string when

given a byte array

byte ascii[] = {65, 66, 67, 68, 69, 70 };

String s1 = new String(ascii);

System.out.println(s1); // ABCDEF

String s2 = new String(ascii, 2, 3);

System.out.println(s2); // CDE

● String Literals

● You can use a string literal to initialize a String object

String s2 = “MindTree Ltd"; // use string literal

The String class

Page 59: Java Basics

© 2011 MindTree Limited Slide 59 CONFIDENTIAL: For limited circulation only Slide 59

● String Length

String s = new String(“MindTree”);

System.out.println( s.length () ) ; // 8

● Character Extraction: char charAt(int where)

char ch = "abc".charAt(1); // b

● String Comparison

● To compare two strings for equality, use equals( ).

boolean equals(Object str)

● To perform a comparison that ignores case differences, call:

boolean equalsIgnoreCase(String str)

Methods of String class

Page 60: Java Basics

© 2011 MindTree Limited Slide 60 CONFIDENTIAL: For limited circulation only Slide 60

● String Comparison example:

String s1 = "Hello";

String s2 = "Hello";

String s3 = "Good-bye";

String s4 = "HELLO";

System.out.println(s1 + " equals " + s2 + " -> " +

s1.equals(s2)); // Hello equals Hello -> true

System.out.println(s1 + " equals " + s3 + " -> " +

s1.equals(s3)); // Hello equals Good-bye -> false

System.out.println(s1 + " equals " + s4 + " -> " +

s1.equals(s4)); // Hello equals HELLO -> false

System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +

s1.equalsIgnoreCase(s4)); // Hello equalsIgnoreCase HELLO -> true

Methods of String class

Page 61: Java Basics

© 2011 MindTree Limited Slide 61 CONFIDENTIAL: For limited circulation only Slide 61

● int compareTo(String str)

● A string is less than another if it comes before the other in

dictionary order. A string is greater than another if it comes after

the other in dictionary order

● int difference = "MindTree".compareTo("IT company");

● Difference is 4, i.e the letter “M” of “MindTree” – letter “I” of “IT

company”.

Methods of String

Page 62: Java Basics

© 2011 MindTree Limited Slide 62 CONFIDENTIAL: For limited circulation only Slide 62

● You can search a string for a specified character or substring in a

String using:

Methods of String class

Method name What it does

int indexOf(int ch) Returns the first occurrence of a character or -1 if the specified character is not found

int lastIndexOf(int ch) Returns the last occurrence of a character or -1 if the specified character is not found

int indexOf (int ch, int startIndex)

Similar to int indexOf(int ch) Here, startIndex specifies the index at which point the search begins

Page 63: Java Basics

© 2011 MindTree Limited Slide 63 CONFIDENTIAL: For limited circulation only Slide 63

● Refer:

● Java Language Basics

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html

● For more information on the String class

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

● For information on StringBuffer class

http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html

● For information on StringBuilder class

http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html

References

Page 64: Java Basics

© 2011 MindTree Limited Slide 64 CONFIDENTIAL: For limited circulation only © 2011 MindTree Limited CONFIDENTIAL: For limited circulation only

Contact Person

Contact_ [email protected]

+Country code-Phone

www.mindtree.com