Upload
adam-stafford
View
227
Download
1
Tags:
Embed Size (px)
Citation preview
UNIT II
DATA TYPES
OPERATORS
AND
CONTROL STATEMENT
1
Introducing Classes
ClassMethodsConstructorsKeyword this
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 } }
A Simple Class
class Time
{
int hour;
int minute;
int second;
}
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();
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
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;
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
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
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
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; }
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();
}}
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
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; } }
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; }
}
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
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
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; } }
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.
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); } }
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
22
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
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); }
}
25
class amount1{ public static void main(String args[]) { amount am1= new amount(10,50);
// declared an object of class amount
am1.disp(); }}
26
Output
27
Arrays, and Strings
28
Arrays, and Strings
Introducing Arrays Declaring Arrays, Creating Arrays, and
Initializing Arrays Array of Objects Copying Arrays Multidimensional Arrays String
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
30
Declaring Arraysdatatype[] arrayname;
Example:int[] myList;
datatype arrayname[];
Example:int myList[];
31
Creating ArraysarrayName = new datatype[arraySize];
Example:myList = new double[10];
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];
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
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); } }
35
36
Multi – Dimensional Arrays
Arrays in Java can have more than one dimension.
We are all familiar with N *N matrices.
matrix1.javamatrix1.java
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(); } } }
38
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}
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];
41
The arraycopy Utility
arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
Example:System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
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”
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
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); }}
Output
45
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.
47
Copying one String into Other
String st1=“School of ICT” ;
String st2=”GBU”;
st1=st2; // copy string
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());
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
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); }}
51
Output
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); }}
53
Output
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
55
// String Concatenation with other Data Types
class string4{ public static void main(String args[]) { String s = "four:"+2+2; System.out.println(s); }}
56
Output
57
//String concat with other data typesclass string5{ public static void main(String args[]) { String s = "four:"+(2+2); System.out.println(s); }}
58
Output
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
60
class char1{ public static void main(String args[]) { char ch; ch="abc".charAt(2); System.out.println(ch); }}
61
Output
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
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); } }
64
Output
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
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)); }}
67
Output
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
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')); }}
70
Output
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
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); }}
73
Output
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” ;
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
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); }}
77
Output
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)
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.
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
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);
}}
82
Output
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); }}
84
Output
Nested If and If-Else If Ladder
85
Syntax of Nested IF
Form1 :if(expression) statement; if(expression) statement; | | | if(expression) statement;
86
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
Syntax of Nested IF
Form2 :if(expression) statement;else if(expression) statement; else if(expression)|||else statement;
88
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