Basic Java Concepts Flashcards
(42 cards)
HOW MANY MAIN GROUPS are there that encompasses the different kind of statements in Java
There are three main groups that encompass the different kinds of statements in Java:
WHAT ARE THE THREE MAIN GROUPS OF STATEMENTS
(1) Expression statements: these change values of variables, call methods and create objects.
(2) Declaration statements: these declare variables.
(3) Control flow statements: these determine the order that statements are executed.
Examples:
//declaration statement int number; //expression statement number = 4; //control flow statement if (number
DEFINITION OF STATEMENTS
Definition:statement
Statements are similar to sentences in the English language. A sentence forms a complete idea which can include one or more clauses. Likewise, a statement in Java forms a complete command to be executed and can include one or more expressions.
There are three main groups that encompass the different kinds of statements in Java:
(1) Expression statements: these change values of variables, call methods and create objects.
(2) Declaration statements: these declare variables.
(3) Control flow statements: these determine the order that statements are executed.
Examples:
//declaration statement int number; //expression statement number = 4; //control flow statement if (number
Definition: expressions
Expressions are essential building blocks of any Java program. They are built using values, variables, operators and method calls.
In terms of the syntax of the Java language, an expression is akin to a clause in the English language. A clause portrays a specific meaning. With the right punctuation it can sometimes stand on its own or more often than not become part of a sentence. Similarly, an expression in Java evaluates to a single value.
Some expressions can make statements by themselves (by adding a semicolon on the end) but more commonly make up part of a statement.
Examples of EXPRESSIONS
The following program contains plenty of expressions (shown in bold italics) that each evaluate to a specific value:
int secondsInDay = 0;
int daysInWeek = 7;
int hoursInDay = 24;
int minutesInHour = 60;
int secondsInMinute = 60;
boolean calculateWeek = true;
secondsInDay = secondsInMinute * minutesInHour * hoursInDay; System.out.println(“The number of seconds in a day is: “ + secondsInDay);
if (calculateWeek == true) { System.out.println(“The number of seconds in a week is: “ + secondsInDay * daysInWeek); }
The expressions in the first six lines of the code above, all use the assignment operator to assign the value on the right to the variable on the left.
The seventh line is an expression that can stand on its own as a statement. It also shows that expressions can be built up through the use of more than one operator. The final value of the variable secondsInDay, is the culmination of evaluating each expression in turn (i.e., secondsInMinute * minutesInHour = 3600, followed by 3600 * hoursInDay = 86400).
Definition: statement(2)
Definition: statement(2)
A statement is a block of code that does something. An assignment statement assigns a value to a variable. A for statement performs a loop.
FIELD
Fields are used to store the data for the object and combined they make up the state of an object. As we’re making a Book object it would make sense for it to hold data about the book’s title, author, and publisher:
public class Book { //fields Below private String title; private String author; private String publisher; }
Fields are just normal variables with one important restriction – they must use the access modifier “private”.
The private keyword means that theses variables can only be accessed from inside the class that defines them.
Note: this restriction is not enforced by the Java compiler. You could make a public variable in your class definition and the Java language won’t complain about it. However, you will be breaking one of the fundamental principles of object-oriented programming – data encapsulation. The state of your objects must only be accessed through their behaviors. Or to put it in practical terms, your class fields must only be accessed through your class methods. It’s up to you to enforce data encapsulation on the objects you create.
The Constructor Method
The Constructor Method
Most classes have a constructor method. It’s the method that gets called when the object is first created and can be used to set up its initial state:
public class Book { //fields private String title; private String author; private String publisher; //constructor method public Book(String bookTitle, String authorName, String publisherName) { //populate the fields title = bookTitle; author = authorName; publisher = publisherName; } }
The constructor method uses the same name as the class (i.e., Book) and needs to be publicly accessible. It takes the values of the variables that are passed into it and sets the values of the class fields; thereby setting the object to it’s initial state.
The Class Declaration
The data an object holds and how it manipulates that data is specified through the creation of a class. For example, below is a very basic definition of a class for a Book object:
public class Book { } It's worth taking a moment to break down the above class declaration. The first line contains the two Java keywords "public" and "class":
The public keyword is known as an access modifier. It controls what parts of your Java program can access your class. In fact, for top-level classes (i.e., classes not contained within another class), like our book object, they have to be public accessible.
The class keyword is used to declare that everything within the curly brackets is part of our class definition. It’s also followed directly by the name of the class.
Data Encapsulation
One of the ways we can enforce data encapsulation is through the use of accessors and mutators. The role of accessors and mutators are to return and set the values of an object’s state. This article is a practical guide on how to program them in Java.
As an example I’m going to use a Person class with the following state and constructor already defined:
public class Person { //Private fields private String firstName; private String middleNames; private String lastName; private String address; private String username; //Constructor method public Person(String firstName, String middleNames, String lastName, String address) { this.firstName = firstName; this.middleNames = middleNames; this.lastName = lastName; this.address = address; this.username = ""; } } Ads
Accessor Methods
An accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word “get” to the start of the method name. For example let’s add accessor methods for firstname, middleNames and lastname:
//Accessor for firstName public String getFirstName() { return firstName; } //Accessor for middleNames public String getMiddlesNames() { return middleNames; } //Accessor for lastName public String getLastName() { return lastName; } These methods always return the same data type as their corresponding private field (e.g., String) and then simply return the value of that private field.
We can now access their values through the methods of a Person object:
public class PersonExample { public static void main(String[] args) { Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall"); System.out.println(dave.getFirstName() + " " + dave.getMiddlesNames() + " " + dave.getLastName()); } } Mutator Methods
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word “set” to the start of the method name. For example, let’s add mutator fields for address and username:
//Mutator for address public void setAddress(String address) { this.address = address; } //Mutator for username public void setUsername(String username) { this.username = username; } These methods do not have a return type and accept a parameter that is the same data type as their corresponding private field.
The parameter is then used to set the value of that private field.
It’s now possible to modify the values for the address and username inside the Person object:
public class PersonExample { public static void main(String[] args) { Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall"); dave.setAddress("256 Bow Street"); dave.setUsername("DDavidson"); } } Why Use Accessors and Mutators?
It’s easy to come to the conclusion that we could just change the private fields of the class definition to be public and achieve the same results. It’s important to remember that we want to hide the data of the object as much as possible. The extra buffer provided by these methods allows us to:
change how the data is handled behind the scenes
impose validation on the values that the fields are being set to.
Let’s say we decide to modify how we store middle names. Instead of just one String we now use an array of Strings:
private String firstName; //Now using an array of Strings private String[] middleNames; private String lastName; private String address; private String username; public Person(String firstName, String middleNames, String lastName, String address) { this.firstName = firstName; //create an array of Strings this.middleNames = middleNames.split(" "); this.lastName = lastName; this.address = address; this.username = ""; } //Accessor for middleNames public String getMiddlesNames() { //return a String by appending all the Strings of middleNames together StringBuilder names = new StringBuilder(); for(int j=0;j 10) { this.username = username.substring(0,10); } else { this.username = username; } } Now if the username passed to the setUsername mutator is longer than ten characters it is automatically truncated.
Constructors : Initializing an Class Object in Java Programming
Constructors : Initializing an Class Object in Java Programming
- Objects contain there own copy of Instance Variables.
- It is very difficult to initialize each and every instance variable of each and every object of Class.
- Java allows objects to initialize themselves when they are created. Automatic initialization is performed through the use of a constructor.
- A Constructor initializes an object as soon as object gets created.
- Constructor gets called automatically after creation of object and before completion of new Operator.
Some Rules of Using Constructor : - Constructor Initializes an Object.
- Constructor cannot be called like methods.
- Constructors are called automatically as soon as object gets created.
- Constructor don’t have any return Type. (even Void)
- Constructor name is same as that of “Class Name“.
- Constructor can accept parameter.
Live Example : How Constructor Works ?
class Rectangle { int length; int breadth;
Rectangle() { length = 20; breadth = 10; }
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
System.out.println(“Length of Rectangle : “ + r1.length);
System.out.println(“Breadth of Rectangle : “ + r1.breadth);
}
}
Output :
C:Priteshjava>javac RectangleDemo.java
C:Priteshjava>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
Explanation :
1. new Operator will create an object.
2. As soon as Object gets created it will call Constructor-
Rectangle() //This is Constructor
{
length = 20;
breadth = 10;
}
3. In the above Constructor Instance Variables of Object r1 gets their own values.
4. Thus Constructor Initializes an Object as soon as after creation.
5. It will print Values initialized by Constructor –
System.out.println(“Length of Rectangle : “ + r1.length);
System.out.println(“Breadth of Rectangle : “ + r1.breadth);
Accessors and mutators
Accessors and mutators
One of the ways we can enforce data encapsulation is through the use of accessors and mutators. The role of accessors and mutators are to return and set the values of an object’s state. This article is a practical guide on how to program them in Java.
As an example I’m going to use a Person class with the following state and constructor already defined:
public class Person { //Private fields private String firstName; private String middleNames; private String lastName; private String address; private String username; //Constructor method public Person(String firstName, String middleNames, String lastName, String address) { this.firstName = firstName; this.middleNames = middleNames; this.lastName = lastName; this.address = address; this.username = “”; } }
Accessor Methods
An accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word “get” to the start of the method name. For example let’s add accessor methods for firstname, middleNames and lastname:
//Accessor for firstName public String getFirstName() { return firstName; } //Accessor for middleNames public String getMiddlesNames() { return middleNames; } //Accessor for lastName public String getLastName() { return lastName; } These methods always return the same data type as their corresponding private field (e.g., String) and then simply return the value of that private field.
We can now access their values through the methods of a Person object:
public class PersonExample { public static void main(String[] args) { Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall"); System.out.println(dave.getFirstName() + " " + dave.getMiddlesNames() + " " + dave.getLastName()); } } Mutator Methods
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word “set” to the start of the method name. For example, let’s add mutator fields for address and username:
//Mutator for address public void setAddress(String address) { this.address = address; } //Mutator for username public void setUsername(String username) { this.username = username; } These methods do not have a return type and accept a parameter that is the same data type as their corresponding private field.
The parameter is then used to set the value of that private field.
It’s now possible to modify the values for the address and username inside the Person object:
public class PersonExample { public static void main(String[] args) { Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall"); dave.setAddress("256 Bow Street"); dave.setUsername("DDavidson"); } } Why Use Accessors and Mutators?
It’s easy to come to the conclusion that we could just change the private fields of the class definition to be public and achieve the same results. It’s important to remember that we want to hide the data of the object as much as possible. The extra buffer provided by these methods allows us to:
change how the data is handled behind the scenes
impose validation on the values that the fields are being set to.
Let’s say we decide to modify how we store middle names. Instead of just one String we now use an array of Strings:
private String firstName; //Now using an array of Strings private String[] middleNames; private String lastName; private String address; private String username; public Person(String firstName, String middleNames, String lastName, String address) { this.firstName = firstName; //create an array of Strings this.middleNames = middleNames.split(" "); this.lastName = lastName; this.address = address; this.username = ""; } //Accessor for middleNames public String getMiddlesNames() { //return a String by appending all the Strings of middleNames together StringBuilder names = new StringBuilder(); for(int j=0;j 10) { this.username = username.substring(0,10); } else { this.username = username; } } Now if the username passed to the setUsername mutator is longer than ten characters it is automatically truncated.
Introduction to Object-Oriented Programming
Introduction to Object-Oriented Programming
Java is designed around the principles of object-oriented programming. To truly master Java you must understand the theory behind objects. This article is an introduction to object-oriented programming outlining what objects are, their state and behaviors and how they combine to enforce data encapsulation.
What Is Object-Oriented Programming?
To put it simply, object-oriented programming focuses on data before anything else.
How data is modeled and manipulated through the use of objects is fundamental to any object-oriented program.
What Are Objects?
If you look around you, you will see objects everywhere. Perhaps right now you are drinking coffee. The coffee mug is an object, the coffee inside the mug is an object, even the coaster it’s sitting on is one too.
Object-oriented programming realizes that if we’re building an application it’s likely that we will be trying to represent the real world. This can be done by using objects.
Let’s look at an example. Imagine you want to build a Java application to keep track of all your books. The first thing to consider in object-oriented programming is the data the application will be dealing with. What will the data be about? Books.
We’ve found our first object type - a book. Our first task is to design an object that will let us store and manipulate data about a book. In Java, the design of an object is done by creating a class. For programmers, a class is what a blueprint of a building is to an architect, it lets us define what data is going to be stored in the object, how it can be accessed and modified, and what actions can be performed on it.
And, just like a builder can build more than more building using a blueprint, our programs can create more than one object from a class. In Java, each new object that is created is called an instance of the class.
Let’s go back to the example. Imagine you now have a book class in your book tracking application.
Bob from next door gives you a new book for your birthday. When you add the book to the tracking application a new instance of the book class is created. It is used to store data about the book. If you then get a book from your father and store it in the application, the same process happens again. Each book object created will contain data about different books.
Maybe you frequently lend your books out to friends. How do we define them in the application? Yes, you guessed it, Bob from next door becomes an object too. Except we wouldn’t design a Bob object type, we would want to generalize what Bob represents to make the object as useful as possible. After all there is bound to be more than one person you lend your books to. Therefore we create a person class. The tracking application can then create a new instance of a person class and fill it with data about Bob.
What Is the State of an Object?
Every object has a state. That is, at any point in time it can be described from the data it contains. Let’s look at Bob from next door again. Let’s say we designed our person class to store the following data about a person: their name, hair color, height, weight, and address. When a new person object is created and stores data about Bob, those properties go together to make Bob’s state. For instance today, Bob might have brown hair, be 205 pounds, and live next door. Tomorrow, Bob might have brown hair, be 200 pounds and have moved to a new address across town.
If we update the data in Bob’s person object to reflect his new weight and address we have changed the state of the object. In Java, the state of an object is held in fields. In the above example, we would have five fields in the person class; name, hair color, height, weight, and address.
What Is the Behavior of an Object?
Every object has behaviors. That is, an object has a certain set of actions that it can perform. Let’s go back to our very first object type – a book. Surely a book doesn’t perform any actions? Let’s say our book tracking application is being made for a library. There a book has lots of actions, it can be checked out, checked in, reclassified, lost, and so on. In Java, behaviors of an object are written in methods. If a behavior of an object needs to be performed, the corresponding method is called.
Let’s go back to the example once more. Our booking tracking application has been adopted by the library and we have defined a check out method in our book class. We have also added a field called borrower to keep track of who has the book. The check out method is written so that it updates the borrower field with the name of the person who has the book. Bob from next door goes to the library and checks out a book. The state of the book object is updated to reflect that Bob now has the book.
What Is Data Encapsulation?
One of the key concepts of object-oriented programming is that to modify an object’s state, one of the object’s behaviors must be used. Or to put it another way, to modify the data in one of the object’s fields, one of its methods must be called. This is called data encapsulation.
By enforcing the idea of data encapsulation on objects we hide the details of how the data is stored. We want objects to be as independent of each other as possible. An object holds data and the ability to manipulate it all in one place. This makes it is easy for us to use that object in more than one Java application. There’s no reason why we couldn’t take our book class and add it to another application that might also want to hold data about books.
If you want to put some of this theory into practice, you can join me in creating a Book class.
Creating an Instance of an Object
Designing and Creating Objects
Creating an Instance of an Object
To create an instance of the Book object we need a place to create it from. Make a new Java main class as shown below (save it as BookTracker.java in the same directory as your Book.java file):
public class BookTracker { public static void main(String[] args) { } } To create an instance of the Book object we use the "new" keyword as follows:
public class BookTracker { public static void main(String[] args) { Book firstBook = new Book(“Horton Hears A Who!”,”Dr. Seuss”,”Random House”); } }
Java Classes On the left hand side of the equals sign is the object declaration. It's saying I want to make a Book object and call it "firstBook". On the right hand side of the equals sign is the creation of a new instance of a Book object. What it does is go to the Book class definition and run the code inside the constructor method. So, the new instance of the Book object will be created with the title, author and publisher fields set to "Horton Hears A Who!", "Dr Suess" and "Random House" respectively. Finally, the equals sign sets our new firstBook object to be the new instance of the Book class.
Now let’s display the data in firstBook to prove that we really did create a new Book object. All we have to do is call the object’s displayBookData method:
public class BookTracker { public static void main(String[] args) { Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House"); firstBook.displayBookData(); } } The result is: Title: Horton Hears A Who! Author: Dr. Seuss Publisher: Random House
Multiple Objects
Multiple Objects
Now we can begin to see the power of objects. I could extend the program:
public class BookTracker { public static void main(String[] args) { Book firstBook = new Book(“Horton Hears A Who!”,”Dr. Seuss”,”Random House”); Book secondBook = new Book(“The Cat In The Hat”,”Dr. Seuss”,”Random House”); Book anotherBook = new Book(“The Maltese Falcon”,”Dashiell Hammett”,”Orion”); firstBook.displayBookData(); anotherBook.displayBookData(); secondBook.displayBookData(); } }
Java Classes From writing one class definition we now have the ability to create as many Book objects as we please!
Adding Methods
Adding Methods
Behaviors are the actions an object can perform and are written as methods. At the moment we have a class that can be initialized but doesn’t do much else. Let’s add a method called “displayBookData” that will display the current data held in the object:
public class Book { //fields private String title; private String author; private String publisher; //constructor method public Book(String bookTitle, String authorName, String publisherName) { //populate the fields title = bookTitle; author = authorName; publisher = publisherName; } public void displayBookData() { System.out.println(“Title: “ + title); System.out.println(“Author: “ + author); System.out.println(“Publisher: “ + publisher); } }
All the displayBookData method does is print out each of the class fields to the screen.
We could add as many methods and fields as we desire but for now let’s consider the Book class as complete. It has three fields to hold data about a book, it can be initialized and it can display the data it contains.
Yet Another Constructor Example : More Detailed Example (Java Programming)
Yet Another Constructor Example : More Detailed Example (Java Programming)
class Rectangle { int length; int breadth;
Rectangle() { length = 20; breadth = 10; }
void setDiamentions() { length = 40; breadth = 20; }
}
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle();
System.out.println(“Length of Rectangle : “ + r1.length);
System.out.println(“Breadth of Rectangle : “ + r1.breadth);
r1.setDiamentions();
System.out.println(“Length of Rectangle : “ + r1.length);
System.out.println(“Breadth of Rectangle : “ + r1.breadth);
} } Output : C:Priteshjava>java RectangleDemo Length of Rectangle : 20 Breadth of Rectangle : 10 Length of Rectangle : 40 Breadth of Rectangle : 20 Explanation : 1. After the Creation of Object , Instance Variables have their own values inside. 2. As soon as we call method , values are re-initialized.
Passing Object as Parameter (this one needs some thinking)
Passing Object as Parameter :
package com.pritesh.programs;
class Rectangle { int length; int width;
Rectangle(int l, int b) { length = l; width = b; }
void area(Rectangle r1) { int areaOfRectangle = r1.length * r1.width; System.out.println("Area of Rectangle : " \+ areaOfRectangle); } }
class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(10, 20); r1.area(r1); } }
Output of the program :
Area of Rectangle : 200
Explanation : 1. We can pass Object of any class as parameter to a method in java. 2. We can access the instance variables of the object passed inside the called method. area = r1.length * r1.width 3. It is good practice to initialize instance variables of an object before passing object as parameter to method otherwise it will take default initial values. Different Ways of Passing Object as Parameter : Way 1 : By directly passing Object Name void area(Rectangle r1) { int areaOfRectangle = r1.length * r1.width; System.out.println("Area of Rectangle : " \+ areaOfRectangle); }
class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(10, 20); r1.area(r1); } Way 2 : By passing Instance Variables one by one package com.pritesh.programs;
class Rectangle { int length; int width;
void area(int length, int width) { int areaOfRectangle = length * width; System.out.println("Area of Rectangle : " \+ areaOfRectangle); } }
class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle();
r1. length = 20; r1. width = 10;
r2.area(r1.length, r1.width); } } Actually this is not a way to pass the object to method. but this program will explain you how to pass instance variables of particular object to calling method. Way 3 : We can pass only public data of object to the Method. Suppose we made width variable of a class private then we cannot update value in a main method since it does not have permission to access it. private int width; after making width private – class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle();
r1. length = 20; r1. width = 10; r2.area(r1.length, r1.width); } }
Method Overloading :
Method Overloading :
- In Java we can define number of methods in a class with the same name.
- Defining two or more methods with the same name in a class is called method overloading.
- Compile determine which method to execute automatically.
- The return type has no effect on the signature of a method.
What is signature of the method ? - The name of a method along with the types and sequence of the parameters is called signature of the method
- Signature of the method should be unique.
Signature of the method includes – - No of Parameters
- Different Parameters
- Sequence of the parameters
- Some Examples of the Method Overloading :
int display(int num1,int num2); Or int display(double num1,int num2); Or void display(double num1,double num2); Live Example :
package com.pritesh.programs;
class Rectangle { double length; double breadth;
void area(int length, int width) { int areaOfRectangle = length * width; System.out.println("Area of Rectangle : " + areaOfRectangle); }
void area(double length, double width) { double areaOfRectangle = length * width; System.out.println("Area of Rectangle : " + areaOfRectangle); }
}
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle(); r1. area(10, 20); r1. area(10.50, 20.50); } } Explanation : 1. We have defined 2 methods with same name and different type of parameters. 2. When both integer parameters are supplied to the method then it will execute method with all integer parameters and if we supply both floating point numbers as parameter then method with floating numbers will be executed.
Parameterized Constructors : Constructor Taking Parameters
Parameterized Constructors : Constructor Taking Parameters
In this article we are talking about constructor that will take parameter. Constructor taking parameter is called as “Parameterized Constructor“.
Parameterized Constructors :
Constructor Can Take Value , Value is Called as – “Argument“.
Argument can be of any type i.e Integer,Character,Array or any Object.
Constructor can take any number of Argument.
See following example – How Parameterized Constructor Works ? –
Live Example : Constructor Taking Parameter in Java Programming
class Rectangle { int length; int breadth;
Rectangle(int len,int bre) { length = len; breadth = bre; } }
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle(20,10);
System.out.println(“Length of Rectangle : “ + r1.length);
System.out.println(“Breadth of Rectangle : “ + r1.breadth);
}
}
Output :
Length of Rectangle : 20
Breadth of Rectangle : 10
Explanation :
Carefully observe above program – You will found something like this –
Rectangle r1 = new Rectangle(20,10); This is Parameterized Constructor taking argument.These arguments are used for any purpose inside Constructor Body. Parameterized Constructor - Constructor Taking Argument
New Operator is used to Create Object. We are passing Parameter to Constructor as 20,10. These parameters are assigned to Instance Variables of the Class. We can Write above statement like – Rectangle(int length,int breadth) { length = length; breadth = breadth; } OR
Rectangle(int length,int breadth) { this.length = length; this.breadth = breadth; } But if we use Parameter name same as Instance variable then compiler will recognize instance variable and Parameter but user or programmer may confuse. Thus we have used “this keyword” to specify that “Variable is Instance Variable of Object – r1“.
this keyword : Refer Current Object in Java Programming
this keyword : Refer Current Object in Java Programming
- this is keyword in Java.
- We can use this keyword in any method or constructor.
- this keyword used to refer current object.
- Use this keyword from any method or constructor to refer to the current object that calls a method or invokes constructor .
Syntax : this Keyword
this.field
Live Example : this Keyword
class Rectangle { int length; int breadth;
void setDiamentions(int ln,int br) { this.length = ln; this.breadth = br; }
}
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.setDiamentions(20,10);
System.out.println(“Length of Rectangle : “ + r1.length);
System.out.println(“Breadth of Rectangle : “ + r1.breadth);
}
}
Output :
Length of Rectangle : 20
Breadth of Rectangle : 10
this Keyword is used to hide Instance Variable :
void setDiamentions(int length,int breadth)
{
this.length = length;
this.breadth = breadth;
}
* length,breadth are the parameters that are passed to the method.
* Same names are given to the instance variables of an object.
* In order to hide instance variable we can use this keyword. above syntax will clearly make difference between instance variable and parameter.
*
Returning Value From the Method :
Returning Value From the Method :
- We can specify return type of the method as “Primitive Data Type” or “Class name”.
- Return Type can be “Void” means it does not return any value.
- Method can return a value by using “return” keyword.
Live Example : Returning Value from the Method class Rectangle { int length; int breadth;
void setLength(int len) { length = len; }
int getLength() { return length; }
}
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.setLength(20);
int len = r1.getLength();
System.out.println(“Length of Rectangle : “ + len);
}
}
Output :
Length of Rectangle : 20 There are two important things to understand about returning values : 1. The type of data returned by a method must be compatible with the return type specified by the method. For example, if the return type of some method is boolean, you could not return an integer. boolean getLength() { int length = 10; return(length); } 2. The variable receiving the value returned by a method (such as len, in this case) must also be compatible with the return type specified for the method. int getLength() { return length; }
boolean len = r1.getLength(); 3. Parameters should be passed in sequence and they must be accepted by method in the same sequence. void setParameters(String str,int len) { ----- ----- ----- }
r1.setParameters(12,"Pritesh"); Instead it should be like – void setParameters(int length,String str) { ----- ----- ----- }
r1.setParameters(12,”Pritesh”);
Introducing Methods in Java Class : Class Concept in Java
Introducing Methods in Java Class : Class Concept in Java
- In Java Class , We can add user defined method.
- Method is equivalent to Functions in C/C++ Programming.
Syntax : Methods in Java Classes
return_type method_name ( arg1 , arg2 , arg3 )
1. return_type is nothing but the value to be returned to an calling method.
2. method_name is an name of method that we are going to call through any method.
3. arg1,arg2,arg3 are the different parameters that we are going to pass to a method.
Return Type of Method :
1. Method can return any type of value.
2. Method can return any Primitive data type
int sum (int num1,unt num2);
3. Method can return Object of Class Type.
Rectangle sum (int num1,unt num2);
4. Method sometimes may not return value.
void sum (int num1,unt num2);
Method Name :
1. Method name must be valid identifier.
2. All Variable naming rules are applicable for writing Method Name.
Parameter List :
1. Method can accept any number of parameters.
2. Method can accept any data type as parameter.
3. Method can accept Object as Parameter
4. Method can accept no Parameter.
5. Parameters areseparatedby Comma.
6. Parameter must have Data Type
Live Example : Introducing Method in Java Class
class Rectangle {
double length;
double breadth;
void setLength(int len) { length = len; } }
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.length = 10;
System.out.println(“Before Function Length : “ + r1.length);
r1.setLength(20);
System.out.println(“After Function Length : “ + r1.length);
}
}
Output :
C:Priteshjava>java RectangleDemo
Before Function Length : 10.0
After Function Length : 20.0
Explanation :
Calling a Method :
1. “r1” is an Object of Type Rectangle.
2. We are calling method “setLength()” by writing –
Object_Name [DOT] Method_Name ( Parameter List ) ;
3. Function call is always followed by Semicolon.
Method Definition :
1. Method Definition contain the actual body of the method.
2. Method can take parameters and can return a value.
Java assigning object reference
Java assigning object reference
Assigning Object Reference Variables : Class Concept in Java Programming
1. We can assign value of reference variable to another reference variable.
2. Reference Variable is used to store the address of the variable.
3. Assigning Reference will not create distinct copies of Objects.
4. All reference variables arereferringto same Object.
Assigning Object Reference Variables does not –
1. Create Distinct Objects.
2. Allocate Memory
3. Create duplicate Copy
Consider This Example –
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
* r1 is reference variable which contain the address of Actual Rectangle Object.
* r2 is another reference variable
* r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it does not create duplicate object , nor does it allocate extra memory.
[468×60] Live Example :Assigning Object Reference Variables class Rectangle { double length; double breadth; }
class RectangleDemo { public static void main(String args[]) {
Rectangle r1 = new Rectangle(); Rectangle r2 = r1;
r1. length = 10;
r2. length = 20;
System.out.println(“Value of R1’s Length : “ + r1.length);
System.out.println(“Value of R2’s Length : “ + r2.length);
} } Output : C:Priteshjava>java RectangleDemo Value of R1's Length : 20.0 Value of R2's Length : 20.0 Typical Concept : Suppose we have assigned null value to r2 i.e Rectangle r1 = new Rectangle(); Rectangle r2 = r1; . . . r1 = null; Note : Still r2 contain reference to an object. Thus We can create have multiple reference variables to hold single object. [468×60]