Free Online Courses With Personalized Certificate


Free Online Courses With Personalized Certificate

I started writing this tutorial targeting MCA students in Himachal Pradesh University, Shimla, India (from where I did MCA back in 99). This is an attempt to help students learn Java by practice. I am posting this tutorial(work in progress) on my blog so as to make it available to all Java seekers.

Approach Java TOC

We are running little behind but that’s okay as long as we do not stop. Here’s the TOC I intend to cover in this series on Java:

1. Introduction to OOPs
2. Java Overview (P/F independence, versions, JRE, JDK)
3. Java data types
4. Java Classes, objects, constructors, methods
5. Introduction to Packages and scope identifiers (import statement as well)
6. Nuts and bolts of language (Conditional constructs, loops and more)
7. Data Structures (Collections)
7. Exception Handling
8. File Handling
9. JDBC
10. Closing and Forward

If you want to participate as an author send me an email.

Approach Java – 1. Introduction to OOPs

OOPs (object oriented programming system) can be confusing at times, especially when one begins to learn it. Let’s try to understand it here. We have read several times that procedural/structural programming is what we do in C or BASIC or Fortran language. In C if we have to develop a software for our MCA department to manage student records and employee records, we will create C program files. We will write a lot of functions in each file. As an example, we may create a file for functions related to storing records in database. And we may separate functions for student information in one file and for employees information in another file.

In a procedural language everything runs around functions. Functions are the algorithms, which together give us a running system.

OOPs is not based around functions. OOPs is based around objects. It is object oriented. It is a system for achieving the same goal of “developing softwares” in a different way. So what is an object? Anything that is a party to the system. OOPs tells us to forget about functions. Instead find everything that is a party/entity to the system. In above example of MCA department’s system, parties can be Student, Lecturer, University, Department, Class (MCA class), Subject or may be more. In the context of requirements, we have to ascertain what is a party to the system and what is not. Once we have found the parties or entities or OBJECTS, OOPs tells us to find 2 more things for each object:

1. Properties
2. Behavior

Again, one finds above 2 things in the context of requirements.
Properties are the basic elements or attributes of an object. Properties define the object. For example, for Student object properties may be Student Name, Date of Birth, MCA Batch, Permanent Address etc. For Lecturer object properties may be date-of-joining, years-of-experience, salary etc.

Once we find the properties, we have to decide behavior or objects. Behavior is what an object does, the way it reacts to certain events. For e.g. if one asks a student what MCA batch do you belong to, he will tell the batch. Here telling is the behavior. If one asks a lecturer to give his/her salary details, he/she may or may not tell (based on who is asking!!). This action of telling/not-telling is an example of behavior of Lecturer object. Behavior is necessary to being activity into the system, otherwise properties will remain with individual objects, will keep lying with them without any use. Behavior of an object opens a window to itself for interaction with outside world. In an object oriented programming language, behavior is known as methods/functions/messages. Together properties and behavior are known as members of the object.

[HPUMCA Group] Approach Java – 1.2. Introduction to OOPs

1. What is a class?
2. What are basic design principles of OOPs?

I asked above questions in previous chapter, but nobody responded. I will have to move on hoping interest will go up with time.

We have been talking about objects so far, but we know in any object oriented language we decide classes first. What is a class? In previous chapter I pointed out that we have to find all objects which are playing a role in system. Lecturer and Student are 2 among several objects we noted. In theory we talk about objects because we are used to them. Because we understand what is a lecturer object and what is a student object. We can even visualize/consider a particular Lecturer/Student when we discuss verbally.

When we move towards a software system, things start getting precise. Since any software system should work for a single object and also for all objects of similar nature, so we have to differentiate between a “single object” and “entire class of that object”. In our case, our system should be able to manage records of a particular student, but it must be developed generically so that it can manage records of students who will join MCA in future (and may be for those who already have completed their MCA – depends on requirement! !). This entire collection of students is known as “Student Class”. So “Class” word is a generic representation of entire category of objects of a particular type. Class is a blueprint, category, entity for which system is developed.

Now when we are defining “Class” we should also give a precise definition to Object. An “object” is a particular element belonging to its class. A specific student is an object. In OOPs, object is also known as “an instance”.

Basic Design Principles

Since OOPs concepts were derived from real world (the real one in which we live!!), so concepts found in real world are also found in OOPs. They are also required for OOPs to function at its best. Basic design/fundamental principles of OOPs are 4:

1. Encapsulation
2. Abstraction
3. Polymorphism
4. Inheritance

Note:  You might have seen that “design principles” term is also being used for advanced object-oriented design guidelines (OCP, DIP, LSP etc.). Also, more and more people are calling above 4 fundamental principles as “pillars of OOPs” – which I agree is a better fitting term. Some people call fundamental principles as “basic principles” omitting “design” word. In any case, we are not talking about OCP, DIP etc. here. We will define above 4 fundamental pillars of OOPs.

Encapsulation

Each object in real world can hide a lot of information within one. I may hide my salary details, food habits, favorite books, movies, even my name from others. I have encapsulated this information within me. This is important for one to live a peaceful and secure life, otherwise if everything is made open, information can be manipulated or misused. Similarly, for an object in OOPs to play its role in a controlled way, without being misused, it must encapsulate its properties within it. In an OOPs language, this is done by assigning a stricter access modifier to the properties (for e.g. make properties ‘private’). This is called encapsulation.

It is not that this information is entirely inaccessible. One has to come through a proper channel to get this information. For e.g. Income tax officials will have the authority to know my salary details. They are the proper channel (or are the super channel !!). Similarly, accessors and mutators (get and set methods respectively) are the proper channel to access and change personal information of an object.

Abstraction

Every object in real world has several views to the outside world. We are programmers for the company, family members for the family, customers for the bank, patients for the doctor and so on. A doctor is concerned about very few details of us to cure us. He wants an “abstract view” of us not the complete view.
Similarly, an object in OOPs has several views to other objects in the system. Lecturer object has one view to the Student object, and a different view to the “Administration” object. This concept is called abstraction.
Another way to define abstraction is that an object is interested in a particular information, not about implementation details. For e.g. doctor may be interested in knowing what I ate in breakfast, but not in how we cooked it (although he may be !!). In OOPs, an object may need to use information without need to know how it is calculated. A lecturer may be interested in favorite subject of a student without knowing how he decided that as favorite.

In OOPs abstraction is achieved through methods. Providing those methods to the outside world, which are of interest to them. Outside objects call methods on an object, get the result back. They do not need to know what is coded inside those methods.

I am taking a break here, we will continue. For you, the next 2 questions are:

1. What is an instance?
2. What is a member of an entity/class?

Approach Java – 1.3. Introduction to OOPs:

1. What is an instance?
2. What is a member of an entity/class?

I asked above questions in previous lesson, but nobody responded. I keep them open for you. Answer them when you get time. Let’s move forward in our “Approach Java” series. We went through 2 basic principles of OOPs (Encapsulation and Abstraction). Let’s cover the next 2 in this lesson (Polymorphism and Inheritance):

Inheritance

In real world, every one inherits many characteristics from one’s parents. Habits, health, height, wealth, skin color and much more. In addition to inherited ones, many specific characteristics are developed in individuals, which make each one unique. For e.g. some of one’s habits may have come from one’s parents but not all of them.
In OOPs, concept is similar. One object may inherit characteristics from its parent object, and then add few of its own characteristics to extend what it inherited. What is a “parent object” – the new term we introduced? Sometimes some objects look similar but still they are different. They belong to same category, but still they have some unique attributes. For e.g. Electric Bike and Petrol bike – both are bikes and their outer features may be common, but their mechanical system will be very different. Their components and operating system will be different. So here bike comes in ‘multiple forms’ and to the same question of ‘how does bike operate’ we get different answer from electric and petrol bike. To accommodate common features we create a parent class called ‘Bike’, put all common features in Bike object. Then we create 2 more classes ElectricBike and PetrolBike, which inherit common features from Bike class and add their specific features within their own class. In pseudo code, this may be represented as following:

class Bike
{
modelName;
manufacturer;
mfgDate;
price;
method howDoesBikeOperate()
{
//do not know, ask a specific bike
}
}
class ElectricBike inherits from Bike
{
//add its specific attributes
batteryPower;
batteryMfgDate;
batteryManufacturer;
method howDoesBikeOperate()
{
//operating mechanism description specific to electric bike
}
}
class PetrolBike inherits from Bike
{
//add its specific attributes
enginePower;
petrolTankCapacity;
method howDoesBikeOperate()
{
//operating mechanism description specific to petrol bike
}
}

Polymorphism

Anything in multiple forms is polymorphic. If I ask a student “what is your daily routine?”, I will get different answer from different students – same question, different answer. In above example of bike, we ask same question ‘how does bike operate’ and get different answer from electric and petrol bike. OOPs has this very important concept of polymorphism within it, which makes it extremely powerful methodology for software development. Same piece of code works for different objects and gives expected result.
Let’s go through some examples of multiple forms before we define types of polymorphism:

1+1 = 2
“hello” + ” world” = “hello world”
1.5+2.2 = 3.7

same + operator can handle different data types and give the expected result:

method getNetPrice()
{
return price;
}

method getNetPrice(discount)
{
return price-discount;
}

same method gives different answer depending on if we pass discount argument or not:

class ElectricBike inherits from Bike
{
//add its specific attributes
batteryPower;
batteryMfgDate;
batteryManufacturer;
method howDoesBikeOperate()
{
//operating mechanism description specific to electric bike
}
}
class PetrolBike inherits from Bike
{
//add its specific attributes
enginePower;
petrolTankCapacity;
method howDoesBikeOperate()
{
//operating mechanism description specific to petrol bike
}
}

Bike bike = createBikeObject(bikeType);
bike.howDoesBikeOperate();

same method howDoesBikeOperate() gives different answer depending on if bike is of type ElectricBike or PetrolBike.

Polymorphism is of 2 types:

1. Compile Time Polymorphism
2. Runtime Polymorphism

In above examples, last one (howDoesBikeOperate()) is an example of Runtime polymorphism. This means, it will be known at runtime what type of object createBikeObject(bikeType) will create and which method will be called. It is not known at compile time.

In other examples, everything is known at compile time. What type of arguments are being added, which method is being called (getNetPrice() or getNetPrice(discount)), this information is available at compile time – so this is called compile time polymorphism.

I am taking a break here. Questions for you:

1. What is Method Overloading?
2. What is Method Overriding?

Approach Java – 2. Java Overview

Let’s move forward in our Approach Java series. In this lesson we will go through overview of Java.
History of Java is a long and interesting story, which I will leave to individuals to google and read. As a brief note Java came into use in 1995 and was developed by a team called ‘green team’. James Gosling is credited as inventor of Java.

We all know the difference between a compiler and interpreter. Compiler translates a high level language program into another language (generally machine language). Execution of program is then done separately or by an extension of compiler software. Interpreter , on the other hand, translates and executes program statement by statement. Some high level languages are compiled (like C and C++), and some others are interpreted (like Basic). Java inventors formulated a combined approach – compiler + interpreter. Java compiler translates Java program into an intermediate language (known as byte code) and Java interpreter executes byte-code statement by statement. Advantage of this dual approach is platform independence.

Platform Independence

If a program is compiled into an exe file on a windows machine, and you want to execute it on a Linux machine, it is not possible (exe is machine specific). Program needs to be copied to Linux, compiled there and then can be executed. This is platform dependence.
Java program, on the other hand, can be compiled on windows – which gives us a byte-code file (not an exe file), this byte-code file can then be copied to Linux and executed there by Java interpreter. That means we can take this byte-code file on any OS and execute it with Java interpreter. This is platform independence.
It should be obvious that Java interpreter has to be OS dependent because it has to convert byte-code into OS dependent machine instructions.
P/F independence has helped software applications in tremendous way. First of all programs need not be distributed, only encrypted byte-code programs need to be. Secondly, byte-code programs can be downloaded from remote machines and executed locally (with local Java interpreter) without any compatibility issues (browser does it when it loads and executed applets). Thirdly, one needs to install only Java interpreter to execute byte-code programs (which is smaller package) instead of the whole Java (JDK).

JVM, JRE and JDK

An exe file is a collection of machine instructions for a specific H/W machine. Similarly a byte-code program is a set of intermediate language instructions for a virtual machine called JVM (Java virtual machine). Java Interpreter is a program in JVM (or some people call Java interpreter as the JVM itself), that executes byte-code program.

JRE (Java runtime environment) is the java interpreter package that is required to execute byte-code programs. It includes java interpreter (java.exe) and rt.jar (java runtime apis) in addition to few other programs.

JDK/Java-SDK (java development kit/Java Software development kit) is the whole java development package required to write programs in Java language. It includes Java compiler, development time java apis and JRE as well. Java comes in 3 flavors – micro edition (for micro devices – mobiles, PDAs etc.), standard edition (core java for desktops) and enterprise edition (for enterprise application development – like servlets, JSPs etc.).

For learning Java, you will need to install Java standard edition on your machine. Go to sun.com to download appropriate JDK for your OS. We are at JDK 1.6 version now.

I am taking a break here. Rajeev, if you are reading this email, contact me. Have you made any progress on Java Data Types?

I will be back soon with next lesson.

[Him. Uni. Friends] Approach Java – 3.1. Java programming basics

At this moment I feel like correcting few titles in TOC, here’s the changed TOC:

1. Introduction to OOPs
2. Java Overview (P/F independence, versions, JRE, JDK)
3. Java programming basics (class structure, compiling & executing programs, member variables, methods, constructors, creating objects, data types)
4. Introduction to Packages and scope identifiers (import statement as well)
5. Adding power to language (Conditional constructs, loops and more)
6. Data Structures (Collections)
7. Exception Handling
8. File Handling
9. JDBC
10. Closing and Forward

3.1 Java programming basics

Java is an object oriented language. Every program in java is a class. Let’s take a look at structure of a java class.

class FirstClass
{
}

Above is a valid java class, although it has no member variables or methods. So a blank class is a valid class in java. You can save above class under any name but with .java extension. Suppose I save it as a.java.
Now I want to compile it – command is (assuming I am in the same folder in which I saved file):

javac a.java

Output of above command is FirstClass.class – bytecode file for a.java. You can see that output has no relation to name a.java. Output is generated corresponding to class defined inside a.java.

Now I want to run it, command is:

java FirstClass

Note that we do not specify .class extension when we run the program. Why so? I leave that to you to find – here’s question number 1 from this lesson:

Q1 – why do we NOT specify .class extension when we run a java program?

Output of above command is:

Exception in thread “main” java.lang.NoSuchMethodError: main

This is because when a java program execution starts, it attempts to find main method in the class – which acts as the starting point of execution (similar to C if I remember correctly).

For above class to do something, let’s add main method to it:

class FirstClass
{
static void main(String[] ss)
{
System.out.println(“First Class”);
}
}

Obviously main method has to be static because when execution starts there is no object in memory, hence only a static method can be called by JVM (java command). Also, since we may need to pass some arguments from outside when we execute a java program, so main method has an argument of “String Array” type. This means every argument value you pass to a java program, irrespective of what datatype it belongs to, is treated as a string value. Finally, we have used System.out.println statement inside main() method. This statement is used to print text output on default output device (in this case console). Here is question number 2 for you from this lesson:

Q2 – What is System, out and println in System.out.println?

Since we made a change to the program so old bytecode will not work for us. We need to recompile:

javac a.java

Now run it

java FirstClass

Here’s the output:

Main method not public.

Still no output. Since we are invoking main method from outside (java is an outside program invoking main of FirstClass), so main method must be public. Hence we change code as below :

class FirstClass
{
public static void main(String[] ss)
{
System.out.println(“First Class”);
}
}

compile and run :

javac a.java

java FirstClass

Output:

First Class

Finally we got the output we expected.

I hope this gives you an idea of writing a simple java class, compiling and executing it.

Before we close for today, here’s one more thing to know. We can put multiple classes in a single file in java. So I extend the above code like below:

a.java contents :

class FirstClass
{
public static void main(String[] ss)
{
System.out.println(“First Class”);
}
}

class SecondClass
{
public static void main(String[] ss)
{
System.out.println(“Second Class”);
}
}

class ThirdClass
{
public static void main(String[] ss)
{
System.out.println(“Third Class”);
}
}

compile and run:

javac a.java

output:

FirstClass.class
SecondClass.class
ThirdClass.class

java FirstClass
output :
First Class

java SecondClass
output :
Second Class

java ThirdClass
output :
Third Class

We will continue in next lesson about java class structure, member variables, methods, jvm arguments, comments etc. Keep reading.

Approach Java – 3.2. Java programming basics

We talked about writing a simple java class, compiling and executing it in last lesson. And then we saw we can pack a lot of classes in a single file in java. In this & next lesson we will learn on following topics:

* Instance Variables
* Instance Methods
* Static Variables
* Static Methods
* Constructors
* Creating objects
* command line arguments
* comments

Note: Instance and Object words are used interchangeably here, they are synonyms in context of our discussion.Instance VariablesSuppose we have to develop a Java program for Students, to manage their name, age, batch and subjects. We will create a class Student and will add required properties to it as below:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;
}

In above class – name, ageInYears, batch, subjects are instance variables of class Student. If there are 50 students for which we have to maintain data, then values of instance variables for each student object can be different and will belong to only that particular instance(student) (hence they are called instance variables). You can also see that each instance variable has a data type (String, int) attached to it, which tells what typs of data that variable can hold. We will go through data types in a later lesson.Instance MethodsIn above class, if we want to print the name of student, where will we write that code? In java any peice of code is written inside methods (except static initializers, which we will cover later). So method is a block of java statements to do some processing. Here’s updated Student class with a method printName added to it:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

void printName()
{
System.out.println(“Name is :”+name);
}
}

printName() is an instance method because it processes/prints an instance variable. It behaves uniqely to each instance (in this case it prints name of a particular student – it does not mix names of several student objects, it does not get confused by that. Later on we will see how to call an instance method

A method, in some cases, can return a result of processing done within it. For e.g. if we want to get the number of subjects a student has taken, method will return the count. But in printName() there’s nothing to return. Just printing the name is required. That’s why you see ‘void’ before method name, which indicates this method does not return anything. On the other hand since ‘number of subjects’ will be a numeric value, therefore such a method will have ‘int’ as return type:

int getNumberOfSubjects()
{
return subjects.length;
}

printName() method also has empty curve brackets. Within these parenthesis we can receive data from outside. In this case since data belongs to the object itself (instance variable – name), hence we do not need to receive it from outside. Inside the class, all instance variables are accessible to instance methods. But suppose we want to print the name n times, then we should pass value of n – which is not available in Student class. Hence we change the method signature as below:

void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println(“Name is :”+name);
}
}

Static Variables

Some of the variables may not be a property of each individual object (they do not hold instance specific value). For e.g. numberOfStudents will not vary for each individual student. That is an external variable, a counter, not a property of student. Hence we can not make it an instance variable. Instead, we associate it to the whole class, which means we keep only one copy of it irrespective of how many student objects are there. Such variables are called static variables. In java we prepend static keyword to define a static variable as below:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println(“Name is :”+name);
}
}
}

Static Methods

An instance method behaves uniquely for each instance – in the sense that it operates on data of that instance only. But since there is only one copy of static variable available in memory for all student instances and has single value, there’s no need for methods processing static variables to behave uniquely for each object. For e.g. if I want to get the numberOfStudents then I do not need to get that from a specific student instance. Value of numberOfStudents is same whichever student I ask from, so I can get that from any student instance or even without student instance (can count myself for e.g!!). Such methods, which behave statically for each instance and which operate on static variables, are called static methods. Similar to static variables, we prepend static keyword before method name:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println(“Name is :”+name);
}
}

static int getNumberOfStudents()
{
return numberOfStudents;
}
}

Let’s now save above class under name b.java, compile and run it. Later on we will see that we should (actually will have to) save each class under <classname>.java i.e. we should save above class in file Student.java instead of b.java. For now, let’s continue with b.java name and when we get to that moment we will understand better why we have to save it under Student.java name.

Compile the program:

javac b.java

output:
Student.class

Now run it :

java Student
Exception in thread “main” java.lang.NoSuchMethodError: main

That error should not be surprising to you, as we went through that in last lesson. We need main() method, which is the starting point for execution. We add the main method:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println(“Name is :”+name);
}
}

static int getNumberOfStudents()
{
return numberOfStudents;
}

public static void main(String[] args)
{
}
}

Now compile & run again :

javac b.java
java Student

Output: No error, no message, nothing.

In output we do not get anything, because we have no statement in main() method.
You can see that although we have 2 methods and several instance variables in class, they are doing nothing. This is because no method gets executed until we call it (including main() which is called by jvm!!).

In this case, we will have to call printName method if we want to execute it. Another thing we have to think about is student data. So far we have written a class, but where is student data? Where are instances we have been discussing about?

We will answer these questions in next lesson. Until then, go through above and send me any questions that come to your mind.

regards
Varun

Approach Java – 3.3. Java programming basics

We discussed instance and static variables and methods in last lesson. Let’s now talk about creating real objects and calling methods on them. We will cover following here :

* Constructors
* Creating objects
* command line arguments
* commentsIn last lesson, we ended up with following class :

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}static int getNumberOfStudents ()
{
return numberOfStudents;
}public static void main(String[ ] args)
{
}
}

And we found that executing above class does not give us anything as output (neither any error occurs). Let’s consider few students for whom we want to use above class and its methods. Student sample data is following:Student Name/ageInYears/batch/subjects – S1/20/2008/FOCA,Data Structure,Accounting
Student Name/ageInYears/batch/subjects – S2/19/2008/FOCA,Data Structure,COBOL
Student Name/ageInYears/batch/subjects – S3/21/2008/FOCA,Data Structure,COBOL,OraCLEHow do we translate above student records in java? We need to create objects/instances for them. Each student will map to one java object. In java we create a new object with ‘new’ operator, like this:

<ClassName> objectName = new <ClassName>();

i.e.

Student s1 = new Student();

Student() is called constructor, which ‘constructs’ an empty object in memory. This looks like a method and is invoked like a method. But since we do not define it in our class, instead is provided by Java itself, so this is called a ‘default’ constructor. Now where do we create objects, in which method? Since execution starts with main() method so we should create these objects there. See below :

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}

static int getNumberOfStudents ()
{
return numberOfStudents;
}

public static void main(String[ ] args)
{
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
}
}

We created 3 student objects since we have data for 3 students. Now you can see that we still are not using their data in main() method, these objects are blank. To fill data in these objects we have 2 approaches :

1. Use setter methods
2. Use constructor

Let’s discuss these 2 approaches here.

1. Setter methods

In first approach, to fill data in objects, we need to have setXXXX() methods defined in class for each instance variable we want to set data in. See below, set methods for name, age, batch and subjects:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}

static int getNumberOfStudents ()
{
return numberOfStudents;
}

public void setName(String name)
{
this.name = name;
}

public void setAge(int age)
{
ageInYears = age;
}

public void setBatch(String batch)
{
this.batch = batch;
}

public void setSubjects(String[] subjects)
{
this.subjects = subjects;
}

public static void main(String[ ] args)
{
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
}
}

Each set method takes an argument of same type as the instance variable it has to set and returns void. You can see ‘this’ keyword used in set methods. Since name of variable passed to setName method is ‘name’ and instance variable name is also ‘name’, therefore if we say name=name; how does java know which name variable is to the left and which one to the right? ‘this.name’ is to help it differentiate between the two, this.name is ‘instance variable’ and that without ‘this’ is the argument passed to method. We will go through ‘this’ keyword later also.

In setAge() method, since argument name is different from instance variable name, therefore we do not need to prepend ‘this’ keyword to differentiate.

These set methods are called setters generally and get methods are called getters. Now we have all the setters, let’s fill data in objects using these methods. Check this code:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}

static int getNumberOfStudents ()
{
return numberOfStudents;
}

public void setName(String name)
{
this.name = name;
}

public void setAgeInYears(int age)
{
ageInYears = age;
}

public void setBatch(String batch)
{
this.batch = batch;
}

public void setSubjects(String[] subjects)
{
this.subjects = subjects;
}

//Student Name/ageInYears/batch/subjects – S1/20/2008/FOCA,Data Structure,Accounting
//Student Name/ageInYears/batch/subjects – S2/19/2008/FOCA,Data Structure,COBOL
//Student Name/ageInYears/batch/subjects – S3/21/2008/FOCA,Data Structure,COBOL,OraCLE
public static void main(String[ ] args)
{
Student s1 = new Student();
s1.setName(“S1″);
s1.setAgeInYears(20);
s1.setBatch(“2008″);

Student s2 = new Student();
s2.setName(“S2″);
s2.setAgeInYears(19);
s2.setBatch(“2008″);

Student s3 = new Student();
s3.setName(“S3″);
s3.setAgeInYears(21);
s3.setBatch(“2008″);

System.out.println(“Student 1 >> Name:”+s1.getName());
System.out.println(“Student 1 >> Age:”+s1.getAgeInYears());
System.out.println(“Student 1 >> Batch:”+s1.getBatch());
}
}

You can see we are calling setXXXX() methods using object name (s1/s2/s3) to fill data in that particular object. If you have any doubt in above code send me your questions and we will go in more detail. Let’s now save above code in b.java, compile and run the code:

javac b.java
b.java:64: cannot find symbol
symbol : method getName()
location: class Student
System.out.println(“Student 1 >> Name:”+s1.getName());
^
b.java:65: cannot find symbol
symbol : method getAgeInYears()
location: class Student
System.out.println(“Student 1 >> Age:”+s1.getAgeInYears());
^
b.java:66: cannot find symbol
symbol : method getBatch()
location: class Student
System.out.println(“Student 1 >> Batch:”+s1.getBatch());

^
3 errors

Errors are genuine because we are missing get methods that we are calling in System.out.println statement. Let’s add them:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;
void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}

static int getNumberOfStudents ()
{
return numberOfStudents;
}

public void setName(String name)
{
this.name = name;
}

public void setAgeInYears(int age)
{
ageInYears = age;
}

public void setBatch(String batch)
{
this.batch = batch;
}

public void setSubjects(String[] subjects)
{
this.subjects = subjects;
}

public String getName()
{
return name;
}

public int getAgeInYears()
{
return ageInYears;
}

public String getBatch()
{
return batch;
}

public String[] getSubjects()
{
return subjects;
}

//Student Name/ageInYears/batch/subjects – S1/20/2008/FOCA,Data Structure,Accounting
//Student Name/ageInYears/batch/subjects – S2/19/2008/FOCA,Data Structure,COBOL
//Student Name/ageInYears/batch/subjects – S3/21/2008/FOCA,Data Structure,COBOL,OraCLE
public static void main(String[ ] args)
{
Student s1 = new Student();
s1.setName(“S1″);
s1.setAgeInYears(20);
s1.setBatch(“2008″);

Student s2 = new Student();
s2.setName(“S2″);
s2.setAgeInYears(19);
s2.setBatch(“2008″);

Student s3 = new Student();
s3.setName(“S3″);
s3.setAgeInYears(21);
s3.setBatch(“2008″);

System.out.println(“Student 1 >> Name:”+s1.getName());
System.out.println(“Student 1 >> Age:”+s1.getAgeInYears());
System.out.println(“Student 1 >> Batch:”+s1.getBatch());
}
}

You can see, each getter has return type of the instance variable it returns. Let’s compile and run now:

javac b.java
no error, output -> Student.class

java Student
Student 1 >> Name:S1
Student 1 >> Age:20
Student 1 >> Batch:2008

So you can see we get the data of student 1 printed on console. This is great, isn’t it!!
If we want to print data of other 2 students as well, we will have to add more System.out.println statement to the main method. Can you do that yourself? It will be a good test for you.

That was approach 1 of filling data in objects. Let’s go through the second approach.

2. Constructor Approach

We saw the default constructor className() above, but that creates a blank object. Fortunately, we can create our own constructor which will create a ‘pre-filled’ object for us, so that we won’t have to call setter methods. Let’s define our own constructor:

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;

Student(String name, int age, String batch)
{
this.name = name;
this.ageInYears = age;
this.batch = batch;
}

void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}

static int getNumberOfStudents ()
{
return numberOfStudents;
}

public String getName()
{
return name;
}

public int getAgeInYears()
{
return ageInYears;
}

public String getBatch()
{
return batch;
}

public String[] getSubjects()
{
return subjects;
}

//Student Name/ageInYears/batch/subjects – S1/20/2008/FOCA,Data Structure,Accounting
//Student Name/ageInYears/batch/subjects – S2/19/2008/FOCA,Data Structure,COBOL
//Student Name/ageInYears/batch/subjects – S3/21/2008/FOCA,Data Structure,COBOL,OraCLE
public static void main(String[ ] args)
{
Student s1 = new Student(“S1″,20,”2008″);
Student s2 = new Student(“S2″,19,”2008″);
Student s3 = new Student(“S3″,21,”2008″);

System.out.println(“Student 1 >> Name:”+s1.getName());
System.out.println(“Student 1 >> Age:”+s1.getAgeInYears());
System.out.println(“Student 1 >> Batch:”+s1.getBatch());
}
}

You can see a much smaller class now with all those getters gone, also main() method is smaller now. We defined a new method ‘void Student(String name, int age, String batch)’, method name for which is <className> and does not return anything. Each constructor’s method name is <className> and it returns nothing*. Can a constructor return a value in java? a question for you to research.
Here, our constructor takes 3 arguments – name, age and batch and fills them in at the same moment when ‘new’ operator is called to create the object (check main method, which supplies data when it calls new).

You can define many constructors in your class, as many as you need, provided they have at least one of following:

1. Different number of arguments
2. Different types of arguments

Let’s now compile and run above code :

javac b.java

java Student
Student 1 >> Name:S1
Student 1 >> Age:20
Student 1 >> Batch:2008

Great, it works!!
One special thing you will have to remember about your own constructors is that once you define them you can no longer call the default constructor. Can you tell why?

We have a lot to cover yet, but we’ll keep moving and extending our TOC as required. In next lesson let’s try to cover following:

1. We have not used ‘subjects’ instance variable anywhere in above classes, we will give a look to it
2. comments are not discussed yet (although we have used comments above in our code, do you see where??)
3. command line arguments

Question for you after this lesson:

1. Why do we not append .class extension when we execute a java class?
2. What are System, out and println in System.out.println statement?
3. Can constructors return a value in Java?
3. If you define your own constructor you can no longer invoke default constructor. Why so?

keep reading, enjoy java series…
Varun

Approach Java – 3.4. Java programming basics

In this lesson we will go through below mentioned points :

1. We have not used ‘subjects’ instance variable anywhere in above classes

2. comments are not discussed yet (although we have used comments above in our code, do you see where??)

3. command line arguments1. We have not used ‘subjects’ instance variable anywhere in above classesWe have defined subjects as a variable of type String[]. This means array of strings. Since subjects is an array, we can put several elements in this variable, provided we declare in advance how many maximum elements we will be putting. This is the precondition with arrays, right? In java we will need to define the max-limit when we use the array, that is when we will actually be using it to put something in it. So far we have not used it, so we do not need to specify that limit (although we can). We will cover arrays in details later, for now just see below how I specify that I want to put maximum 7 subjects in this array, and I actually put few subjects for student 1 and then print them.

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;static int numberOfStudents;Student(String name, int age, String batch)
{
this.name = name;
this.ageInYears = age;
this.batch = batch;
}void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}static int getNumberOfStudents ()
{
return numberOfStudents;
}

public String getName()
{
return name;
}

public int getAgeInYears()
{
return ageInYears;
}

public String getBatch()
{
return batch;
}

public String[] getSubjects()
{
return subjects;
}

//Student Name/ageInYears/batch/subjects – S1/20/2008/FOCA,Data Structure,Accounting
//Student Name/ageInYears/batch/subjects – S2/19/2008/FOCA,Data Structure,COBOL
//Student Name/ageInYears/batch/subjects – S3/21/2008/FOCA,Data Structure,COBOL,OraCLE
public static void main(String[ ] args)
{
Student s1 = new Student(“S1″,20,”2008″);
Student s2 = new Student(“S2″,19,”2008″);
Student s3 = new Student(“S3″,21,”2008″);

System.out.println(“Student 1 >> Name:”+s1.getName());
System.out.println(“Student 1 >> Age:”+s1.getAgeInYears());
System.out.println(“Student 1 >> Batch:”+s1.getBatch());

/*
add subjects for student 1
english, math, computers
*/
s1.subjects = new String[7];
s1.subjects[0] = “english”;
s1.subjects[1] = “math”;
s1.subjects[2] = “computers”;

System.out.println(“Student 1′s subjects:”);
System.out.println(s1.subjects[0]);
System.out.println(s1.subjects[1]);
System.out.println(s1.subjects[2]);

}
}

compile and run :

javac b.java
java Student

Student 1 >> Name:S1
Student 1 >> Age:20
Student 1 >> Batch:2008
Student 1′s subjects:
english
math
computers

2. comments are not discussed yet (although we have used comments above in our code, do you see where??)

In java, you can use single line comments or multi line comments. Comments are good to explain lines of code when they are not obvious to understand. We used both types of comments above. Single line comments start with //, they do not end with anything because they are single line. Everything after // is treated as a comment. Below are few examples of using single line comments:

int a = 0;//comment starts from here: a is a variable of int type

//comment starts from here: your java statement becomes a comment now because you added // at the beginning: int a = 0;

//comment start from here: a is a variable of int type
int a = 0;

Multi line comments start with /* and end with */. We need an end mark here because comment spans to multiple lines and compiler need to know where the comment ends. One important point is you can not nest multi line comments within each other, so following is invalid:

/*Here starts a comment

/*Here starts a nested comment – but it won’t work 🙁 NO multiple line comment nesting
*/

*/

Following is fine though :

/*Here starts a comment

//Here starts a single line nested comment – it is allowed

*/

3. command line arguments

Sometimes we do not want to hardcode things in program. We want to pass different set of values to a program everytime we run it. In this case we can use command line arguments, which means we pass values to main() method from command line when we invoke java command on it. Something like this:

java Student val1 val2

Here we are passing val1 and val2 to Student class at runtime. If you remember signature of main method, it looks like below:

public static void main(String[] args)

all the command line arguments get packed into ‘args’ variable in main() method, that means even if you pass a float or an int value, it is converted into text (String).

Let’s do something realistic. Let’s pass student data from command line instead of hard coding it in program. Look at changed code below :

class Student
{
String name;
int ageInYears;
String batch;
String[] subjects;

static int numberOfStudents;

Student(String name, int age, String batch)
{
this.name = name;
this.ageInYears = age;
this.batch = batch;
}

void printName(int numberOfTimes)
{
for (int counter=0; counter<numberOfTimes; counter++)
{
System.out.println( “Name is :”+name);
}
}

static int getNumberOfStudents ()
{
return numberOfStudents;
}

public String getName()
{
return name;
}

public int getAgeInYears()
{
return ageInYears;
}

public String getBatch()
{
return batch;
}

public String[] getSubjects()
{
return subjects;
}

//getting data from command line
public static void main(String[ ] args)
{
Student s1 = new Student(args[0],Integer.parseInt(args[1]),args[2]);

System.out.println(“Student 1 >> Name:”+s1.getName());
System.out.println(“Student 1 >> Age:”+s1.getAgeInYears());
System.out.println(“Student 1 >> Batch:”+s1.getBatch());

/*
add subjects for student 1
english, math, computers
*/
s1.subjects = new String[7];
s1.subjects[0] = “english”;
s1.subjects[1] = “math”;
s1.subjects[2] = “computers”;

System.out.println(“Student 1′s subjects:”);
System.out.println(s1.subjects[0]);
System.out.println(s1.subjects[1]);
System.out.println(s1.subjects[2]);

}
}

As you can see, we removed s2 and s3 statements. We will get data of only one student at a time from command line for now, so we kept only s1. In addition we replaced hardcoded name, age and batch from the constructor call with args[0], args[1] and args[2]. This is because first command line argument will be available in argsp[0], second at position 1 and so on. We have to make sure we pass values in same sequence as we are assuming here in constructor call (name, age and then batch). One more thing you will notice, we have called Integer.parseInt method on args[1] before we passed it to constructor. As I told you earlier, every command line argument is converted to String, but constructor needs age as int. So we need to convert String age to int age and that’s precisely what Integer.parseInt method does (don’t worry if it does not make much sense at this moment, we will get back to it later).

let’s now compile and run it :

javac b.java
java Student
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0
at Student.main(b.java:54)

Since we did not pass any argument so it complains that array has no element and code is trying to get element at position 0. If you remember from lesson 1, java is an interpreted language when it comes to executing code, so it stopped at the very first error it faced.

run it again with command line arguments (no need to compile again because we did not change anything) :

java Student ajay 20 2008
Student 1 >> Name:ajay
Student 1 >> Age:20
Student 1 >> Batch:2008
Student 1′s subjects:
english
math
computers

It works!! doesn’t it?

Let’s take a look at TOC once again now. Only thing we are left with in lesson 3 are “data types”. We will cover it in next lesson and then we move to lesson 4. Hope you enjoy java lessons and they help you to learn java.

1. Introduction to OOPs
2. Java Overview (P/F independence, versions, JRE, JDK)
3. Java programming basics (class structure, compiling & executing programs, member variables, methods, constructors, creating objects, data types)
4. Introduction to Packages and scope identifiers (import statement as well)
5. Adding power to language (Conditional constructs, loops and more)
6. Data Structures (Collections)
7. Exception Handling
8. File Handling
9. JDBC
10. Closing and Forward

Approach Java – 3.5. Java programming basics – Java Data Types

Java Data TypesHere we are, at the last topic of chapter 3. It took a little longer for us to go through this chapter – don’t you feel so, I do at least. Let’s cover it.Java is strongly typed language, that means before we use a variable in our programs, we have to tell what type of data it can hold. So we have to assign a datatype to each variable and we stick to storing data of only that type in the variable, otherwise we get a compile time error. This is forced upon us by Java, hence strongly typed.Look at this:int a; a = “hello”;Java won’t allow that. Variable a is of type int, so we can store only numeric data in it. This will be a compile time error.In Java there 2 types of data-types:1. Primitive 2. ObjectPrimitive data types are fundamental types supported by Java itself. There are 8 primitive data types: byte short int long float double char boolean byte, short, int and long – all hold integer data. Main difference is the range of values they can hold (based on how many bytes are allocated in memory under each type). byte – 8 bits (-128 to 127) short- 2 bytes (-32768 to 32767) int – 4 bytes (-2147483648 to 2147483647) long – 8 bytes (-9223372036854775808 to 9223372036854775807) Most of the times, using ‘int’ should be fine for you. If we use a number directly in an expression (like a+230), how many bytes are allocated to that number? Well, Java will see how many bytes are required and will allocate based on that. BUT it will go only up to int. Any number out of range of int (requiring more than 4 bytes) will be a problem. Java does not allocate long datatype to it by default. For long values, we need to explicitly append L (small or capital – doesn’t matter) after the value (like 4444444444444L). Let’s do some testing now, take a look at class below (that I saved under filename DT.java – we will come to the point soon when we will have to store all classes under ‘<classname>.java’ filenames)

class DataType
{
static byte b = 450;
static short s = 4500;
static int i = 450000;
static long l = 450000000000;
}

compile
javac DT.java

DP.java:6: integer number too large: 450000000000
static long l = 450000000000;

^
1 error

As you can see, we did not put an L after the value so it did not let it pass. for long values we need to put L.
Change the code, run again:

class DataType
{
static byte b = 450;
static short s = 4500;
static int i = 450000;
static long l = 450000000000L;
}

javac DT.java

DP.java:3: possible loss of precision
found : int
required: byte
static byte b = 450;

^
1 error

We did not get that error now, but there’s another problem – we are trying to put 450 in a byte variable which can hold values only upto 127.
I wonder why it did not report both the problems together 🙁

Let’s fix that and compile again.

class DataType
{
static byte b = 125;
static short s = 4500;
static int i = 450000;
static long l = 450000000000L;
}

javac DT.java

SUCEESS – we get a class DataType.class as output. Let’s run it :

java DataType
Exception in thread “main” java.lang.NoSuchMethodError: main

Obviously, we did not put any main method. But since we only have few static variables, so we can also print them in “static block”. A static block is a special block that can work with static variables and can even call static methods.

See code below :

class DataType
{
static byte b = 125;
static short s = 4500;
static int i = 450000;
static long l = 450000000000L;

static
{
System.out.println(“byte = “+b);
System.out.println(“short = “+s);
System.out.println(“int = “+i);
System.out.println(“long = “+l);
}
}

compile and run again :

javac DT.java
java DataType
byte = 125
short = 4500
int = 450000
long = 450000000000
Exception in thread “main” java.lang.NoSuchMethodError: main

We still get that error but at least we see the output now – thanks to static block that can work with static data.

Before we go on to other datatypes, couple of more points:

* integer datatype variables can hold octal and hexadecimal data as well
* for octal data prepend value with 0, and for hex prepend 0x or 0X

Here’s an example :

class DataType
{
static byte b = 125;
static short s = 4500;
static int i = 450000;
static long l = 450000000000L;

static int j = 045;//octal value – equivalent to 37 in decimal
static int k = 0×45;//hexadecimal value – equivalent to 69 in decimal

static
{
System.out.println(“byte = “+b);
System.out.println(“short = “+s);
System.out.println(“int = “+i);
System.out.println(“long = “+l);

System.out.println(“j = “+j);
System.out.println(“k = “+k);
}

}

compile and run :

javac DT.java
java DataTypes

byte = 125
short = 4500
int = 450000
long = 450000000000
j = 37
k = 69
Exception in thread “main” java.lang.NoSuchMethodError: main

As you can see, it converts values of J and K to decimal before printing them.
So here’s next question for you.

Q – How can you print octal and hexadecimal values in their own base in Java? Instead of getting 37 and 69 above, how can we get original value in their own base (045, 0×45) as output?

I will have a take a break here.
We will continue.

regards
Varun

Approach Java – 3.6. Java programming basics – Data Types

Java Data TypesWe were going through primitive data-types in java and so far we are done with byte, short, int and long. Let’s go through following here:float
double
char
boolean
ObjectAs you might have guessed, for real numbers we use float and double data types. Similar to integer datatypes, float and double basically differ in the range of values they can manage.float – 4 bytes
double – 8 bytes float data type variables get four bytes of memory. The maximum value for a float is about 10 raised to the power 38. A float can have about 7 significant digits. A double takes up 8 bytes, can range up to about 10 to the power 308, and has about 15 significant digits. Every real number, by default, is stored as a double value (not as a float). So if you assign a real value to float variable compiler will complain. You need to put an F (small or capital) after the value to explicitly indicate to compiler that you want it stored as a float. Check the code below:

class DataType
{
static float f = 125.0;static
{
System.out.println(“float = “+f);
}}

save above as DT.java, compile

javac DT.java
DT.java:3: possible loss of precision
found : double
required: float
static float f = 125.0;
^
1 error

It won’t let us store even a small value such as 125.0 into a float variable. Change the code, run again :

class DataType
{
static float f = 125.0f;//put f after the value

static
{
System.out.println(“float = “+f);
}

}

compile and run:

javac DT.java
java DataType
float = 125.0
Exception in thread “main” java.lang.NoSuchMethodError : main

We are through this time!!
Let’s try few more examples :

class DataType
{
static float f = 125.0F;
static float f1 = 125.232379232345F;
static double d1 = 125.232379232345;

static
{
System.out.println(“float f = “+f);
System.out.println(“float f1 = “+f1);
System.out.println(“double d = “+d1);
}

}

compile and run :

javac DT.java
java DataType
float f = 125.0
float f1 = 125.232376
double d = 125.232379232345
Exception in thread “main” java.lang.NoSuchMethodError: main

You can see we get more precision with double than with float when there are a lot of digits after decimal place.

Here’s another question for you :

Q – What does strictfp mean in Java?

Additionally, numbers can also be represented in exponential form – 12E3 means 12 times 10^3, 12E-3 means 12 times 10^-3. See more examples below :

class DataType
{
static float f = 125.0F;
static float f1 = 125.232379232345F;
static double d1 = 125.232379232345;

static double d2 = 11.1234e-111;
static double d3 = 11.1234e307;

static
{
System.out.println(“float f = “+f);
System.out.println(“float f1 = “+f1);
System.out.println(“double d1 = “+d1);
System.out.println(“double d2 = “+d2);
System.out.println(“double d3 = “+d3);
}

}

compile and run :

javac DT.java
java DataType

float f = 125.0
float f1 = 125.232376
double d1 = 125.232379232345
double d2 = 1.11234E-110
double d3 = 1.11234E308
Exception in thread “main” java.lang.NoSuchMethodError: main

Let’s go to ‘char’ now. char datatype is to store single character in a variable. It takes 2 bytes. With a single byte we can store up to 256 characters (2^8), but there are several other characters in foreign languages that need representation. So to hold them, 2 bytes are allocated for each char variable. Those 2-byte characters are called Unicode characters. In fact some of unicode characters may need space upto 4 bytes, hence jdk 1.5 has done that via using int datatype internally (google and study in detail if you want to). Unicode characters start with u [this time only small u] in Java. We can also store special characters like tab and carriage return in char variables.

Let’s go through some examples :

class DataType
{
static float f = 125.0F;
static float f1 = 125.232379232345F;
static double d1 = 125.232379232345;

static double d2 = 11.1234e-111;
static double d3 = 11.1234e307;

static char c1 = ‘c’;
static char tabcharacter = ‘t’;
static char unicodecharacter = ‘u00E9′;

static
{
System.out.println(“float f = “+f);
System.out.println(“float f1 = “+f1);
System.out.println(“double d1 = “+d1);
System.out.println(“double d2 = “+d2);
System.out.println(“double d3 = “+d3);

System.out.println(“simple char c1 = “+c1);
System.out.println(tabcharacter+” = tab char”);
System.out.println(“unicode character = “+unicodecharacter);
}

}

compile and run:

javac DT.java
java DataType

float f = 125.0
float f1 = 125.232376
double d1 = 125.232379232345
double d2 = 1.11234E-110
double d3 = 1.11234E308
simple char c1 = c
= tab char
unicode character = é
Exception in thread “main” java.lang.NoSuchMethodError: main

As you can see, ‘t’ of tab character is prefixed with a backslash () to tell the compiler that this is not letter ‘t’, and in output it is obvious that it pushed “= tab char” away by a tab – hence it works!! Also you must have noticed that ‘u00E9′ is character é (e with accute accent) – that’s what we get when we print it. That summarizes char datatype. Let me know if you have any question.

boolean

The last primitive datatype is boolean. boolean represents 2 constant values true & false. They are not 1 and 0 in Java. They are what they are – true and false. We will see in lessons ahead that expressions of type a>b return boolean results. Let’s go through a boolean example quickly :

class DataType
{
static float f = 125.0F;
static float f1 = 125.232379232345F;
static double d1 = 125.232379232345;

static double d2 = 11.1234e-111;
static double d3 = 11.1234e307;

static char c1 = ‘c’;
static char tabcharacter = ‘t’;
static char unicodecharacter = ‘u00E9′;

static boolean b1 = false;
static boolean b2 = 5>13;
static boolean b3 = 2<=3;

static
{
System.out.println(“float f = “+f);
System.out.println(“float f1 = “+f1);
System.out.println(“double d1 = “+d1);
System.out.println(“double d2 = “+d2);
System.out.println(“double d3 = “+d3);

System.out.println(“simple char c1 = “+c1);
System.out.println(tabcharacter+” = tab char”);
System.out.println(“unicode character = “+unicodecharacter);

System.out.println(“boolean b1 = “+b1);
System.out.println(“boolean b2 = “+b2);
System.out.println(“boolean b3 = “+b3);

}

}

compile and run :

javac DT.java
java DataType

float f = 125.0
float f1 = 125.232376
double d1 = 125.232379232345
double d2 = 1.11234E-110
double d3 = 1.11234E308
simple char c1 = c
= tab char
unicode character = é
boolean b1 = false
boolean b2 = false
boolean b3 = true
Exception in thread “main” java.lang.NoSuchMethodError: main

Result should be obvious. Let me know if you have any question.

We are done with primitive datatypes in Java.

Object Datatypes

The other type of datatypes in Java is “Object”. We learned in a prior lesson that to create an object of class C, we use following statement:

C myObj = new C();

This should look similar to:

float f = 1.2f;

If we just look at left side, C is equivalent to float and myObj is equivalent to f. Hence C should be a datatype equivalent to float. That’s what it is indeed!! In fact classes that we create or that are provided by Java itself are all datatypes, we can create objects of those datatypes. Since they are all classes (while float, int are not classes – they are primitives), hence they are clubbed together under heading “Object datatypes”.

In lessons to follow, we will go in more detail about objects and classes.

 

Approach Java – 4.1 Introduction to Access modifiers and Packages (import statement as well)

In real world a software system rarely contains a single program. Multiple programs work together to accomplish the required task. In Java, multiple classes need to be designed and coded to develop a system. Objects of these classes individually cannot do much, they need to communicate with each other via method calls. There are 2 problems that arise out of this need :1. Since objects need access to each other’s methods (and sometimes data), hence they need to be accessible to each other

2. Number of classes can quickly grow to large number and their names may also clash with each other, so classes need to be clubbed together in groups for easier handlingThese 2 problems are solved via “Access Modifiers” and “Packages” in Java. We will cover “Access Modifiers” and “Packages” in this and next few lessons.Access ModifiersConsider following classes:

class Person
{
String name;
int ageInYears;
Address myAddress;
}class Address
{
String city;
String state;
String country;
}

As you can see, Person class contains a member variable myAddress, which is object of another class Address. Hence Person class needs access to Address class to successfully store and retrieve person’s address. Providing access is one problem which has many solutions, and to decide the best solution is another problem. In summary, we need to preserve 2 OOP principles (encapsulation & abstraction) while providing access. Member variables of Address class should not be exposed directly to Person class otherwise there’s no encapsulation. Similarly, Person class may be interested in single address value (a String) instead of worrying about individual parts (variables) of address. Consider following pieces of code :

class Person
{
String name;
int ageInYears;
Address myAddress;

//wrong
void printAddress()
{
String concatenatedAddress = myAddress.city+” “+myAddress.state+” “+myAddress.country;
System.out.println(concatenatedAddress);
}

//right
void printAddress2()
{
System.out.println(myAddress);
}
}

In printAddress() method, Person class itself is creating concatenated address string, so it is not getting the abstract view of address it needs. This is wrong way of achieving the goal. In addition, what if pincode is added to Address class? That would not get printed until printAddress() method is modified. What if Address class changes variable name (country to ‘countryName’), that needs to be changed in printAddress() method as well. Now further, what if more instance variables are involved, suppose ageInYears is also a class:

class Person
{
String name;
Age age;
Address myAddress;

//wrong
void printAddress()
{
String concatenatedAddress = myAddress.city+” “+myAddress.state+” “+myAddress.country;
System.out.println(concatenatedAddress);
}

//right
void printAddress2()
{
System.out.println(myAddress);
}

//wrong
void printAge()
{
System.out.println(age.years + ” years, “+ age.month + ” months” );
}

//right
void printAge2()
{
System.out.println(age);
}
}

class Age
{
int years;
int months;
}

Now we have more direct dependencies, for every change in Age and Address classes, Person class may need to be modified. Hence it pays to follow object oriented principles of Encapsulation and Abstraction while providing access to other classes.

There are few more points to take care of while providing access to a class’s functionality:

* Access to a class may be required for only limited number of other classes, hence it is not wise to provide free access to a shared class – Free access here means any other class is able to access and change values of a class’s data.

* Access to only some of the instance variable may be desirable. Suppose we never want to provide direct access to pincode in Address example, we should be able to set selective access in such cases (to all other except pincode)

* No Access may be desirable, hence there must be a way to restrict other classes from accessing a class’s functionality

* Free access to all

Looking at above points explains the need of having various access levels to control what should be accessible and what should not.

We will see how this is done in Java in next lesson.

regards
Varun

Approach Java – 4.2 Introduction to Access modifiers and Packages (import statement as well)

In last lesson we concluded that one needs control at different levels in a program while sharing it. Java provides access sharing control at following levels:* Class Level – Controlling class sharing* Method Level – Controlling method sharing
* Variable Level – Controlling variable sharingSyntactically, following “Access Modifiers” are used to control access:* <default>
* private
* protected
* publicLet’s discuss above keywords with some examples.<default> – If we do not use any of the 3 keywords – public, private and protected, access is <default>. Note that we never use <default> word in programs, it is implicit. Whatever is ‘default’ is accessible ONLY within its own ‘package’ to any other class. ‘Package’ term may be confusing at this stage, it will become more clear when we go through packages in next lesson. For now, visualize ‘package’ as a folder.Consider following classes, assume they are saved in same folder (package)://save under filename person.java

class Person
{
String name;
Age age;
String myAddress;
}//save under filename age.java
class Age
{
int years;
int months;
}

Since we did not use private/public/protected with class, variables or methods, all of them have default access. Also we saved Person and Age classes in same folder, hence Person can use a reference to Age class. We save Person class in person.java and Age class in age.java. Try to compile person.java now:

javac person.java
person.java:5: cannot find symbol
symbol : class Age
location: class Person
Age age;
^
1 error

OOPs, didn’t work. Note that we have been saving classes under any file name so far. But if you read lesson “Approach Java – 3.5. Java programming basics – Data Types”, I mentioned there “we will come to the point soon when we will have to store all classes under ‘<classname>.java’ filenames“.
In this case rename age.java to Age.java and compile person.java again:

mv age.java Age.java
javac person.java

It works now. So what happened here?

When compiler attempts to compile person.java file, it finds a reference to Age class at line 5. Now it needs Age class in compiled form. Since it does not find Age.class in same folder, it attempts to find Age.java, assuming that Age class will be defined inside Age.java file. It does not find Age.java either (because we saved it in age.java). Hence it complains.

When we rename age.java to Age.java, compiler is able to find Age.java, it compiles it, which gives it Age.class, hence it can proceed to rest of the compilation of Person class. Note that by compiling person.java, compiler will compile all other classes as well to which person.java holds references. If you check the list of class files now,

ls -la *.class

-rw-r–r– 1 user users 217 2008-08-13 14:20 Age.class
-rw-r–r– 1 user users 264 2008-08-13 14:20 Person.class

You will see that Age.class is also present and timestamp is same as that of Person.

Now remove Person.class and Age.class, move Age.java to some other folder and compile person.java again :

rm Age.class Person.class
mv Age.java ..
javac person.java

person.java:5: cannot find symbol
symbol : class Age
location: class Person
Age age;

^
1 error

It cannot find that class again because it is not in same folder now. That’s how default access works.
Now move Age.java back into current folder.
mv ../Age.java .

private – Sometimes default access is too liberal. If we do not want to share an element with any other class, we make it private. Then it is accessible only within its own class. A class can not be private in Java.

Let’s see what compile says if we make a class private, just add private to Person class:

//save under filename person.java

private class Person
{
String name;
Age age;
String myAddress;
}

javac person.java
person.java:2: modifier private not allowed here
private class Person

^
1 error

It clearly says a class cannot be specified as private. This is a question for you:

Q – Why a class cannot be specified as ‘private’ in Java?

What about private methods and variables. Let’s try them. Check code below:

//save under filename person.java

class Person
{
String name;
Age age;
String myAddress;

public static void main(String[] args)
{
Person person = new Person();
person.name = “Bobby”;
person.age.years = 10;
person.age.printMonth();
}
}

//save under filename Age.java
class Age
{
private int years;
int months;
int day;

private void printMonths()
{
System.out.println(months);
}
}

We changed years to private in Age class and a private method printMonths() is also introduced. We try to access this private variable and method from person.java.

Now compile person.java

javac person.java
person.java:12: years has private access in Age
person.age.years = 10;
^
person.java:13: cannot find symbol
symbol : method printMonth()
location: class Age
person.age.printMonth();

^
2 errors

Message should be clear, let me know if any confusion is there.

protected – Sometimes we want to go beyond restrictions enforced by default access. We want to make a class X accessible to other classes in same package as well as to classes that inherit from X (we will go through inheritance in a later chapter). Then we use protected keyword.

Here’s an example (don’t worry if inheritance is not very clear at this moment):

//save under filename person.java

class Person
{
String name;
Age age;
String myAddress;

public static void main(String[] args)
{
Person person = new Person();
person.name = “Bobby”;
person.age.years = 10;
}
}

//save under filename Age.java
class Age
{
protected int years;
private int months;
private int day;
}

Note that Age class now marks years as protected and months as private. Since years is protected now and Person class is in same package as Age class, hence it can access years directly.

javac person.java

It works, no problems.

Let’s create another class now which inherits from Age class:

//save under filename SuperAge.java

class SuperAge extends Age
{
public static void main(String[] args)
{
SuperAge sage = new SuperAge();
System.out.println(sage.years);
System.out.println(sage.months);
}
}

“extends Age” here means SuperAge extends (inherits from) Age class. We will go in more detail about inheritance later.
SuperAge class attempts to access years and months here. Since years is a protected variable and protected can be accessed by classes that extend base class (Age is base class here), so that should be fine. But months is private hence not accessible outside. Let’s compile SuperAge.java now:

javac SuperAge.java

SuperAge.java:8: months has private access in Age
System.out.println(sage.months);
^
1 error

Expected error displayed, years goes through successfully.

public – Sometimes we want some resources to be available to all other classes, then we use public modifier. Mostly public is not used with instance variables to follow encapsulation principle (although it can be but it is a bad practice). But with classes, methods and static variables it is common.

//save under filename person.java

class Person
{
String name;
Age age;
String myAddress;

public static void main(String[] args)
{
Person person = new Person();
person.name = “Bobby”;
person.age.printMonths();
}
}

//save under filename Age.java
class Age
{
private int years;
int months;
int day;

public void printMonths()
{
System.out.println(months);
}
}

Now printMonths method is public. Therefore compiling person.java works without any problems:

javac person.java

works without problems!!

In this lesson we went through access modifiers, we also found that we need to name program files same as java classes because otherwise they may not be accessible to each other. In next lesson we will go through java packages.

Let me know if you have any question.

regards
Varun


Approach Java – 4.3 Introduction to Access modifiers and Packages (import statement as well)

 

Java PackagesIn this lesson we will go through Java Packages, classpath and import statement.
As we discussed in previous lessons, we need to organize classes in different folders in a large project. If we put all classes in same folder it makes it very difficult to understand their purpose later on and to maintain them. Java Package mechanism gives us a way to group classes together. In addition to ease of management, packaging also allows us to use same file name for different classes because we store them in different folders.Let’s go through an example. Consider following classes ://class for human memory

public class Memory
{
private String humanName;
private int phoneNumbersRemembered;
private int addressesRemembered;

public Memory(String name, int pn, int add)
{
this.humanName = name;
this.phoneNumbersRemembered = pn;
this.addressesRemembered = add;
}

public void printName()
{
System.out.println(humanName);
}
}

//class for computer memory
public class Memory
{
String ipAddress;
String hardDiskCapacity;
String RAMCapacity;

public Memory(String ip, String hdc, String rc)
{
this.ipAddress = ip;
this.hardDiskCapacity = hdc;
this.RAMCapacity = rc;
}

public void printIp()
{
System.out.println(ipAddress);
}
}

And we save above 2 classes under name Memory.java. We will have to put them in different folders because we cannot save both with same name in same folder. Hence we create 2 folders – human and computer (under folder javatutorial – I am assuming ‘javatutorial’ as parent folder name, you can use any folder name you wish)

javatutorial/human/Memory.java
javatutorial/computer/Memory.java

Now if I need to access these classes from within javatutorial folder how will I do that? Let’s create a class PrintComputerMemory in javatutorial folder.

//class to test computer memory

public class PrintComputerMemory
{
public static void main(String[] args)
{
Memory computerMemory = new Memory(“192.168.1.1″,”100GB”,”2GB”);
computerMemory.printIp();
}
}

javatutorial/PrintComputerMemory.java

Try to compile it :

javac PrintComputerMemory.java
PrintComputerMemory.java:7: cannot find symbol
symbol : class Memory
location: class PrintComputerMemory
Memory computerMemory = new Memory(“192.168.1.1″,”100GB”,”2GB”);
^
PrintComputerMemory.java:7: cannot find symbol
symbol : class Memory
location: class PrintComputerMemory
Memory computerMemory = new Memory(“192.168.1.1″,”100GB”,”2GB”);
^
2 errors

Errors are obvious. PrintComputerMemory class needs to know where Computer Memory class is. It needs to refer to that – and for that java provides import statement. Here’s simplified import statement syntax:

import x.<className>

where x is the package (folder) name. Let’s use import statement in PrintComputerMemory class and try again:

//import computer memory class first
import computer.Memory;

//class to test computer memory

public class PrintComputerMemory
{
public static void main(String[] args)
{
Memory computerMemory = new Memory(“192.168.1.1″,”100GB”,”2GB”);
computerMemory.printIp();
}
}

Now compile:

javac PrintComputerMemory.java
PrintComputerMemory.java:1: cannot access computer.Memory
bad class file: ./computer/Memory.java
file does not contain class computer.Memory
Please remove or make sure it appears in the correct subdirectory of the classpath.
import computer.Memory;
^
1 error

Still there is a problem. Although Memory.java exists in computer folder, but in addition we need to specify in Java that this class is under package computer. For that Java provides ‘package’ statement. Its simplified syntax is:

package x;

where x is the package (folder) name. Add this to Memory class in computer folder. It must be the first statement in Java class (comments are allowed before it though).

//package statement for Computer Memory class
package computer;

//class for computer memory
public class Memory
{
String ipAddress;
String hardDiskCapacity;
String RAMCapacity;

public Memory(String ip, String hdc, String rc)
{
this.ipAddress = ip;
this.hardDiskCapacity = hdc;
this.RAMCapacity = rc;
}

public void printIp()
{
System.out.println(ipAddress);
}
}

Now compile PrintComputerMemory class again (which will compile computer.Memory in turn):

javac PrintComputerMemory.java

No error this time. Let’s run it now :

java PrintComputerMemory
192.168.1.1

So that was a simple example of using package statement and import statement. Packages can be nested also. Instead of storing Memory class in computer folder, I can store it in computer/parts/ folder. In this case package statement will be:

package computer.parts;

Accordingly import statement will also change:

import computer.parts.Memory;

Rest of the code will remain the same.

Classpath

There is another very important concept – it is of classpath. “classpath” is an environment variable required to Java to locate classes during compilation and execution. Suppose I create a folder ‘testclasses’ within javatutorial and move PrintComputerMemory.java in it:

javatutorial>mkdir testclasses
javatutorial>mv PrintComputerMemory.java testclasses
javatutorial>cd testclasses

Now compile it :

/javatutorial/testclasses> javac PrintComputerMemory.java
PrintComputerMemory.java:2: package computer does not exist
import computer.Memory;
^
PrintComputerMemory.java:9: cannot find symbol
symbol : class Memory
location: class PrintComputerMemory
Memory computerMemory = new Memory(“192.168.1.1″,”100GB”,”2GB”);
^
PrintComputerMemory.java:9: cannot find symbol
symbol : class Memory
location: class PrintComputerMemory
Memory computerMemory = new Memory(“192.168.1.1″,”100GB”,”2GB”);
^
3 errors

Now it cannot locate computer.Memory class. Why was it able to locate it when this class was in javatutorial folder? This is because JVM checked within javatutorial folder the existence of computer folder and it found it, hence it did not complain. It checks the local folder first (earlier we needed to add ./ at the beginning of classpath to force compiler to look in current folder first, but with jdk 5 I did not need to do this on Linux – I will have to check if this is built inside JVM in jdk 5, if you can check it let the group know. Also if prior examples did not work for you, add ./ to classpath variable on your machine and try again, if it still does not work contact me). After we moved the class to ‘testclasses’ folder, it can no longer find computer package.
When should it check now? Should it check in all folder on system? That can be too slow. It needs infromation that where should it look for imported classes. This information is provided by ‘classpath’ environment variable. Classpath environment variable should contain path UPTO where the package starts from. In our case package starts from computer folder, so we should add path only up to javatutorial folder (that will tell compiler to look into javatutorial folder).

Set ‘classpath’ environment variable on command line like this (in Linux, google ‘setting environment variables in windows’ for setting it in windows):

export CLASSPATH=/home/Office/Desktop/javatutorial/
javatutorial/testclasses> javac PrintComputerMemory.java
javatutorial/testclasses> java PrintComputerMemory
192.168.1.1

That works. Classpath is a wide topic. Classpath can also contain jar files and zip files (a jar file is a collection of classes bundled together). You can read a lot more about it on http://mindprod.com/jgloss/classpath.html.

We will continue with next topic in next lesson.

Approach Java – 5.1 Adding power to language (Conditional constructs, loops and more)

 

It took me long time to start with this topic – sluggishness as ever. But let’s get together our act here and proceed ahead.
As we know, software programs several times need to follow a non-sequential path during execution. Therefore there must be ways in a programming language to express these non-sequential situations and decision making based on that. Additionally, programs need to re-iterate same steps several times. Hence we need some provision in language for looping. Java has several options to take care of these needs. In this lesson we will cover the following:

Special Topics – 
Boolean Expressions and Operators
Operator Precedence

Decision Making Statements:

* if-else statement, nested if
* switch statement
* Conditional Operator (only ternary operator in Java)

Loop Constructs:

* for loop
* while loop
* do-while loop

Additional Execution Control statements:

* break and labels
* continue

This is going to be a rather long lesson (of course in multiple parts), hence keep focussed.

Special Topic – Boolean Expressions and Operators

We looked at boolean datatype in Lesson 3. Let’s take that further here for more uses of it. There are 2 boolean values in Java – true and false.

boolean condition = true;//a simple boolean variable with true value

Boolean expressions are expressions that return a boolean result – true or false. Take a look below :

boolean condition = 10 > 5;
System.out.println(condition);

Here 10>5 is a boolean expression. Since 10 is always > 5 hence value of condition variable is true. More complex boolean expressions can be formed with the help of operators. There are 2 types of operators which can be used to generate boolean expressions:

1. Relational operators
2. Logical Operators

Relational Operators are mathematical comparison operators

==, <, >, <=, >=, !=

== is for equality comparison. != is for “not equal to”. Remaining should be obvious.

Examples:

condition = 10 == 10;//true
condition = 10 == 5;//false
condition = 10 > 10;//false
condition = 10 < 11;//true
condition = 10 >= 10;//true
condition = 10 <= 10;//true
condition = 10 != 10;//false

Logical Operators are applied only on boolean values, hence they help us in forming more complex compound boolean expressions.
Logical Operators are:

&&, ||, &, |, !, ^

Here && and & stand for AND, || and | stand for OR, ! stands for NOT and ^ stands for XOR (remember boolean algebra!!).

Let’s take a look at examples below:

boolean condition = true && true;//result is true
condition = true & false;//result is false
condition = (10 < 5) || (8 == 8);//result is true
condition = (10 < 5) | (8 == 8);//result is true
condition = (10 != 10) ^ (8 != 8);//result is false
condition = (10 != 10) ^ (8 == 8);//result is true
condition = (10 == 10) ^ (8 == 8);//result is false
condition = !(10 == 10);//result is false
condition = !(10 == 10) || !(8!=8);//result is true

Q1 for you – What is the difference between && and & in Java. Similarly, what is the difference between || and | and when should you use which operator?

Operator Precedence
Operator Precedence determines the order in which operators are applied when multiple of them are used together in an expression. I am giving details of relational and boolean operator only here (for others send me if you have any question)

Here’s the summary:

Logical Operator ! – highest precedence
Relational Operators <, >, <=, >= – same precedence – second after Logical Operator !
Relational Operators == and != – same precedence – after Relational Operators <, >, <=, >=
Logical Operator &&, &, |, ||, ^ – same precedence, evaluated last

Some examples follow :

boolean condition = 10 == 10 ^ false;//result is true
condition = 10 == 10 && 10 > 5;//result is true
//THIS IS AN ERROR CASE – WILL NOT COMPILE
condition = !10 == 10 && 10 > 5;//result is compilation error

condition = !(10 == 10) && 10 > 5;//result is false

Operators with same precedence are evaluated from left to right. You can use parenthesis to override default precendence.

Q2 for you today – Can you think of an expression which would prove that == has less precedence than <=?

Here’s the code for today’s examples, that you can compile and run :

package testclasses;
public class ControlFlow
{
public static void main(String[] args)
{
//BOOLEAN EXPRESSION EXAMPLES
booleanExpressionExamples();
}

private static void booleanExpressionExamples()
{
relationalOperatorExamples();
logicalOperatorExamples();
operatorPrecedenceExamples();
}

private static void relationalOperatorExamples()
{
System.err.println(“nnRelational Operator Examples”);
boolean condition = 10 > 5;
System.out.println(“10 > 5 >> “+condition);
condition = 10 == 10;//true
System.out.println(“10 == 10 >> “+condition);
condition = 10 == 5;//false
System.out.println(“10 == 5 >> “+condition);
condition = 10 > 10;//false
System.out.println(“10 > 10 >> “+condition);
condition = 10 < 11;//true
System.out.println(“10 < 11 >> “+condition);
condition = 10 >= 10;//true
System.out.println(“10 >= 10 >> “+condition);
condition = 10 <= 10;//true
System.out.println(“10 <= 10 >> “+condition);
condition = 10 != 10;//false
System.out.println(“10 != 10 >> “+condition);
System.err.println(“END Relational Operator Examplesnnnn”);
}

private static void logicalOperatorExamples()
{
System.err.println(“Logical Operator Examples”);
boolean condition = true && true;//result is true
System.out.println(“true && true >> “+condition);
condition = true & false;//result is false
System.out.println(“true & false >> “+condition);
condition = (10 < 5) || (8 == 8);//result is true
System.out.println(“(10 < 5) || (8 == 8) >> “+condition);
condition = (10 < 5) | (8 == 8);//result is true
System.out.println(“(10 < 5) | (8 == 8) >> “+condition);
condition = (10 != 10) ^ (8 != 8);//result is false
System.out.println(“(10 != 10) ^ (8 != 8) >> “+condition);
condition = (10 != 10) ^ (8 == 8);//result is true
System.out.println(“(10 != 10) ^ (8 == 8) >> “+condition);
condition = (10 == 10) ^ (8 == 8);//result is false
System.out.println(“(10 == 10) ^ (8 == 8) >> “+condition);
condition = !(10 == 10);//result is false
System.out.println(“!(10 == 10)>> “+condition);
condition = !(10 == 10) || !(8!=8);//result is true
System.out.println(“!(10 == 10) || !(8!=8)>> “+condition);
System.err.println(“END Logical Operator Examplesnnnn”);
}

private static void operatorPrecedenceExamples()
{
System.err.println(“Operator Precedence Examples”);
boolean condition = 10 == 10 ^ false;//result is true
System.out.println(“10 == 10 ^ false >> “+condition);
condition = 10 == 10 && 10 > 5;//result is true
System.out.println(“10 == 10 && 10 > 5 >> “+condition);
//THIS IS AN ERROR CASE – WILL NOT COMPILE – COMMENTED OUT
//condition = !10 == 10 && 10 > 5;//result is false
//System.out.println(“!10 == 10 && 10 > 5 >> “+condition);
condition = !(10 == 10) && 10 > 5;//result is false
System.out.println(“!(10 == 10) && 10 > 5 >> “+condition);
System.err.println(“END Operator Precedence Examplesnnnn”);
}
}

This is it for today. We will continue in next lesson.

[Him. Uni. Friends] Approach Java – 5.2 Adding power to language (Conditional constructs, loops and more) – If statement

5. Adding power to language (Conditional constructs, loops and more)Decision Making Statementsa) if-else statement (if else if and nested if)When execution control should follow a certain path only in case a particular requirement is met then if statement can be used.

Syntax of if statement is:

if (booleanExpression)
statement;if (booleanExpression)
{
statement1;
statement2;
}

Here booleanExpression is that check to see if requirement is being met or not. If it is met then statement; is executed otherwise not. Using second syntax, multiple statements can be executed if booleanExpression is true.examples:if (10 > 5)
System.out.println(“I always get executed”);

if (5 < 10)
System.out.println(“I never get executed”);

Note that we can also use boolean value directly instead of booleanExpression, see examples below:

if (true)
System.out.println(“I am always true”);

if (false)
System.out.println(“I am always false – hence never executed”);

boolean result = 10>5;
if (result)
System.out.println(“I always get executed”);

boolean result = 10<5;
if (result)
System.out.println(“I never get executed”);

Here’s how objects can be compared in java (incorrect way, then correct way is specified) :

String student1Name = “Ajay”;
String student2Name = “Ajay”;
String student3Name = new String(“Ajay”);
//WRONG WAY TO COMPARE – THIS IS COMPARING OBJECT REFERENCES – ALTHOUGH IT WORKS IN THIS CASE BECAUSE “AJAY IS A LITERAL”
if (student1Name == student2Name)
System.out.println(“student1 and student2 have same name”);

//WRONG WAY TO COMPARE – THIS IS COMPARING OBJECT REFERENCES
if (student1Name == student3Name)
System.out.println(“student1 and student3 have same name”);

//RIGHT WAY TO COMPARE – THIS IS COMPARING OBJECT VALUES
if (student1Name.equals(student2Name))
System.out.println(“student1 and student2 have same name”);

//RIGHT WAY TO COMPARE – THIS IS COMPARING OBJECT VALUES
if (student1Name.equals(student3Name))
System.out.println(“student1 and student3 have same name”);

equals method is used to compare 2 objects in Java. For String objects, equals compares value stored in variables. For more complex objects it depends on what is coded in equals method (equals is a method from Object class. Every class provides its own implementation of equals method – we will learn more about it in a later lesson).

So that was if statement. Let’s look at its else part now. If we need to take step1 if booleanExpression is true and step2 if booleanExpression is false, then we have to use else clause. See examples below :

String student1Name = “Ajay”;
String student2Name = “Vijay”;
if (student1Name.equals(student2Name))
System.out.println(“student1 and student2 have same name”);
else
System.out.println(“student1 and student2 have different names”);

Now take a look at this piece of code where we do not use else :

if (student1Name.equals(student2Name))
System.out.println(“student1 and student2 have same name”);
System.out.println(“student1 and student2 have different names”);

Here “student1 and student2 have different names” is always printed even when names are same, now you see why else is important.

As I said earlier, you can also execute multiple statements in case a booleanExpression is true or false, just put the statements in block. See code below:

//multiple statements in if/else block – if-else example

private static void calculateTax()
{
float salary = 10000.56f;
float taxRate = 15.5f;//%
float netTax = 0.0f;
boolean booleanExpression = salary > 10000;
if (booleanExpression)
{
//additional surcharge apply
System.out.println(“additional surcharge applies”);
float additionalSurcharge = 2.3f;//%
float tax = salary * taxRate / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else
{
netTax = salary * taxRate / 100.0f;
}
System.out.println(“netTax = “+netTax);
}

It is good practice to use curly braces always even when you have only one statement to execute in if or else block.

If you went through last lesson on boolean expressions, you would know that you can have more complex boolean expressions with if statement (but make sure you take care of precedence so that you get expected result).

if (a>b && b <= c && (!d || a-b != 0))
{
//do something
}
else
{
//do else part
}

If-else-If (and so on)

Sometimes you need to execute code1 when X condition is met, otherwise if Y condition is met then you need to execute code2. In such a scenario you can use if-else-if:

//if-else-if example

static void calculateTax1()
{
float salary = 5000.56f;
float taxRate1 = 15.5f;//%
float taxRate2 = 13.5f;//%
float netTax = 0.0f;
boolean booleanExpression1 = salary > 10000;
boolean booleanExpression2 = salary > 5000;
if (booleanExpression1)
{
//additional surcharge apply
System.out.println(“additional surcharge applies”);
float additionalSurcharge = 2.3f;//%
float tax = salary * taxRate1 / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else if (booleanExpression2)
{
netTax = salary * taxRate2 / 100.0f;
}
System.out.println(“netTax = “+netTax);
}

Similarly see this code :

if (booleanExpression1)
{
//additional surcharge apply
System.out.println(“additional surcharge applies”);
float additionalSurcharge = 2.3f;//%
float tax = salary * taxRate1 / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else if (booleanExpression2)
{
netTax = salary * taxRate2 / 100.0f;
}
else if (booleanExpression3)
{
netTax = salary * taxRate3 / 100.0f;
}
else
{
//finally for remaining cases
netTax = 100.0;//flat
}

Nested if

You can use if within if statement (because if statement is just another java statement so it can appear inside an if block):

if (booleanExpression1)
if (booleanExpression2)
//do this
else
//do this else – note that this else belongs to if (booleanExpression2)
else
//main else

else for innermost if (in case required) must appear before the else of just outer if and so on.
What if you do not need else of inner if, then use parenthesis.

if (booleanExpression1)
{
if (booleanExpression2)
//do this – inner if has no else part
}
else
//main else

There is no limit on nesting if statements :

if (booleanExpression1)
if (booleanExpression2)
if (booleanExpression3)
if (booleanExpression4)
//do this
else
//do this else – note that this else belongs to if (booleanExpression4)
else
//do this else – note that this else belongs to if (booleanExpression3)
else
//do this else – note that this else belongs to if (booleanExpression2)
else
//main else

Here’s updated Code to test what we learned so far in lesson 5 :

package testclasses;
public class ControlFlow
{
public static void main(String[] args)
{

//BOOLEAN EXPRESSION EXAMPLES
booleanExpressionExamples();

//simple if-else examples
simpleIfElseExamples();

//MULTIPLE STATEMENTS IN IF-ELSE BLOCK
calculateTax();

//if-else-if example
calculateTax1();

//nested if example
nestedIfExample();
}

private static void booleanExpressionExamples()
{
relationalOperatorExamples();
logicalOperatorExamples();
operatorPrecedenceExamples();
}

private static void relationalOperatorExamples()
{
System.err.println(“nnRelational Operator Examples”);
boolean condition = 10 > 5;
System.out.println(“10 > 5 >> “+condition);
condition = 10 == 10;//true
System.out.println(“10 == 10 >> “+condition);
condition = 10 == 5;//false
System.out.println(“10 == 5 >> “+condition);
condition = 10 > 10;//false
System.out.println(“10 > 10 >> “+condition);
condition = 10 < 11;//true
System.out.println(“10 < 11 >> “+condition);
condition = 10 >= 10;//true
System.out.println(“10 >= 10 >> “+condition);
condition = 10 <= 10;//true
System.out.println(“10 <= 10 >> “+condition);
condition = 10 != 10;//false
System.out.println(“10 != 10 >> “+condition);
System.err.println(“END Relational Operator Examplesnnnn”);
}

private static void logicalOperatorExamples()
{
System.err.println(“Logical Operator Examples”);
boolean condition = true && true;//result is true
System.out.println(“true && true >> “+condition);
condition = true & false;//result is false
System.out.println(“true & false >> “+condition);
condition = (10 < 5) || (8 == 8);//result is true
System.out.println(“(10 < 5) || (8 == 8) >> “+condition);
condition = (10 < 5) | (8 == 8);//result is true
System.out.println(“(10 < 5) | (8 == 8) >> “+condition);
condition = (10 != 10) ^ (8 != 8);//result is false
System.out.println(“(10 != 10) ^ (8 != 8) >> “+condition);
condition = (10 != 10) ^ (8 == 8);//result is true
System.out.println(“(10 != 10) ^ (8 == 8) >> “+condition);
condition = (10 == 10) ^ (8 == 8);//result is false
System.out.println(“(10 == 10) ^ (8 == 8) >> “+condition);
condition = !(10 == 10);//result is false
System.out.println(“!(10 == 10)>> “+condition);
condition = !(10 == 10) || !(8!=8);//result is true
System.out.println(“!(10 == 10) || !(8!=8)>> “+condition);
System.err.println(“END Logical Operator Examplesnnnn”);
}

private static void operatorPrecedenceExamples()
{
System.err.println(“Operator Precedence Examples”);
boolean condition = 10 == 10 ^ false;//result is true
System.out.println(“10 == 10 ^ false >> “+condition);
condition = 10 == 10 && 10 > 5;//result is true
System.out.println(“10 == 10 && 10 > 5 >> “+condition);
//THIS IS AN ERROR CASE – WILL NOT COMPILE – COMMENTED OUT
//condition = !10 == 10 && 10 > 5;//result is false
//System.out.println(“!10 == 10 && 10 > 5 >> “+condition);
condition = !(10 == 10) && 10 > 5;//result is false
System.out.println(“!(10 == 10) && 10 > 5 >> “+condition);
System.err.println(“END Operator Precedence Examplesnnnn”);
}

//simple if-else examples
private static void simpleIfElseExamples()
{
System.err.println(“nnSimple If Else Examples”);
if (10>5)
System.out.println(“I am always executed”);
if (5>10)
System.out.println(“I am never executed”);

if (true)
System.out.println(“I am always true”);

if (false)
System.out.println(“I am always false – hence never executed”);

boolean result = 10>5;
if (result)
System.out.println(“I always get executed”);

result = 10<5;
if (result)
System.out.println(“I never get executed”);

String student1Name = “Ajay”;
String student2Name = “Ajay”;
String student3Name = new String(“Ajay”);
//WRONG WAY TO COMPARE – THIS IS COMPARING OBJECT REFERENCES – ALTHOUGH IT WORKS IN THIS CASE BECAUSE “AJAY IS A LITERAL”
if (student1Name == student2Name)
System.out.println(“student1 and student2 have same name”);

//WRONG WAY TO COMPARE – THIS IS COMPARING OBJECT REFERENCES
if (student1Name == student3Name)
System.out.println(“student1 and student3 have same name”);

//RIGHT WAY TO COMPARE – THIS IS COMPARING OBJECT VALUES
if (student1Name.equals(student2Name))
System.out.println(“student1 and student2 have same name”);

//RIGHT WAY TO COMPARE – THIS IS COMPARING OBJECT VALUES
if (student1Name.equals(student3Name))
System.out.println(“student1 and student3 have same name”);

student1Name = “Ajay”;
student2Name = “Vijay”;
if (student1Name.equals(student2Name))
System.out.println(“student1 and student2 have same name”);
else
System.out.println(“student1 and student2 have different names”);

//WRONG – USE ELSE
student1Name = “Ajay”;
student2Name = “Ajay”;
if (student1Name.equals(student2Name))
System.out.println(“student1 and student2 have same name”);
System.out.println(“student1 and student2 have different names”);
System.err.println(“END Simple If Else Examplesnnnn”);
}

//multiple statements in if/else block – if-else example
private static void calculateTax()
{
System.err.println(“nnmultiple statements in if/else block Example”);
float salary = 10000.56f;
float taxRate = 15.5f;//%
float netTax = 0.0f;
boolean booleanExpression = salary > 10000;
if (booleanExpression)
{
//additional surcharge apply
System.out.println(“additional surcharge applies”);
float additionalSurcharge = 2.3f;//%
float tax = salary * taxRate / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else
{
netTax = salary * taxRate / 100.0f;
}
System.out.println(“netTax = “+netTax);
System.err.println(“END multiple statements in if/else block Examplennnn”);
}

//if-else-if example
static void calculateTax1()
{
System.err.println(“nnif-else-if Example”);
float salary = 5000.56f;
float taxRate1 = 15.5f;//%
float taxRate2 = 13.5f;//%
float netTax = 0.0f;
boolean booleanExpression1 = salary > 10000;
boolean booleanExpression2 = salary > 5000;
if (booleanExpression1)
{
//additional surcharge apply
System.out.println(“additional surcharge applies”);
float additionalSurcharge = 2.3f;//%
float tax = salary * taxRate1 / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else if (booleanExpression2)
{
netTax = salary * taxRate2 / 100.0f;
}
System.out.println(“netTax = “+netTax);
System.err.println(“END if-else-if Examplennnn”);
}

//nested if example
static void nestedIfExample()
{
System.err.println(“nnnested if Example”);
float salary = 15000.56f;
float taxRate1 = 15.5f;//%
float taxRate2 = 13.5f;//%
float netTax = 0.0f;
int age = 37;
boolean booleanExpression1 = salary > 10000;
boolean booleanExpression2 = salary > 5000;
boolean booleanExpression3 = age <35 && age > 25;
boolean booleanExpression4 = age <= 25;
if (booleanExpression1)
{
//additional surcharge apply if young :-)
if (booleanExpression4)
{
System.out.println(“additional high surcharge applies”);
float additionalSurcharge = 2.3f;//%
float tax = salary * taxRate1 / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else if (booleanExpression3)//moderate surcharge for moderate aged
{
System.out.println(“additional moderate surcharge applies”);
float additionalSurcharge = 1.3f;//%
float tax = salary * taxRate1 / 100.0f;
netTax = tax + additionalSurcharge * tax;
}
else
{//no surcharge for old
System.out.println(“additional moderate surcharge applies”);
netTax = salary * taxRate1 / 100.0f;
}
}
else if (booleanExpression2)
{
netTax = salary * taxRate2 / 100.0f;
}
System.out.println(“netTax = “+netTax);
System.err.println(“END nested if Examplennnn”);
}

}

I guess above details are enough to make you feel comfortable with if statement. Let me know if you have any questions. We will learn about switch statement in next lesson.

[Him. Uni. Friends] Re: Approach Java – 5.3 Adding power to language (Conditional constructs, loops and more) – Switch Statement

Switch StatementThis is another statement that can be used to control execution flow. Syntax of switch statement is :

switch (flag)
{
case A1://code 1;
case A2://code 2;
…
…
case An://code n;
case default://code def;
}

If flag = Ax “code x” is executed. On the other hand if flag does not match any value from A1 to An then “code def” is executed. “flag” can be a variable or any valid java expression that results in value of any of following datatypes:byte, short, int, Character, Byte, Short, Integer, or an enumNote that valid datatypes do not contain boolean, long, float and double.Let’s take a look at an example:package approach.java.lesson5;

public class SwitchExamples {
public static void main(String[] args)
{
testByte(Byte.MIN_VALUE);
}

private static void testByte(byte flag) {
switch(flag)
{
case Byte.MIN_VALUE: System.out.println(“MIN flag is “+Byte.MIN_VALUE);
case Byte.MAX_VALUE: System.out.println(“MAX flag is “+Byte.MAX_VALUE);
default: System.out.println(“flag not matching”);
}
}
}

Compile and run:

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples
MIN flag is -128
MAX flag is 127
flag not matching

Compile and run again after changing testByte(Byte.MIN_VALUE); to testByte(Byte.MAX_VALUE);:

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples
MAX flag is 127
flag not matching

As you can deduce from output of test1 and 2 above, code is going through ‘Default’ case in both executions. In test1, code even went through MAX case while it should have matched only Byte.MIN_VALUE case.

This is happening because of the nature of Switch statement in Java. Once it finds a matching case, it executes the code against it and then it keeps on rolling through the rest of the cases regardless of whether they match the flag or not. To stop this behavior break; statement is used, which forces it to exit out of switch statement.

Modified code :

package approach.java.lesson5;
public class SwitchExamples {
public static void main(String[] args)
{
testByte(Byte.MIN_VALUE);
}

private static void testByte(byte flag) {
switch(flag)
{
case Byte.MIN_VALUE: System.out.println(“MIN flag is “+Byte.MIN_VALUE);
break;
case Byte.MAX_VALUE: System.out.println(“MAX flag is “+Byte.MAX_VALUE);
break;
default: System.out.println(“flag not matching”);
}
}
}

Now compile and run:

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples
MIN flag is -128

Looks all better, right? We will see more uses of break; statement in following lessons.

You might think you can use return statement in place of break. Let’s try that :

package approach.java.lesson5;
public class SwitchExamples {
public static void main(String[] args)
{
testByte(Byte.MIN_VALUE);
}

private static void testByte(byte flag) {
switch(flag)
{
case Byte.MIN_VALUE: System.out.println(“MIN flag is “+Byte.MIN_VALUE);
return;
case Byte.MAX_VALUE: System.out.println(“MAX flag is “+Byte.MAX_VALUE);
return;
default: System.out.println(“flag not matching”);
}
}
}

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples
MIN flag is -128

Yey, it works!! Yes return can be used but only when you have no code following switch statement. Take a look below:

package approach.java.lesson5;
public class SwitchExamples {
public static void main(String[] args)
{
testByte(Byte.MIN_VALUE);
}

private static void testByte(byte flag) {
switch(flag)
{
case Byte.MIN_VALUE: System.out.println(“MIN flag is “+Byte.MIN_VALUE);
return;
case Byte.MAX_VALUE: System.out.println(“MAX flag is “+Byte.MAX_VALUE);
return;
default: System.out.println(“flag not matching”);
}
System.out.println(“I must be executed for successful test”);
}
}

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples
MIN flag is -128

As you can see System.out.println outside switch is not executed in this case. This is because return statement exits the control out of function. We need to use break here, which only exits the control out of switch statement.

package approach.java.lesson5;
public class SwitchExamples {
public static void main(String[] args)
{
testByte(Byte.MIN_VALUE);
}

private static void testByte(byte flag) {
switch(flag)
{
case Byte.MIN_VALUE: System.out.println(“MIN flag is “+Byte.MIN_VALUE);
break;
case Byte.MAX_VALUE: System.out.println(“MAX flag is “+Byte.MAX_VALUE);
break;
default: System.out.println(“flag not matching”);
}
System.out.println(“I must be executed for successful test”);
}
}

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples
MIN flag is -128
I must be executed for successful test

Go through code at the end of this lesson for more complex examples.

Enums in short
In java 5.0 Enums were introduced. We will cover them shortly here from switch statement’s perspective. But I will add them to TOC for detailed coverage in a later lesson.
In very simple terms, Java enums is a type that can be used to define enumerated values. An example:

enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

Here Day is the name of enumeration and Monday…Sunday are its values. This variable Day can be used as the flag in switch statement. See code example below :

package approach.java.lesson5;
public class SwitchExamples {
enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

public static void main(String[] args)
{
testEnum(Day.Monday);
}

private static void testEnum(Day day) {
switch(day)
{
case Monday: System.out.println(“Monday”);
break;
case Tuesday: System.out.println(“Tuesday”);
break;
default: System.out.println(“Neither Monday nor Tuesday”);
}
}
}

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples

Monday

Isn’t it much better than using int values to represent weekday?

If versus Switch

You might think that same can be done with if statement also, then why to use switch. You are right. Most of the time deciding between if and switch is a matter of judgment. I personally feel switch is better when you have to compare same expression against several different values. It keeps the code clean. But remember, missing break statement is a very common mistake programmers make and this can lead to invalid logic. Such a defect is also hard to detect. So while attempting to write clean code, keep the logic intact.

If statement is more powerful than switch in the sense that it can use relational and logical operators to build more complex expressions. This is not possible with switch which can work against integer family expressions and enums only.

More complex switch examples

package approach.java.lesson5;
public class SwitchExamples {
enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum Month {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};

public static void main(String[] args)
{
testByte(Byte.MIN_VALUE);
testEnum(Day.Monday);
testCharacter(new Character(‘x’));
testExpression();
testNestedSwitch(Month.Apr, Day.Saturday);
}

private static void testByte(byte flag) {
switch(flag)
{
case Byte.MIN_VALUE: System.out.println(“MIN flag is “+Byte.MIN_VALUE);
break;
case Byte.MAX_VALUE: System.out.println(“MAX flag is “+Byte.MAX_VALUE);
break;
default: System.out.println(“flag not matching”);
}
}

private static void testEnum(Day day) {
switch(day)
{
case Monday: System.out.println(“Monday”);
break;
case Tuesday: System.out.println(“Tuesday”);
break;
default: System.out.println(“Neither Monday nor Tuesday”);
}
}

private static void testCharacter(Character flag) {
switch(flag)
{
case ‘a’: System.out.println(“Character is a”);
break;
case ‘x’: System.out.println(“Character is x”);
break;
default: System.out.println(“flag not matching”);
}
}

private static void testExpression() {
switch(10 * 875% 5)
{
case 0: System.out.println(“Remainder is 0″);
break;
case 1: System.out.println(“Remainder is 1″);
break;
default: System.out.println(“flag not matching”);
}
}

private static void testNestedSwitch(Month month, Day day) {
switch(month)
{
case Feb:
System.out.println(“Month is Feb”);
switch(day)
{
case Friday:
System.out.println(“Day is Friday”);
break;
case Saturday:
System.out.println(“Day is Saturday”);
break;
case Sunday:
System.out.println(“Day is Sunday”);
break;
}
break;
case Mar:
System.out.println(“Month is Mar”);
switch(day)
{
case Friday:
System.out.println(“Day is Friday”);
break;
case Saturday:
System.out.println(“Day is Saturday”);
break;
case Sunday:
System.out.println(“Day is Sunday”);
break;
}
break;
case Apr:
System.out.println(“Month is Apr”);
switch(day)
{
case Friday:
System.out.println(“Day is Friday”);
break;
case Saturday:
System.out.println(“Day is Saturday”);
break;
case Sunday:
System.out.println(“Day is Sunday”);
break;
}
break;
default: System.out.println(“flag not matching”);
}
}
}

javac approach/java/lesson5/SwitchExamples.java
java approach.java.lesson5.SwitchExamples

MIN flag is -128
Monday
Character is x
Remainder is 0
Month is Apr
Day is Saturday

We will proceed ahead in lesson. Keep reading, keep approaching Java, your questions are most welcome.

Updated TOC:
1. Introduction to OOPs
2. Java Overview (P/F independence, versions, JRE, JDK)
3. Java programming basics (class structure, compiling & executing programs, member variables, methods, constructors, creating objects, data types)
4. Introduction to Packages and scope identifiers (import statement as well)
5. Adding power to language (Conditional constructs, loops and more)
6. Data Structures (Collections) – Generics and Enums
7. Exception Handling
8. File Handling
9. JDBC
10. Closing and Forward

Leave a Reply

Your email address will not be published. Required fields are marked *