UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

Chapter 25 Lists, Stacks, Queues, and Priority Queues
1
Final and Abstract Classes
1 Inheritance Classes and Subclasses Or Extending a Class.
1 Arrays, Strings and Collections [1] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
Classes and Objects in Java
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 8 Operator Overloading, Friends, and References.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Chapter 1 The Study of Body Function Image PowerPoint
1 Copyright © 2013 Elsevier Inc. All rights reserved. Appendix 01.
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
David Burdett May 11, 2004 Package Binding for WS CDL.
3 Copyright © 2005, Oracle. All rights reserved. Basic Java Syntax and Coding Conventions.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
FACTORING ax2 + bx + c Think “unfoil” Work down, Show all steps.
Introduction to Programming
Learning to show the remainder
© Vinny Cahill 1 Writing a Program in Java. © Vinny Cahill 2 The Hello World Program l Want to write a program to print a message on the screen.
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Chapter 7: Arrays In this chapter, you will learn about
Break Time Remaining 10:00.
Turing Machines.
PP Test Review Sections 6-1 to 6-6
Chapter 24 Lists, Stacks, and Queues
ITEC200 Week04 Lists and the Collection Interface.
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Color Templates Software Engineering Module: Core of Java Topic: Constructors TALENTSPRINT | © Copyright 2012.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Chapter 8: Arrays.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Factor P 16 8(8-5ab) 4(d² + 4) 3rs(2r – s) 15cd(1 + 2cd) 8(4a² + 3b²)
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
© 2012 National Heart Foundation of Australia. Slide 2.
1 User-Defined Classes The String class is a pre-defined class that is provided by the Java Designer. Sometimes programmers would like to create their.
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
MaK_Full ahead loaded 1 Alarm Page Directory (F11)
While Loop Lesson CS1313 Spring while Loop Outline 1.while Loop Outline 2.while Loop Example #1 3.while Loop Example #2 4.while Loop Example #3.
Objects & Methods Defining Classes. Slide 2 Reference Variables Revisited Remember: Object variables are references (aka pointers) Point to “null” by.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Subtraction: Adding UP
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Types of selection structures
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
©Brooks/Cole, 2001 Chapter 12 Derived Types-- Enumerated, Structure and Union.
Essential Cell Biology
Chapter 2 JAVA FUNDAMENTALS
Converting a Fraction to %
Clock will move after 1 minute
Intracellular Compartments and Transport
PSSA Preparation.
Essential Cell Biology
Select a time to count down from the clock above
Copyright Tim Morris/St Stephen's School
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
1 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
class Box { double width; double height; double depth; }
Presentation transcript:

UNIT II DATA TYPES OPERATORS AND CONTROL STATEMENT 1

Introducing Classes Class Methods Constructors Keyword this

Class A 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(); //create You can combine declaration and creation. Time t1 = new Time();

Write a program to define and use an object of class Time class 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.java class 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

Methods class 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(); }

Constructors A 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 this The 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 Elements of type double

30 Declaring Arrays datatype[] arrayname; Example: int[] myList; datatype arrayname[]; Example: int myList[];

31 Creating Arrays arrayName = 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 Arrays Using 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.java

37 // Demonstration of Matrix using Array class 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 as for(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.java class 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.java class 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 types class 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 types class 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(" "); 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; 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); } Output x 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); else if(x > 0) System.out.println("x is a positive number having value " + x); } Output x is a positive number having value 10 89