Looking for a Tutor Near You?

Post Learning Requirement » x
Ask a Question
x

Choose Country Code

x

Direction

x

Ask a Question

x

Hire a Tutor

Java Classes And Methods Part 1

Published in: Java And J2EE
7,778 Views

This Ppt cover a core description Java classes and methods. In this ppt you will learn classes and methods in details.

Saurabh S / Delhi

4 years of teaching experience

Qualification: MCA

Teaches: Accountancy, Commerce Subjects, Computer Science, IT & Computer Subjects, All Subjects, Mathematics, Economics, Social Studies, BBA Tuition, BCA Tuition, Statistics, .Net, C, C++, Java And J2EE, BCA Subjects, MCA Subjects

Contact this Tutor
  1. NAME SAURABH SANI
  2. Classes and Methods
  3. Objectives Apply OOPs concept when writing code in Java, use eclipse tool to write good code, Apply arrays and strings in different programming scenarios, Write different methods, overload methods
  4. Tahle of o.nntpnt Encapsulation through access Specifiers Getter(Accessor) and Setter (Mutators) Creating and accessing attributes using Constructor Memory allocations null Local vs Class declarations for an reference this instanceof Destruction Types of members Accessing static members Class constants Static Code Analysis with CheckStyle Configuration Management SVN Arrays Initializing arrays Enhanced for loop statement ArrayList Collections Multidimensional arrays Command Line Arguments String class Immutability String comparison when created using constructors
  5. What is a Class? What is an Object? What is encapsulation?
  6. Encapsulation through access Specifiers public access modifier can be used with class declarations and member declaration. private access modifier can be used only with inner class declarations and all member declarations ( variable and methods). Name Registration number Name of the degree Current Semester Student What will you declare as private among the above attributes? Generally a class is responsible for the integrity of its data. Therefore exposing the data within the class may prove to be dangerous. But if you make all data private, how can other classes use them?
  7. Getter(Accessor) and Setter (Mutators) public class Student { private String name ; private int regNo ; public String getName ( ) public void setName (String nm) public int getRegNo ( ) regNo cannot be set by any other class public String private String degreeName ; getDegreeName ( ) public void setDegreeName (String dnm) private int currentSemester ; Instance variables of Student class public int getCurrentSemes ter ( ) public void setCurrentSemester (int i) Instance methods of Student class
  8. Activity Complete the Student code in the previous slide. Add Logic to check the sanity of the values before assigning to the attribute. Did you notice the way the methods are named? Java s recommendation is to use these naming conventions.
  9. Back to Conventions Writing code that follows conventions makes it easy for others to identify the constructs in your code. Local variable names must begin with Constants' names must begin with case. case. Class name must begin with uppercase and each subsequent word with an upper case letter. Names must be meaningful. Methods must be named like variables: name must begin with lower case and each subsequent word beginning with an upper case letter. In other words, members of the class are to be named in lower case (unless they are constants) . Method names are generally verbs and variable names are nouns. Class names, variable names and method names syntactically can be same, but it is better to give different names where ever possible to avoid confusion.
  10. Creating and accessing attributes using . The new keyword is used to create objects. Student s= new Student ( ) ; Access any member of a class, use operator s . name or s . getCurrentSemester ( ) The code listed below prints null, why? public class Test { public static void main (String str[] ) { Student s= new Student ( ) ; System . out . println (s . getName ( ) ) ; 10
  11. Constructor The constructor is a special method for every class that helps initialize the object members at the time of creation. It is a special method because it has the same name as the class name does not have a return type. Can be called only using 'new' keyword when object gets created. There can be more than one constructor for a class. Space is allocated for an object only when the constructor is called. Declaring a variable of class and not calling new does not consume any memory !
  12. Constructor Example public class Student { private String name ; private int regNo ; private String degreeName ; private int currentSemester ; / *Constructor 1 for student who has decided the degree he/she is going to enroll into * / public Student (String setName (nm) ; regNo=generateRegno ( ) ; setDegreeName (d) tCurrentSemes ter ( 1 ) nm, String d) {
  13. / *Constructor 2 for student who has not decided the degree he/she is going to enroll into * / public Student (String nm) { setName (nm) ; regNo=generateRegno ( ) ; setCurrentSemester (1) ; } private int generateRegno ( ) { int nextNo=1 ; // logic to generate regNo will be written later return nextNo ; } // add setter and getters 13
  14. Creating objects by calling constructors public class StudentTest{ public static void main (String args [ ] ) { // Creating object using constructor 1 Student studentl= new Student ( " John // Creating object using constructor 2 Student student2= new Student ("Mary") Student studentl= new Student ( ) • will result in a compilation error. This is because of the absence of no-argument or default constructor.
  15. No argument constructor new Student ( ) will try to invoke a constructor similar to the one below class Student { public Student() { • • } An error will be generated because a no-argument constructor is not defined. When no constructors are defined for a class, compiler automatically inserts a constructor that takes no argument public public 15 class Teacher { Compiler enerated constructor public Teacher ( ) String name ; Compiler inserts super ( ) ; Learn about this in inheritance
  16. [Ylepmorx a.lfcations Stac Heap for references public void test ( ) { int i; Student s=new Student ("Mary' s . setCurrentSemester (2) • STACK s 16 HEAP ame : Ma regNo : 1 currentSem ester : 2 : null
  17. Activity: Multiple references to an object Student studentl= new Student ("Mary" ) Student student2=student1 ; studentl . setName ("Merry Mary") ; System . out . println (student2 . getName ( ) ) ; Complete the diagram. What will the code snippet print? STACK HEAP
  18. Just ec aration of a variable for a class does not create an object. Student s ; STACK s s reference points to nothing o r null value Of an Object reference is null 18
  19. Local vs Class declarations for an reference public class Test { Student student ; public void test ( ) { student . display ( ) ; On executing the code above, an error occurs at runtime j ava . lang . Null PointerException public class Test { public void test ( ) { Student student ; student . display ( ) ; On executing the code above , a compile time error occurs. Can you figure out why we get compile time error? 19
  20. this this is a keyword used only inside a constructor or instance method and is used to refer to the current object. this is like a hidden reference that compiler provides to refer to current object. From the programmer's point of view this comes handy in two places To distinguish between local and class variables when they are the same. public class Student { String name ; Student (String name) { his . name—nam 20
  21. 2. To call a constructor from another constructor of the same class public class String name ; S tudent { public Student (String name) { setName (name) ; regNo=generateRegno ( ) ; setCurrentSemes ter ( 1 ) public Student (String name, String d) { calls this (name) ; setDegreeName (d) •
  22. is an operator that is used to check if the instance is a type of class. usage. object—ref instanceof class—name returns a boolean value. Example : Student s 1= new Student ("Mary") ; System. out . println (sl instanceof Student) ' // true System. out . println (sl instanceof College) ; // compilation error ! System. out . println (null instanceof / / false Student) ; 22
  23. Destruction Any thing created in heap space must be freed. Why? In Java, objects are automatically freed by a background thread called Garbage Collector. Garbage Collector frees the space if the object reference is set to null and no other object reference refers to that object OR if the object goes out of scope and its reference is not assigned to any other variable outside its scope. One cannot really determine when an object will be garbage collected. However, to explicitly invoke Garbage Collector following could be used System. gc ( ) or Runtime . getRuntime ( ) .gc ( ) ; 23
  24. Test your understanding Student studentl= new Student ( "Mary ) ; Student studentref=s tudentl ; studentl=null ; How many objects are created? Will the student object created in the first line be garbage collected? 24
  25. Inst Members of a class that is called using instance. They are part of every object. Class Member Members of a class that is called using class They are shared by objects of same class. Are created using the static modifier. Are initialized even before the instance variables are initialized and can be accessed even if the objects are not created. A static method can access only static variables. But an instance method/ constructor can access both static and instance variables. 25
  26. Member publxc c as private static int gRegNo , Student (String nm) { constructor accessing static member regNo=generateRegno ( ) , int generateRegno ( ) { private static g Reg NO + + ; static method accessing static member static method cannot access instance member return public return 26 gRegNo ; int getGRegNo ( ) { static gRegNo ; }
  27. Accesing Ftaqic members • Static members can e acc e in one oft e two ways: obj ec tRef. s ta ti cvari able or obj ectRef. sta ti cFunction ( ) ClassName . sta ti cvariable or ClassName . sta ti cFunction ( ) public class StudentTest ( ) { public static void main (String args [ ] ) { Student studentl= new Student ("Mary") ; Student student2 ; System . out . println ( System . out . println ( System . out . println ( 27 Student . getGRegNo ( ) studentl . getGRegNo ( ) student2 . getGRegNo ( )
  28. studentl student2 (9 Explore the modifiers of ma in ( ) 28 gRegNo : 2 Student name : John regNo : 2 method Student name : Mary regNo : 1
  29. fina eywor ma es a vana e declaration constant. A final member of a class either has to be initialized where it is declared or must be initialized in all the constructors of the class. If static modifier is also included, then the variable becomes class constant. public class Student { public static final int MAX STUDENTS=3000,• Note that while local variable can be made final, it cannot be made Sta tic! 29
  30. Tell me hqwQ Then, how are the static members stored? J VM Memory is actually divided into 3 sections the Stack the Heap the Method Area The Method Area has information about classes that is part of the executing code- information about methods information about static variables. the Constant Pool for both strings and literals 30
  31. Activity Analyse main ( ) method's modifiers. Can main access instance and static members of its class? 31
  32. GeneFhinß Code in Eclipse Eclipse provi es t e r many ways to gener te code automatically by which the time spent on the development can be saved. Can generate getter and setter methods for attributes. Can generate constructors. Can override/ implement methods from superclasses. Can generate the toString(), hashcode() and equals() methods. Can generate delegate methods. Code generating options can be found in the Sour menu. 32 ROct0t Add C Gee-gee EWnent Correct Element Add Enpotts Sort Clen up— b&hods.... Ger—ee Getters Genetge t&nnqO.. Genet ee hahC•deO Md Gereee from Orca m ftnnqs Prqed Rzn Ctn.? AR.SMt.J Ctrl. I Ctn.Shtt.V Ctn. Shtt.M Ctn.Sh4t.O AR. SMt•Z
  33. To insert the Constructor using fields, Generate Constructor from Fields Select Source Cense& Select Ok Genetø• Ekmerg Cbem Genete.t Genesee toStm.3... and The code is generated. Ct't. CM. 9,n.O pra•taee Similarly all the options can be used. 33
  34. Activity: Cpde Refactoripß code without There IS an opti in ec Ipse, where we can modl y changing its behavior as per our need. For example if we need to rename a Java class or method, we can do this in eclipse which will update in all the references of that class or method. This process is called code refactoring. Eclipse supports simple refactoring activities, such as renaming or moving. For Example, to rename your class or method, right click on it and select Refractor* Rename. Eclipse will make sure that all calls in the Workspace to this class or method will also be renamed. 34 Open type Type ct,t.c at. Sha.v
  35. Static Code Analysis with CheckStyIe CheckStyle is a source code analyzer. It is a plug-in that can be added to many IDEs. It helps in enforcing coding guidelines by pointing out items that deviate from a defined set of coding rules. Apart from coding standards, it also checks for code layout issues, class design problems and duplicate code. Go through CheckStyle documentation or http://checkst_vle.sourceforge.net/checks.html to find out the standard checks that is done 35
  36. EXIßÆGsise e following details: regNo, MarksInEng, Create a c MarksInMaths and MarksInScience. Write getters and setters for the all variables. Use the class Student which is already created for getting the details of the student. Create a class called Standard with 5 students' details and write separate method for each of the following tasks and invoke the same. (30 Mins) a) To display the entire reg no and the name of the students in the class in the ascending order of reg no. b) To display the reg no and the name of the student who has got the highest percentage. c) To display the reg no and the name of the student who scored highest mark in mathematics. d) To display the reg no and the name of the student in the ascending order of the total marks in mathematics and science alone. e) To display the reg no, name, total marks, percentage and rank of all the students in the descending order of rank. 36
  37. Activity use CheckStyle to analyze the code that you have written. Hint: go through http://eclipse- cs. sourceforge. net/ getting_started. html 37
  38. Confi%uration ManaKement Configuration anagement (CM) is a too at is used to manage changes in intermediate components and finished components during the life of an application development. Every item has a unique identification. Apart from these, configuration management tool also facilitates storage and status reporting of selected components. CM aims to control the costs and effort involved in making changes to a system. CM is not just for the code. It can be used for all artifacts like specifications, design, test data etc. It is used right from the beginning of the project. The component that is added to CM is generally referred to as being baselined. 38
  39. SVN Subversion (S V N) the Configuration Management and Version Control product is a popular tool for CM. Apache distributes under a open-source license. S V N uses Copy-modify-merge model 39
  40. Arrays Arrays m jav are like objects; they are created in heap. To create an array new keyword has to be used. Or int [ ] num int sum=O , mul=O ; int num [ ] = new int [5] for (int ;i
  41. public class ArrayTest{ static int num [ ] static void main (String args [ ] ) { public System . out . println (num) ; prints null System . out . println (num [O] ) ; error at runtime NullPointerException
  42. Initializing arrays int [ ] a—new int [ ] Or simply int [ ] The subscript can appear either before or after the variable name. The first syntax comes handy when we need to send an anonymous array to a method call method (new int [ ] 42
  43. Activity int new int [O] ' int —null; What is the difference between the two statements? 43
  44. Enhanced fqr st9tement Syntax : for (datatype variable: array) statement (s) ; Example 1 : int a [ ] = for (int j : a) System . out . println (j) ; Example 2: Student s [ ] = new Student [2] s [O] = new Student ("Mary") ; s [1] = new Student ("John") ; for (Student sl : s) stem . out . println (sl . getName ( ) ) ; 44
  45. Exercise Create a Stack class that can hold any number of integers. Provide methods like push and pop. Use appropriate OOPS principles. Hint: encapsulate an int array with some predefined size. During push operation, if there is an overflow, then the array size should be increased. Make sure that values are not lost in process of doing this. (30 mins 45
  46. ArrayList Collections Arrays in java requires us to specify the size while it is created. In other words array does not grow dynamically. Java API provides java . util . ArrayList class that can be used in cases where we need dynamic array. The Array List class can hold only reference types. If we want Array List to be type-safe we can specify the type in the angular brackets. The enhanced for loop can also be used (apart from regular for loop) for iterating through it Locate ArrayList in Java API and go through the methods for 10 minutes 46
  47. Example: ArraxList import java . util. rrayList; class ArrayListTest{ public static void main (String [ ] ArrayList a= new ArrayList ( ) ; a . add (new Student ("Mary") a. add (new Student ("John") ' a . add (new Student ("Kate") for (Student o: a) System . out . println (o . getName ( ) ) ; 47
  48. Tell me how If Array List can hold only references, then how can we use it for primitives types? There are two ways to do this. 1. 2. Create your own class and encapsulate your preferred primitive type. Java API also provides corresponding class for every primitive type like Byte , Short, Integer, Long, Float, Double, Boolean , Character . So instead of int ; Integer ; we can use 48
  49. Exercise Create an ArrayList that can hold integers. Use methods to insert, delete and find values in the ArrayList. (30 mins 49
  50. Multidimensional arrays Declaration and creating int [ ] [ ] m= new Initlalizing int [ ] [ ] matrix= int [ ] [ ] matrix= Accessing int [3] [3] ; new int [ ] [ ] System . out . println (matrix [O] [O] ) ; Length matrix [O] . length 2 matrix . length 3 50
  51. Exercise Write a program to construct two matrices and display the sum of those. (30 Mins) 51
  52. Activity How will you create a constant array? What does it mean when you declare a constant array? 52
  53. Command Line Arguments Command line arguments are sent as string arrays through main function's argument. public class Test { public static void main (String args [ ] ) { / *command line argument passed * / / * java Test Mary * / System . out . println ( " length : Length=O System . out . println (args [O] ) ; 53 '+args . length) • // Mary
  54. Activity Checkout what happens if you run Test with and without supplying command line arguments ? • VVhy doesn 't the first line end up in NullPointerException? 54
  55. Strinq class String class ha een part of Java right from its inception. • In Java, strings can be created without using char array. • The String class has convenient methods that allows working with strings. Constructors: String ( ) String (String s) Examples of creating String object : String s="abc" ; String s= new String ( ) ; String s= new String ("Hello") ' String sl= new String (s) ; Open the Java doc and locate String API. Go through the methods for 5 minutes. 55
  56. Tell me why? Why do we require equals() method to compare Strings ? Can we not compare using works fine with primitive data types. But with references, (since they are like pointers) compare the addresses. — will actually What we want here is to check equality of value of strings. String s 1= abc" ; String s2=new String (s 1) • // returns false System . out . println (sl==s2) ; // returns true System. out . println (sl . equals (s2) ) ; 56
  57. Write class ha ec ares e following String. "The quick brown fox jumps over the lazy dog Perform the following modifications to the above string using appropriate Methods. (30 Mins) a) b) c) d) e) Print the character at the 12th index. Check whether the String contains the word "is". Add the string "and killed it"to the existing string. Check whether the String ends with the word "dogs" Check whether the String is equal to "The quick brown Fox jumps over the lazy Dog Check whether the string is equal to 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" Cont...
  58. g) h) i) j) k) 1) m) n) o) 58 Find the length of the String. Check whether the String matches to "The quick brown Fox jumps over the lazy Dog". Replace the word "The" with the word A . Split the above string into two such that two animal names do not come together. Print the animal names alone separately from the above string. Print the above string in completely lower case. Print the above string in completely upper case. Find the index position of the character a Find the last index position of the character e (30 mins
  59. Stri 1 Java. String literals are very heavily used in applications and they also occupy a lot of memory. Therefore for efficient memory management, all the strings are created and kept by the J VM in a place called string pool (which is part of Method Area). Garbage collector does not come into string pool. String String 59 sl ABC String pool
  60. String s 1= Assigning string references: String sl="ABC" String s2=s1 ; System . out . println (sl ) 60 This string object remains intact. This is not chan ed. sl ABC String pool DEF sl ABC DEF prints ABC Strmg pool
  61. Test your understanding What will the code print? String sl="ABC" String s2=s1 ; System . out . println (sl==s2 ) System . out . println (sl==s2 ) String s4="ABC" System . out . println ) 61 String studentl= "Mary" String studentref=" John" ; String studentref=studentl ; studentl=null ; How many instances of String will be eligible for garbage collection?
  62. String comparison when created using constructors sl ABC String String po I String s4=new String ( "ABC") System . out . println (sl==s4) ; / / Prints false The String constructor creates the string outside the strin o I m e ap. If there is no string represented by the string created, then tlf strin ets added to the pool also. String s5=new String ("MQ") StF 62
  63. Test your understanding String s 1= "abc" ; sl=sl . replace ( 'a sl . replace ( 'b System . out . print (s 1) ; What will the code print? How many Strings are created in the pool? 63
  64. r n ate abc class Abc ABc In the example in the previous slide, 3 strings were created in the pool. What was needed after the 3rd line was the last string ABC. Since garbage collector does not go to the string pool, we have to be very careful when we work with the strings. If there are lots of String manipulations in your application and you are concerned about memory, then String class should not be used. JSE comes with another class for such operations StringBui1der and StringBuffer class. 64
  65. Exercise Given an array of 10 students' names. Convert the array as a single string and print it. Hint: Efficient use of memory is the focus here (15 Mins) 65
  66. Exercise Write a program to check whether the given strings are an anagram or not. An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example, "Ate " is an anagram of "Eat The program should ignore white space and punctuation. (30 Mins) 66
  67. S IJtrn rx The new eywor is sed to create objects The constructor is a special method that helps initialize the object members at the time of creation. It has the same name as the class name. this is a keyword which is used to refer to the current object. Instanceof operator is used to check if the instance is a type of class. In Java, objects are automatically freed by a background thread called Garbage Collector. Configuration management (CM) is a tool that is used to manage changes in intermediate components and finished components during the life of an application development. Arrays in java are like objects and they are created in heap. rings are immutable in Java.