Basic Java Concepts Flashcards

1
Q

HOW MANY MAIN GROUPS are there that encompasses the different kind of statements in Java

A

There are three main groups that encompass the different kinds of statements in Java:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

WHAT ARE THE THREE MAIN GROUPS OF STATEMENTS

A

(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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

DEFINITION OF STATEMENTS

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Definition: expressions

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Examples of EXPRESSIONS

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Definition: statement(2)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

FIELD

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

The Constructor Method

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

The Class Declaration

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Data Encapsulation

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Constructors : Initializing an Class Object in Java Programming

A

Constructors : Initializing an Class Object in Java Programming

  1. Objects contain there own copy of Instance Variables.
  2. It is very difficult to initialize each and every instance variable of each and every object of Class.
  3. Java allows objects to initialize themselves when they are created. Automatic initialization is performed through the use of a constructor.
  4. A Constructor initializes an object as soon as object gets created.
  5. Constructor gets called automatically after creation of object and before completion of new Operator.
    Some Rules of Using Constructor :
  6. Constructor Initializes an Object.
  7. Constructor cannot be called like methods.
  8. Constructors are called automatically as soon as object gets created.
  9. Constructor don’t have any return Type. (even Void)
  10. Constructor name is same as that of “Class Name“.
  11. 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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Accessors and mutators

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Introduction to Object-Oriented Programming

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Creating an Instance of an Object

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Multiple Objects

A

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!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Adding Methods

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Yet Another Constructor Example : More Detailed Example (Java Programming)

A

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.
18
Q

Passing Object as Parameter (this one needs some thinking)

A

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);
} }
19
Q

Method Overloading :

A

Method Overloading :

  1. In Java we can define number of methods in a class with the same name.
  2. Defining two or more methods with the same name in a class is called method overloading.
  3. Compile determine which method to execute automatically.
  4. The return type has no effect on the signature of a method.
    What is signature of the method ?
  5. The name of a method along with the types and sequence of the parameters is called signature of the method
  6. Signature of the method should be unique.
    Signature of the method includes –
  7. No of Parameters
  8. Different Parameters
  9. Sequence of the parameters
  10. 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.
20
Q

Parameterized Constructors : Constructor Taking Parameters

A

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“.
21
Q

this keyword : Refer Current Object in Java Programming

A

this keyword : Refer Current Object in Java Programming

  1. this is keyword in Java.
  2. We can use this keyword in any method or constructor.
  3. this keyword used to refer current object.
  4. 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.
*

22
Q

Returning Value From the Method :

A

Returning Value From the Method :

  1. We can specify return type of the method as “Primitive Data Type” or “Class name”.
  2. Return Type can be “Void” means it does not return any value.
  3. 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”);

23
Q

Introducing Methods in Java Class : Class Concept in Java

A

Introducing Methods in Java Class : Class Concept in Java

  1. In Java Class , We can add user defined method.
  2. 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.

24
Q

Java assigning object reference

A

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]





25
Q

The null Keyword : Null Reference inside Instance Variable

A

The null Keyword : Null Reference inside Instance Variable

  1. A reference variable refers to an object.
  2. When a reference variable does not have a value (it is not referencing an object) such a reference variable is said to have a null value.
Live Example : Null Value
class Rectangle {
  double length;
  double breadth;
}
class RectangleDemo {
  public static void main(String args[]) {

Rectangle myrect1;
System.out.println(myrect1.length);

  }
}
Output :
C:Priteshjava>javac RectangleDemo.java
RectangleDemo.java:10: variable myrect1 might not have
been initialized
  System.out.println(myrect1.length);
                     ^
1 error
[468×60]
Explanation : Null Value
1. As explained in the previous chapter , Creating Object is two step process.
2. In the above example myrect is not initialized.
3. Default value inside myrect1 is null , means it does not contain any reference.
4. If you are declaring reference variable at “Class Level” then you don’t need to initialize instance variable with null. (Above Error Message : error is at println stetement)
Checking null Value
class Rectangle {
  double length;
  double breadth;
}
class RectangleDemo {
  public static void main(String args[]) {

Rectangle myrect1;

  if(myrect1 == null)
     {
     myrect1 = new Rectangle();
     }

}
}
* We can check null value using “==” operator.
Different Ways Of Null Value Statements :
Way 1 : Class Level null Value
1. No need to initialize instance variable with null.
2. Instance Variable contain default value as “null”.
3. Meaning of “null” is that – Instance Variable does not reference to any object.
Rectangle myrect1;
is similar to –
Rectangle myrect1 = null;
Way 2 : Method Level null Value
1. Suppose we have to create any object inside “Method” then we must initialize instance variable with Null value.
2. If we forgot to initialize instance variable with null then it will throw compile time error.
Valid Declaration :
Rectangle myrect1 = null;
Invalid Declaration :
Rectangle myrect1 ;
[336×280]

26
Q

Java assigning object reference

A

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]





27
Q

Java declaring object in class

A

Java declaring object in class


Declaring Object in Class : Declaring Reference to an Object in Java Programming
1. When we create class then we are creating new data type.
2. Newly created data type is used to create an Object of that Class Type.
3. Creating object is two step process.
Creation of Object involves two steps –
1. Declaration
2. Allocation and Assigning
Rectangle myrect1 = new Rectangle();
this statement is used to create an object we are going to break down this statement in two separate statements –
Rectangle myrect1 ;
myrect1 = new Rectangle();
Step 1 : Declaration of Variable of Type Class

  1. Above Declaration will just declare a variable of class type.
  2. Declared Variable is able to store the reference to an object of Rectangle Type.
  3. As we have not created any object of class Rectangle and we haven’t assigned any reference to myrect1 , it will be initialized with null.
    Step 2 : Allocation and Assigning Object to variable of class Type
  4. Above Statement will create physical copy of an object.
  5. This Physical Copy is then assigned to an variable of Type Class i.e myrect1.
  6. Note : myrect1 holds an instance of an object not actual object. Actual Object is created elsewhere and instance is assigned to myrect1.
    In short –
  7. First statement will just create variable myrect1 which will store address of actual object.
  8. First Statement will not allocate any physical memory for an object thus any attempt accessing variable at this stage will cause compile time error.
  9. Second Statement will create actual object ranndomly at any memory address where it found sufficient memory.
  10. Actual memory address of Object is stored inside myrect1.
28
Q

Java classes

A

Java classes

Live Example : Simple Class Program [Area of Rectangle]
class Rectangle {
  double length;
  double breadth;
}
// This class declares an object of type Rectangle.
class RectangleDemo {
  public static void main(String args[]) {
    Rectangle myrect = new Rectangle();
    double area;
// assign values to myrect's instance variables

myrect. length = 10;
myrect. breadth = 20;
    // Compute Area of Rectangle
    area =  myrect.length * myrect.breadth ;
System.out.println("Area is " + area);   } } Output : C:Priteshjava>java RectangleDemo Area is 200.0 [336×280] Explanation : Class Concept 1. Class Creation / Declaration : Consider following class – class Rectangle {   double length;   double breadth; } * class defines a new type of data. * Rectangle is our new data type. * “Rectangle” will be used to declare objects of type Rectangle. * class declaration only creates a template. It does not create an actual object. 2. Creation of Object Rectangle myrect = new Rectangle(); * Actual Creation of Object. * Memory is allocated for an object after executing this statement. * This Statement will create instance of the class “Ractangle” and name of instance is nothing but actual object “myrect“. * Fresh copy of Instance variables gets created for Fresh Instance. [myrect now have its own instance variables -> length,breadth ] * Following fig shows one unknown term – Constructor(Don’t worry about this term , you will get more details in the incoming chapters)
  1. Accessing Instance Variables Of Object/Instance using DOT Operator
    myrect.length = 10;
    myrect.breadth = 20;
    * As explained earlier , Each Instance/Object gets their own copy of instance variables i.e length and breadth.
    * We can access “myrect’s” copy of instance variable using “DOT” operator (as shown above).
    [468×60]
    Steps to Run Above Program
  2. Create RectangleDemo.java . [suppose your file have multiple classes then you must save file with class name that contain main class ]
  3. Copy Above Program into RectangleDemo.java and save it.
  4. Run MyRectangle.java inside Command Prompt.
29
Q

A. Introducing Class Concept in Java Programming

A
A. Introducing Class Concept in Java Programming
In the previous article we have learned the basics of class and object related to real life.In this chapter we are going to see the basic programmatic syntax of class.
B. Syntax : Class Concept
class classname {
    type instance-variable1;
    type instance-variable2;
    // ...
    type instance-variableN;
    type methodname1(parameter-list) {
      // body of method
    }
    type methodname2(parameter-list) {
      // body of method
    }
    // ...
    type methodnameN(parameter-list) {
      // body of method
    }
}
C. Explanation Of Syntax :
Class name
class classname {
1. class is Keyword in Java used to create class in java.
2. classname is Name of the User defined Class.
Class Instance Variable
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
1. Instance Variables are Class Variables of the class.
2. When a number of objects are created for the same class, the same copy of instance variable is provided to all.
3. Instance variables have different value for different objects.
4. Access Specifiers can be applied to instance variable i.e public,private.
5. Instance Variable are also called as “Fields“
Class Methods
type methodname1(parameter-list) {
      // body of method
    }
8. Above syntax is of Class Methods.
9. These methods are equivalent to function in C Programming Language.
10. Class methods can be declared public or private.
11. These methods are meant for operating on class data i.e Class Instance Variables.
12. Methods have return type as well as parameter list. We are going to learn this concept deeply in next few tutorials.
D. Live Example : Class concept
public class Rectangle {
    // two fields
    public int breadth;
    public int length;
    // two methods
    public void setLength(int newValue) {
        length = newValue;
    }
public void setBreadth(int newValue) {
    breadth = newValue;
}
}
Explanation :
Rectangle
Class name
length
Instance Variable
breadth
Instance Variable
setLength()
Method
setBredth()
Method

As soon as we create this class , Inside memory it would looks like –

[box][**]In the above program we have written “public” means this class is accessible to others.[/box]

30
Q

Class Concept in Java Programming | Explained with Real Life Example:

A

Class Concept in Java Programming | Explained with Real Life Example :
Consider Person as a class. Now we can have some properties associated with this class Person such as
Attributes of Person :
1. Name of Person
2. Gender
3. Skin Color
4. Hair Color etc.
Now these are the general properties which forms template of the class Person,and above properties of the are called as Attributes of the Class.
Now Person class may have some core functionality such as –
1. Talking
2. Walking
3. Eating
Thus in short Class have –
1. Class name
2. Properties or Attributes
3. Common Functions
Now ,we are going to create objects of the class , i.e actual instance of the class. Let us say that we have created objects such as “Ram”,”Sam”. Both will have same attributes andfunctionality but have different attribute value.

Now this is just a template , called as “Class” , and Object is instance of the class.

Summary : Class Concept in Java Programming (Quick Look Class)

*Reference : Here
Syntax of Class :
* A Class is a blueprint or a template to create objects of identical type.
* A Class is core concept of Object Oriented Programming Language.
class classname {
    type instance-variable1;
    type instance-variable2;
    // ...
    type instance-variableN;
    type methodname1(parameter-list) {
      // body of method
    }
    type methodname2(parameter-list) {
      // body of method
    }
    // ...
    type methodnameN(parameter-list) {
      // body of method
    }
}
31
Q

SOME THINGS WE KNOW ABOUT CONSTRUCTORS.

A

(1) Ajava constructorhas the same name as the name of the class to which it belongs.
(2) Constructor’s syntax does not include a return type, since constructors never return a value.
(3) Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
(5) Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

32
Q

(1) INTRODUCTION TO JAVA CONSTRUCTORS.
(2) JAVA OVERLOADED CONSTRUCTORS
(3) CONSTRUCTOR CHAINING

A

INTRODUCTION TO JAVA CONSTRUCTORS

Ajava constructorhas the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
	Cube1() {
		length = 10;
		breadth = 10;
		height = 10;
	}
	Cube1(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
	}
	public static void main(String[] args) {
		Cube1 cubeObj1, cubeObj2;
		cubeObj1 = new Cube1();
		cubeObj2 = new Cube1(10, 20, 30);
		System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
		System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
	}
}


Note:If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.
JAVA OVERLOADED CONSTRUCTORS
Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context
public class Cube2 {
	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
	Cube2() {
		this(10, 10);
		System.out.println("Finished with Default Constructor");
	}
	Cube2(int l, int b) {
		this(l, b, 10);
		System.out.println("Finished with Parameterized Constructor having 2 
                   params");
	}
	Cube2(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
		System.out.println("Finished with Parameterized Constructor having 3 
                   params");
	}
	public static void main(String[] args) {
		Cube2 cubeObj1, cubeObj2;
		cubeObj1 = new Cube2();
		cubeObj2 = new Cube2(10, 20, 30);
		System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
		System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
	}
}

public class Cube2 {

	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
	Cube2() {
		this(10, 10);
		System.out.println("Finished with Default Constructor");
	}
	Cube2(int l, int b) {
		this(l, b, 10);
		System.out.println("Finished with Parameterized Constructor having 2 
                  params");
	}
	Cube2(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
		System.out.println("Finished with Parameterized Constructor having 3 
                   params");
	}
	public static void main(String[] args) {
		Cube2 cubeObj1, cubeObj2;
		cubeObj1 = new Cube2();
		cubeObj2 = new Cube2(10, 20, 30);
		System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
		System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
	}
}
Output
Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

DownloadCube2.java
CONSTRUCTOR CHAINING
Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.
class Cube {
	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
	Cube() {
		this(10, 10);
		System.out.println("Finished with Default Constructor of Cube");
	}
	Cube(int l, int b) {
		this(l, b, 10);
		System.out.println("Finished with Parameterized Constructor having
			2 params of Cube");
	}
	Cube(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
		System.out.println("Finished with Parameterized Constructor having
			3 params of Cube");
	}
}

public class SpecialCube extends Cube {

int weight;
SpecialCube() {
	super();
	weight = 10;
}
SpecialCube(int l, int b) {
	this(l, b, 10);
	System.out.println("Finished with Parameterized Constructor having
				2 params of SpecialCube");
}
SpecialCube(int l, int b, int h) {
	super(l, b, h);
	weight = 20;
	System.out.println("Finished with Parameterized Constructor having
				3 params of SpecialCube");
}
public static void main(String[] args) {
	SpecialCube specialObj1 = new SpecialCube();
	SpecialCube specialObj2 = new SpecialCube(10, 20);
	System.out.println("Volume of SpecialCube1 is : "
			\+ specialObj1.getVolume());
	System.out.println("Weight of SpecialCube1 is : "
			\+ specialObj1.weight);
	System.out.println("Volume of SpecialCube2 is : "
			\+ specialObj2.getVolume());
	System.out.println("Weight of SpecialCube2 is : "
			\+ specialObj2.weight);
} } DownloadSpecialCube.java Output Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20 The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors.
if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.

Note:If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.
Below is an example of a class demonstrating constructor chaining using explicit super() call.
class Cube {

	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
	Cube(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
		System.out.println("Finished with Parameterized Constructor having
								3 params of Cube");
	}
}

public class SpecialCube1 extends Cube {

	int weight;
	SpecialCube1() {
		super(10, 20, 30); //Will Give a Compilation Error without this line
		weight = 10;
	}
	public static void main(String[] args) {
		SpecialCube1 specialObj1 = new SpecialCube1();
		System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume());
	}
}
Output
Finished with Parameterized Constructor having 3 params of Cube
Volume of SpecialCube1 is : 6000





33
Q

Java - Basic Language Elements

Keywords etc

A

Java - Basic Language Elelemnts

(Identifiers, keywords, literals, white spaces and comments)
This part of the java tutorial teaches you thebasic language elementsand syntax for the java programming language. Once you get these basic language concepts you can continue with the other object oriented programming language concepts.
KEYWORDS
There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case.
Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
Keywords are marked in yellow as shown in the sample code below
/** This class is a Hello World Program used to introducethe Java Language/
 public class HelloWorld {
 public static void main(String[] args) {
 System.out.println(“Hello World”); //Prints output to console
For more information on different Keywords– Java Keywords
Some Tricky Observations:The words virtual, ifdef, typedef, friend, struct and union are all words related to
the C programming language. const and goto are Java keywords. The word finalize is the name of a method
of the Object class and hence not a keyword. enum and label are not keywords.
COMMENTS
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program.
Java supports three comment styles.
Block stylecomments begin with /
and terminate with */ that spans multiple lines.
Line stylecomments begin with // and terminate at the end of the line. (Shown in the above program)
Documentation stylecomments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.
VARIABLE, IDENTIFIERS AND DATA TYPES
Variablesare used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known asidentifiers. An Identifier must be unique within a scope of the Java program. Variables have adata type, that indicates the kind of value they can store. Variables declared inside of a block or method are calledlocal variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.
public class localVariableEx {
public static int a;
public static void main(String[] args) {
int b;
System.out.println(“a : “+a);
System.out.println(“b : “+b); //Compilation error
}}
Notein the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.
data typeindicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data types.
* Integer:byte, short, int, and long.
* Floating Point:float and double
* Character:char
* Boolean:variable with a value of true or false.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.
Data Type
Default Value (for fields)
Range
byte
0
-127 to +128
short
0
-32768 to +32767
int
0

long
0L

float
0.0f

double
0.0d

char
‘\u0000′
0 to 65535
String (object)
null

boolean
false

When we declare a variable we assign it an identifier and a data type.
For Example
String message = “hello world”
In the above statement, String is thedata typefor theidentifiermessage. If you don’t specify a value when the variable is declared, it will be assigned the default value for its data type.
Identifier Naming Rules
* Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character.
* Must begin with a letter, dollar sign, or an underscore
* Are case sensitive
* Keywords cannot be used as identifiers
* Within a given section of your program or scope, each user defined item must have a unique identifier
* Can be of any length.
CLASSES
A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.
OBJECTS
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
INTERFACE
An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.
INSTANCE MEMBERS
Each object created will have its own copies of the fields defined in its class called instance variables which represent an object’s state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot ‘.’ notation with a object reference is used to access Instance Members.
STATIC MEMBERS
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed above.
/** Comment
* Displays “Hello World!” to the standard output.

 */
public class HelloWorld {
      String output = "";
      static HelloWorld helloObj;  //Line 1 
      public HelloWorld(){
            output = "Hello World";
      } 
  public String printMessage(){
        return output;
  } 
      public static void main (String args[]) {
            helloObj = new HelloWorld();  //Line 2
            System.out.println(helloObj.printMessage());
  }

}
Class Name:HelloWorld
Object Reference:helloObj (in Line 1)
Object Created:helloObj (In Line 2)
Member Function:printMessage
Field:output (String)
Static Member:helloObj
Instance Member :output (String)

34
Q
  • How to Write and Use a Java Method
A
  • How to Write and Use a Java Method

by Nancy Sewell
Simple Java Method
Sometimes the terms function and method are used interchangeably. They are virtually the same. The correct terminology for Java is method. It is a set of commands that can be used over again. In this, they share similarities with sub routines in the early days of programming.
  • 
1. 
A simple Java method requires a minimum of three items:
Visibility : public, private, protected
Return Type: void, int, double, (etc.)
name: whatever you want to call the method

Visibility means who can access it. If it is public, anyone who has access to your class file can access the method. In some circumstances, this is perfectly fine. If the method is private, only the functions inside of that class can call the method. This is used as utility methods to do something you do not want just anyone who uses the class to do. Protected gives public function to all child classes.
Return type is void if you do not want the method to give you any data back. It would be used for such things as a method that prints out something. Any other return requires a return statement with the type of data it returns. For example, if you add two integers and want the results of that integer, your return type would be int.
Name of the method is anything you choose that is not already used in the class (unless you are overloading the method which is beyond the scope of this article)
If you want the method to do something with the data you supply it, you also need to include parameters within the ( ) You include what data type it is and give that parameter a name (ie: you are declaring a local variable for that method only)
2. 
examples:
access return type name parameters 
public void add (int a, int b)

  • 
This would be written

    * public void add(int a, int b)
    * {
    * // do stuff here
    * }
  • Since the return type is void, you will have to write what you want the method to do inside of the method such as by printing it out from the method

    * public void add(int a, int b)
    * {
    * System.out.println(a+b);
    * }
  • To use the above method, you would simply call that method and inserting the two integers that will go into the integer parameters:

    * add(7, 4);
  • If we want to use the results for something else within our main method, we will need a return type. Since we are adding integers, int return type is adequate:

    * public int add(int a, int b)
    * {
    * // do stuff here
    * // return type required
    * }
  • Since we have an integer return type, we need to have a return statement that will return an int. We can use a local variable (c) to hold the result and return the value of that local variable. Note that c must be the same datatype as the return type - which is int in this example:

    * public static int add(int a, int b)
    * {
    * int c = a+b;
    * return c;
    * }
  • This can also be shortened to do away with the local variable:
    * public static int add(int a, int b)
    * {
    * return a + b;
    * }
    1. 
In order to use the above with the int return type, In the main method you can either set a variable to the result:

      • int temp = add(5, 7);
  • or you can print out the result by calling it in your print statement:

    * System.out.println( add(3,3));
  • 
I know this is very simple. I found that sometimes instructors fail to explain the simple things to students assuming they already know it. This is meant for beginner students who are not understanding the concept and is not meant for those who are already accomplished programmers.
35
Q

Aclasshas the following general syntax

A

Aclasshas the following general syntax:

 class
  {
 // Dealing with Classes (Class body)
 
 
 
 
 
 
}
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().
public class Cube {
	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
}
36
Q

Java Class Example

A

Java Class Example

  1. /*

  2. Java Class example.

  3. This Java class example describes how class is defined and being used

  4. in Java language.

  5. Syntax of defining java class is,

  6. class {

  7. // members and methods

  8. }

  9. */

  10. public class JavaClassExample{

  11. /*

  12. Syntax of defining memebers of the java class is,

  13. type ;

  14. */

  15. private String name;

  16. /*

  17. Syntax of defining methods of the java class is,

  18. methodName() {

  19. …

  20. }

  21. */

  22. public void setName(String n){

  23. //set passed parameter as name

  24. name = n;

  25. }

  26. public String getName(){

  27. //return the set name

  28. return name;

  29. }

  30. //main method will be called first when program is executed

  31. public static void main(String args[]){

  32. /*

  33. Syntax of java object creation is,

  34. object-name = new ;

  35. */

  36. JavaClassExample javaClassExample = new JavaClassExample();

  37. //set name member of this object

  38. javaClassExample.setName(“Visitor”);

  39. // print the name

  40. System.out.println(“Hello “ + javaClassExample.getName()); 

  41. }

  42. }

  43. /*

  44. OUTPUT of the above given Java Class Example would be :

  45. Hello Visitor

  46. */

37
Q
  • How to Define and Use A Java Array
A
  • How to Define and Use A Java Array

by Nancy Sewell
Beginner Java: Simple array
Java Arrays are data structures containing objects of the same type. A String array can only contain Strings and a Car array can only contain car objects. Arrays are used to store objects that you want to use in other calculations or want to reference to. For example, an array can contain grades that can be averaged or referenced.

Things You’ll Need
      1. 
When you declare a Java array, you need to give it a data type when you declare it just like you would give a variable a datatype.
For example, we will declare an integer array containing five elements which we will name arrayName
 int[] arrayName = new int[5];
2. 
When you need to access an element of the array you can do so directly :
 System.out.println(arrayName[3] ); 
or you can print out the entire array using a for loop - first put some values in it so we can see what is going on. Remember arrays start numbering with 0 so an array with a length of five has elements numbered from 0-4 and not 1-5.
 arrayName[0] = 000; 
 arrayName[1] = 111; 
 arrayName[2] = 222; 
 arrayName[3] = 333; 
 arrayName[4] = 444; 

To print out the entire array (five is the size of the array):
 for (int i=0; i
38
Q

JAVA ACCESS SPECIFIERS

A

JAVA ACCESS SPECIFIERS
The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.
Access Modifiers
1. private
2. protected
3. default
4. public
public access modifier
Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.
private access modifier
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.
protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.
default access modifier
Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

39
Q

Java Control Flow Statements

A

Java Control Flow Statements

Java Control statementscontrol the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;
Selection statements:if, if-else and switch.
Loop statements:while, do-while and for.
Transfer statements:break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution
SELECTION STATEMENTS
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if ()

Below is an example that demonstrates conditional execution based on if statement condition.

public class IfStatementDemo {

	public static void main(String[] args) {
		int a = 10, b = 20;
		if (a > b)
			System.out.println("a > b");
		if (a < b)
			System.out.println("b > a");
	}
}
Output
b > a
DownloadIfStatementDemo.java
The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
  if ()
  
  else
 
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo {
	public static void main(String[] args) {
		int a = 10, b = 20;
		if (a > b) {
			System.out.println("a > b");
		} else {
			System.out.println("b > a");
		}
	}
}
DownloadIfElseStatementDemo.java
Switch Case StatementThe switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.Its general form is as follows:
 switch () {
 caselabel1:
  caselabel2:
    …
  caselabeln:
  default:
 } // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {
	public static void main(String[] args) {
		int a = 10, b = 20, c = 30;
		int status = -1;
		if (a > b &amp;&amp; a > c) {
			status = 1;
		} else if (b > c) {
			status = 2;
		} else {
			status = 3;
		}
		switch (status) {
		case 1:
			System.out.println("a is the greatest");
			break;
		case 2:
			System.out.println("b is the greatest");
			break;
		case 3:
			System.out.println("c is the greatest");
			break;
		default:
			System.out.println("Cannot be determined");
		}
	}
}
Output
c is the greatest
40
Q

Introduction to Java Inheritance

A

Introduction to Java Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. ClassInheritance in javamechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.
Java Inheritance Example - 1
class Box {

	double width;
	double height;
	double depth;
	Box() {
	}
	Box(double w, double h, double d) {
		width = w;
		height = h;
		depth = d;
	}
	void getVolume() {
		System.out.println("Volume is : " + width * height * depth);
	}
}

public class MatchBox extends Box {

	double weight;
	MatchBox() {
	}
	MatchBox(double w, double h, double d, double m) {
		super(w, h, d);
		weight = m;
	}
	public static void main(String args[]) {
		MatchBox mb1 = new MatchBox(10, 10, 10, 10);
		mb1.getVolume();
		System.out.println("width of MatchBox 1 is " + mb1.width);
		System.out.println("height of MatchBox 1 is " + mb1.height);
		System.out.println("depth of MatchBox 1 is " + mb1.depth);
		System.out.println("weight of MatchBox 1 is " + mb1.weight);
	}
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
What is not possible using java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass
Java Inheritance Example - 2
class Vehicle {
	// Instance fields
	int noOfTyres; // no of tyres
	private boolean accessories; // check if accessorees present or not
	protected String brand; // Brand of the car
	// Static fields
	private static int counter; // No of Vehicle objects created
	// Constructor
	Vehicle() {
		System.out.println("Constructor of the Super class called");
		noOfTyres = 5;
		accessories = true;
		brand = "X";
		counter++;
	}
	// Instance methods
	public void switchOn() {
		accessories = true;
	}
	public void switchOff() {
		accessories = false;
	}
	public boolean isPresent() {
		return accessories;
	}
	private void getBrand() {
		System.out.println("Vehicle Brand: " + brand);
	}
	// Static methods
	public static void getNoOfVehicles() {
		System.out.println("Number of Vehicles: " + counter);
	}
}

class Car extends Vehicle {

	private int carNo = 10;
	public void printCarInfo() {
		System.out.println("Car number: " + carNo);
		System.out.println("No of Tyres: " + noOfTyres); // Inherited.
		//  System.out.println("accessories: "    + accessories); 
                // Not Inherited.
		System.out.println("accessories: " + isPresent()); // Inherited.
		//        System.out.println("Brand: "     + getBrand());  
               // Not Inherited.
		System.out.println("Brand: " + brand); // Inherited.
		//  System.out.println("Counter: "    + counter);     // Not Inherited.
		getNoOfVehicles(); // Inherited.
	}
}

public class VehicleDetails { // (3)

	public static void main(String[] args) {
		new Car().printCarInfo();
	}
}
Output
Constructor of the Super class called
Car number: 10
No of Tyres: 5
accessories: true
Brand: X
Number of Vehicles: 1

THIS AND SUPER KEYWORDS
The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class.
The this reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the this reference. Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.
THIS AND SUPER Example
class Counter {

	int i = 0;
	Counter increment() {
		i++;
		return this;
	}
	void print() {
		System.out.println("i = " + i);
	}
}

public class CounterDemo extends Counter {

public static void main(String[] args) {
	Counter x = new Counter();
	x.increment().increment().increment().print();
} } Output Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
41
Q

JAVA PACKAGES

A
Java packages

Packages are containers for classes. Packages are collection of similar type of classes in Java. In java there are two types of packages – User Defined Package and Built in Packages.
A. Need of Packaging :
1. Maintainability : Suppose we are developing the big project then instead of keeping all the classes together under same name we can categorize them in the different folders called package.
2. Avoid Confusion : If Java provides us complete code in single package then it would be very difficult to get required api. In order to make everything clear, Java provides us everything in the package so that we can import only those packages that are required in the application.
3. Avoid naming conflicts
4. Control access
B. How to Import classes and packages :
When we are using the import statement as first statement then we are importing the required classes that are being used in current application.
Import All the Classes of Package :
import java.util.*;
* In the above statement, we are importing all the classes of the package util.
* An import statement can import all the classes in a package by using an asterisk wildcard
Import Single Class of Package :
import java.util.ArrayList;
In the above statement we are just importing the ArrayList class of the util package. Due to this facility to import the specific class in the application, we can avoid necessary importing of classes in the application.
42
Q

Statements are

A

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.