Basic Java Concepts Flashcards
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.