89
UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Embed Size (px)

Citation preview

Page 1: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

UNIT II

DATA TYPES

OPERATORS

AND

CONTROL STATEMENT

1

Page 2: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Introducing Classes

ClassMethodsConstructorsKeyword this

Page 3: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

ClassA class is declared by use of the class keyword.A class is a template for an object, and an object is an

instance of a class.The general form of a class is: class class_name { type instance_variable1; type instance_variable2;

// ….. type method_name1(parameter_list)

{ // body of method } }

Page 4: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

A Simple Class

class Time

{

int hour;

int minute;

int second;

}

Page 5: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Declaring and Creating Objects

An object is nothing but an instantiation of a class.

An object declaration is like any other variable.

Time t1; //declaration t1 = new Time(); //createYou can combine declaration and creation.

Time t1 = new Time();

Page 6: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Write a program to define and use an object of class Timeclass Time {

int hour;

int minute;

int second;

}

class time1{

public static void main(String args[])

{

int total;

Time t1= new Time();

t1.hour=5;

t1.minute=30;

t1.second=0;

total=t1.hour*60*60 + t1.minute*60+t1.second;

System.out.println(" Total seconds "+ total);

}

}

time1.java

Page 7: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

7

//time2.javaclass Time { int hour; int minute; int second;}class time2{ public static void main(String args[]) { int total; Time t1= new Time(); Time t2= new Time(); t1.hour=5; t1.minute=30; t1.second=0; t2.hour=2; t2.minute=20; t2.second=10;

Page 8: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

8

total=t1.hour*60*60 + t1.minute*60+t1.second; System.out.println(" Total seconds "+ total);

total=t2.hour*60*60 + t2.minute*60+t2.second; System.out.println(" Total seconds "+ total); }}

time2.java

Page 9: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Introducing Methods

A class in Java contains data in the form of variables.

In addition, a class contains functions to work with these variables.

These functions are termed as methods in Java

Page 10: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Methodsclass Time { int hour; int minute; int second; int total (){ return 3600*hour + 60*minute + second; }}class time3{ public static void main(String args[]) { int result; Time t1= new Time(); t1.hour=5; t1.minute=30; t1.second=0; result=t1.total(); System.out.println(" Total seconds "+ result); } }

time3.java

Page 11: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Methods with Parameters

A parameterized method can operate on a variety of data be used in a number of slightly different situations. class Time {

int hour; int minute; int second; void convert(int n) { int temp=n; second=n%60; temp=temp/60; minute=temp%60; hour=temp/60; }

Page 12: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

12

time4.java

void display() { System.out.println(":TIME:"); System.out.println("Hours="+hour); System.out.println("Minutes="+minute); System.out.println("Seconds="+second); }}class time4{ public static void main(String args[]) { Time t1= new Time(); t1.convert(7840); t1.display();

}}

Page 13: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

ConstructorsA constructors method is a special kind of method that determines how an object is initialized when created.

They have the same name as the class and do not have any return type.

Constructors are two types: Default Constructors

Parameterized Constructors

Page 14: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Default Constructors

Class Box{ double width; double height; double depth; Box () // this is the constructor for Box { System.out.println(“Constructing Box ”); width=10; height=10; depth=10; } }

Page 15: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

15

class Box{ double width; double height; double depth;

Box() // this is the constructor for Box { System.out.println("Constructing Box"); width=10; height=10; depth=10; }

double volume() { return width*height*depth; }

}

Page 16: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

16

class Box1{ public static void main(String args[]) { Box mybox= new Box(); // declare,allocate and initialize Box objects

double vol;

vol=mybox.volume();

System.out.println("Volume is "+vol);

}}

Box1.java

Page 17: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Parameterized Constructors

Class Box{ double width; double height; double depth; // this is the parameterized constructor for Box Box ( double w, double h, double d) { System.out.println(“Constructing Box ”); width= w; height= h; depth= d; } }

Box2.java

Page 18: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Keyword thisThe this keyword is used inside any instance

method to refer to the current object.

The value of this refers to the object on which the current method has been called.

class amount{ int rupee; int paise; amount(int r1, int p1) // constructor { rupee=r1; paise=p1; } }

Page 19: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Keyword this cont…

class amount {int rupee; int paise; amount(int rupee, int paise) //

constructor { rupee=rupee; paise=paise; } }In this parameter our computer cannot

resolve this ambiguity.

Keyword this comes solve it.

Page 20: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

20

class amount{ int rupee; int paise;

amount( int rupee, int paise) { rupee=rupee; paise=paise; }

void disp() { System.out.println("rupee:"+rupee); System.out.println("paise:"+paise); } }

Page 21: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

21

class amount_out{ public static void main(String args[]) { amount am1= new amount(10,50); // declared an object of class amount

am1.disp(); }}

amount_out.java

Page 22: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

22

Page 23: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Keyword this cont…

amount(int rupee, int paise) // constructor

{ this.rupee=rupee; this.paise=paise; } this.rupee refers to rupee for current

object and rupee represents the parameter.

amount1.java

Page 24: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

24

class amount{ int rupee; int paise; amount( int rupee, int paise) { this.rupee=rupee; this.paise=paise; } void disp() { System.out.println("rupee:"+rupee); System.out.println("paise:"+paise); }

}

Page 25: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

25

class amount1{ public static void main(String args[]) { amount am1= new amount(10,50);

// declared an object of class amount

am1.disp(); }}

Page 26: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

26

Output

Page 27: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

27

Arrays, and Strings

Page 28: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

28

Arrays, and Strings

Introducing Arrays Declaring Arrays, Creating Arrays, and

Initializing Arrays Array of Objects Copying Arrays Multidimensional Arrays String

Page 29: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

29

Introducing Arrays

double[] myList = new double[10]

Array is a data structure that represents a collection of the same types of data. Java treats these arrays as objects.

An Array of 10 Elementsof type double

Page 30: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

30

Declaring Arraysdatatype[] arrayname;

Example:int[] myList;

datatype arrayname[];

Example:int myList[];

Page 31: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

31

Creating ArraysarrayName = new datatype[arraySize];

Example:myList = new double[10];

Page 32: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

32

Declaring and Creating in One Step

datatype[] arrayname = new

datatype[arraySize];

double[] myList = new double[10];

datatype arrayname[] = new datatype[arraySize];

double myList[] = new double[10];

Page 33: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

33

Initializing ArraysUsing a loop:

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

Declaring, creating, initializing in one step:

double[] myList = {1.9, 2.9, 3.4, 3.5};

array1.java

Page 34: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

34

class array1{ public static void main(String args[]) { float total=0, avg; int j; int marks[];// decalared marks= new int[5];// creation System.out.println("the array is:"); marks[0]=26;

marks[1]=43;marks[2]=56;marks[3]=67;marks[4]=45;for(j=0;j<marks.length;j++)

{ total=total+marks[j]; } avg=(float)(total/5.0); System.out.println("avg marks are: "+avg); } }

Page 35: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

35

Page 36: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

36

Multi – Dimensional Arrays

Arrays in Java can have more than one dimension.

We are all familiar with N *N matrices.

matrix1.javamatrix1.java

Page 37: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

37

// Demonstration of Matrix using Arrayclass matrix1{ public static void main(String args[]) { int i,j; int matrix[][]={ {1,2,3}, {4,5,6}, {7,8,9} }; System.out.println("the matrix is:"); for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { System.out.print("\t"+matrix[i][j]); } System.out.println(); } } }

Page 38: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

38

Page 39: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

39

Enhanced for Loop

Now we can set a loop asfor(int j:marks) { body of the loop }Here, body of the loop is executed for every value j

which is present in an array.It is equivalent to a standard for loop like:for(i=0;i<marks.length;i++){ body of the loop}

Page 40: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

40

Copying Arrays

Using a loop:

int[] sourceArray = {2, 3, 1, 5, 10};

int[] targetArray = new int[sourceArray.length];

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

targetArray[i] = sourceArray[i];

Page 41: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

41

The arraycopy Utility

arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);

Example:System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Page 42: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

42

Strings

Strings is a combination of characters.Strings are instances of the class string.Java has a class String defined in the package java.lang.

“this is a string”

Page 43: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

43

Declaring and Constructing a String

An object of class String is declared just like any other object declaration

String s1;

s1=“Good Morning”

Another way:-

String s1= new String(“Good Morning”);

The third way:

char [] box={‘I’,’C’,’T’,’G’,’B’,’U’};

String s3= new String(box);

string1.java

Page 44: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

44

// string1.javaclass string1{ public static void main(String args[]) { String s1=new String("Good Morning"); String s2;

s2="Sir.";

char[] box={'I','C','T','G','B','U'};

String s3= new String(box);

System.out.println(s1); System.out.println(s2); System.out.println(s3); }}

Page 45: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Output

45

Page 46: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

46

Declaring and Constructing a String

You can specify a subrange of a character array as an initializer using the following constructor:

String(char chars[ ], int startIndex, int numChars)

Here, startIndex specifies the index at which the subrange

begins, and numChars specifies the number of characters to use.

Here is an example:

char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };String s = new String(chars, 2, 3);This initializes s with the characters cde.

Page 47: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

47

Copying one String into Other

String st1=“School of ICT” ;

String st2=”GBU”;

st1=st2; // copy string

Page 48: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

48

String Length

The length of a string is the number of characters that it contains.

To call the length() method

int length()

char chars[]={‘a’, ’b’, ’c’};

String s = new String(chars);

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

Page 49: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

49

Special String Operations

String Concatenation

String age=“9”;

String s = “He is ”+age+”years old”;

System.out.println(s);

String Concatenation with other Data Types

int age=9;

String s = “He is ”+age+”years old”;

System.out.println(s);

string2.java

string3.java

Page 50: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

50

//string2.javaclass string2{ public static void main(String args[]) { String age=" 9 "; String s = "He is"+age+"years old"; System.out.println(s); //System.out.println(s2); //System.out.println(s3); }}

Page 51: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

51

Output

Page 52: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

52

//string3.java string concat with data typesclass string3{ public static void main(String args[]) { int age=9; String s = "He is "+age+" years old."; System.out.println(s); //System.out.println(s2); //System.out.println(s3); }}

Page 53: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

53

Output

Page 54: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

54

Special String Operations cont..

• String Concatenation with other Data Types

String s = “four :”+2+2;

System.out.println(s);

This fragment displays four : 22 rather than the four: 4

String s = “four :”+(2+2);

System.out.println(s);

s contains the string “four : 4”;

string4.java

string5.java

Page 55: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

55

// String Concatenation with other Data Types

class string4{ public static void main(String args[]) { String s = "four:"+2+2; System.out.println(s); }}

Page 56: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

56

Output

Page 57: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

57

//String concat with other data typesclass string5{ public static void main(String args[]) { String s = "four:"+(2+2); System.out.println(s); }}

Page 58: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

58

Output

Page 59: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

59

Character Extraction

The String class provides a number of ways that characters can be extracted from a String object.

• charAt( ) //It returns a character at the specified location

• To extract a single character from a String

char charAt(int where)

char ch;

ch= “abc”.charAt(1);

char1.java

Page 60: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

60

class char1{ public static void main(String args[]) { char ch; ch="abc".charAt(2); System.out.println(ch); }}

Page 61: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

61

Output

Page 62: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

62

Character Extraction cont…

If you need to extract more than one character at a time , you can use the getChars ( ) method

void getChars(int sourceStart, int sourceEnd, char target[],int targetStart)

class getcharsdemo {

public static void main (String args[]) {

String s = “This is a demo of the getchars method.”;

int start = 10; int end= 14;

char buf [] = new char[end - start];

s.getChars(start, end, buf, 0);

System.out.println(buf); } }getcharsdemo.java

Page 63: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

63

class getcharsdemo { public static void main (String args[]) { String s = "This is a demo of the getchars method."; int start = 10; int end= 14; char buf [] = new char[(end - start)]; s.getChars(start, end, buf, 0); System.out.println(buf); } }

Page 64: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

64

Output

Page 65: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

65

String Comparison

The String class included several methods that compare strings or substrings within strings.

equals( ) and equalsIgnoreCase( )

String s1=“Hello”;

String s2=“Hello”;

String s3=“HELLO”;

s1.equals(s2);

s1.equalsIgnoreCase(s3);

stringcomp.java

Page 66: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

66

class stringcomp{ public static void main(String args[]) { String s1="Hello"; String s2="Hello"; String s3="HELLO"; System.out.println(s1.equals(s2)); System.out.println(s1.equalsIgnoreCase(s3)); }}

Page 67: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

67

Output

Page 68: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

68

Searching Strings The String class provides two methods that allow you to

search a string for a specified character or substring.

indexOf( ) : searches for the first occurrence of a character or substring.

lastIndexOf( ): searches for the last occurrence of a character or substring.

int indexOf( int ch);

int lastIndexOf(int ch);

int indexOf(String str);

int lastIndexOf(String str);

indexofdemo.java

Page 69: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

69

class indexofdemo{ public static void main(String args[]) { String s="Now is the time for all good man"; System.out.println(s);System.out.println("indexOf(t)= "+s.indexOf('t')); System.out.println("lastIndexOf(t)= "+s.lastIndexOf('t')); }}

Page 70: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

70

Output

Page 71: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

71

Modifying a String

substring( ) you can extract a substring using substring( ). It has two forms.

The first is : String substring(int startIndex)

startindex specifies the index at which the substring will began.

The second form is:

String substring(int startIndex, int endIndex)

startIndex specifies the beginning index, and endIndex specifies the stopping point stringsub.java

Page 72: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

72

class stringsub{ public static void main(String args[]) { String s="Now is the time for all good man"; String s1,s2; s1=s.substring(10); System.out.println(s1);

s2=s.substring(5,25); System.out.println(s2); }}

Page 73: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

73

Output

Page 74: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

74

Modifying a String concat( ) you can concatenate two string using concat( ),shown

here

String concat(String str)

String s1 = “School of ” ;

String s2 = s1.concat(“Biotechnology”) ;

same as

String s1= “School of ” ;

String s2 = s1 +” Biotechnology” ;

Page 75: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

75

Modifying a String

replace( ) The replace( ) method replaces all occurrences of one character in

the invoking string with another.

String replace(char original, char replacement)

String s = “SoIT”.replace(‘I’,’B’);

trim( )

The trim() method returns a copy of the invoking string from which any leading and trailing whitespace has been removed.

String trim( )

String s = “ School of Biotechnology ”.trim();

stringmod.java

Page 76: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

76

class stringmod{ public static void main(String args[]) { String s1="School of "; String s2= s1.concat("Biotechnology"); System.out.println(s2); String s3 = "SoIT".replace('I','B'); System.out.println(s3);

String s4 = " School of Biotechnology ".trim(); System.out.println(s4); }}

Page 77: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

77

Output

Page 78: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

78

StringBuffer

String is a very useful class.

You cannot change a string,you have to use copy and modify and replace for every task.

Java provided a new class StringBuffer

There are following three different constructors.

StringBuffer ()

StringBuffer (int size)

StringBuffer(String str1)

Page 79: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

79

StringBuffer cont…

StringBuffer ()This string buffer with default capacityof 16.

StringBuffer (int size)This string buffer with specified capacity.

StringBuffer(String str1) This string buffer creates an object by copying a given

string.

Page 80: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

80

StringBuffer cont…

The operations on a StringBuffer can be stated as follows :

append insert reverse replace convert to string get substring convert to character array

strbuf.java

strbuf1.java

Page 81: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

81

class strbuf{ public static void main(String args[]) {StringBuffer st1=new StringBuffer("1234567890123456789012345"); System.out.println(st1); System.out.println("after insertion"); st1.insert(20,"at 20th col"); System.out.println(st1);

}}

Page 82: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

82

Output

Page 83: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

83

class strbuf1{ public static void main(String args[]) { StringBuffer st1=new StringBuffer("school of ICT"); System.out.println(st1); System.out.println("after reverse"); st1.reverse(); System.out.println(st1); StringBuffer st2=new StringBuffer("biotechnology"); st2.delete(2,6); System.out.println(st2); }}

Page 84: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

84

Output

Page 85: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Nested If and If-Else If Ladder

85

Page 86: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Syntax of Nested IF

Form1 :if(expression) statement;  if(expression) statement;    |    |    |     if(expression) statement;

86

Page 87: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Example 1 : Program that checks number is zero, positive or negative using nested if statement

class CheckSignNumberDemo {   public static void main(String args[])    {

int x = 10;

if(x > -1) if(x != 0)   if(x > 0)System.out.println("x is a positive number having value " + x);

   }} 

Outputx is a positive number having value 10

87

Page 88: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Syntax of Nested IF

Form2 :if(expression) statement;else    if(expression) statement;    else        if(expression)|||else statement;

88

Page 89: UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Example 2 : Program that checks number is zero, positive or negative using if-else-if ladder

class CheckSignNumberDemo {   public static void main(String args[])    {int x = 10;

if(x <= -1)System.out.println("x is a negative number having value " + x);else if(x == 0)System.out.println("x is a zero number having value " + x);elseif(x > 0)System.out.println("x is a positive number having value " + x);   }} Outputx is a positive number having value 10

89