Java Lab Sessions-CSL 201: 1 Intro 2 (3 4)
Java Lab Sessions-CSL 201: 1 Intro 2 (3 4)
1 class intro
2 {
3
4 }
A class in Java is called a public class if the keyword public is added before the
keyword class in a class definition. For example the code of listing 2 creates a
public class newintro.,
1
where var is any string. Above syntax declares that var is a reference/handle
of type intro. It is to be noted that the above syntax only creates a
handle/reference to an intro object. Actual object is not created by
this syntax.. Java provides a keyword new to create a new object of a given
type and assign it to a reference of that type.
intro var = new intro;
The above syntax does two things. It first declares var to be a reference/handle
of intro type. Second, it creates a new object of type intro and assign its
reference/address to variable var. It is clear that many objects can be created
of the same type/class . Each of these objects occputy separate memory area.
Fields and Methods A class consists of a set of variables, also called fields,
and a set of functions, also called methods. For an object of a given class, the
fields and methods of that class are accessed using . operator. A field of a class
is of the following form [Qualifier] type variablename where Qualifier is
optional and can take following values,
public: It means that this field can be accessed from outside the class by
just using objectname.fieldname.
static: It means that to access this field you do not need to create an
object of this class. Therefore this field is also sometimes called as class
variable/field.
For the example program in listing 3, credits is a public static variable
and hence can be accessed from outside this class as intro.credits. On the
other hand, age is only a pubic variable and hence can only be accessed after
creating an object of intro type as below.
intro var = new intro;
var.age = 10;
Above code first creates an object of intro class and then assign value 10 to the
field age of this object. It is to be noted that every object of a class, contains
different copies of non-static variable (e.g. age in listing 3) and the same copy
of static variable (credits in listing 3). You do not require to create an object
to access the static members of a class.
1 class intro
2 {
3 public int age ;
4 public static int credits ;
5 }
2
public: A public method can be invoked from outside the class using the
object of that class.
static: A static method can be called without creating an object of that
class.
Following restrictions are applied on invocation of static methods.
static function can not call non-static functions of that class.
static function can not access non-static variables/fields of that class.
Every class in Java has a public method by default, it is called
Constructor of that class. The name of the constructor function is same as
the name of the class without any return type, but it can take a set of arguments
like any method. This method is called when an object of this class is created
using new operator as shown earlier.
1 class intro
2 {
3 public int age ;
4 public static int credits ;
5 public intro ( int a )
6 {
7 age = a ;
8 }
9 public void setage ( int newage )
10 {
11 age = newage ;
12 }
13 public static int getcredit ()
14 {
15 return credits ;
16 }
17 }
In the example program of listing 4, static function getcredit returns the value
of static field credits. Function setage takes an integer argument and set the
value of the field age to this value. Return type of setage is void as it does not
return any value, while the return value of getcredit is int. We also have a
constructor in this class which takes an integer and assign it to field age of that
object. Constructors are mainly used to make sure that all fields of an object
are initialized properly at the time of creation.
Having covered the most essential aspect of a class definition in Java, now
let us look at the process of compiling and executing a Java program.
3
If a java file contains no public class then the name of the file must be
same as any of the non-public class present in that file.
Smallest non-empty java file, which is compilable, must have at least one
class declaration.
Executing a java program Once you get a set of class files after compiling
a java program, you execute the program with the following command.
java first
where first is the name of the public class, if any, which was declared in
first.java. It is to be noted that to execute a java program it must
contain at least one public class with a public static method main
declared in it.
Why a method main is needed? Method main is like entry point for a java
program. It must be static so that the java runtime do not need to instantiate
any object to executed it. It must be public so that it can be invoked by java
runtime.
What minimal changes do you require to compile and execute the program of listing
4?
4
2 {
3 public static void main ( String args [])
4 {
5 System . out . println ( " Hello world " );
6 }
7 }
Compile and execute the program of listing 5. Execute and show its output to your
TA.
We can modify the program of listing 5 as following
Create a public function in class intro which prints Hello world on
screen.
Create an object of this class in function main and invoke/call the function
define above on this object.
Along the same line,
Complete the program of listing 6 (in place of ) such that it prints Hello world
on console.
Reading from console To read from command line we use the class Scanner
which is defined in the package java.util.Scanner. Following program takes one
string (name) and an integer (age) from the command line and store it in two
fields.
5
13 obj . name = s . nextLine ();
14 System . out . println ( " Enter your age " );
15 obj . age = s . nextInt ();
16 s . close ();
17
18 System . out . println ( " Name : " + obj . name );
19 System . out . println ( " Age : " + obj . age );
20 }
21 }
Write a java program which takes two integer numbers as input and returns the
minimum of these two.
loop and condition constructs Java has three constructs for implementing
loops,
do{Statements} while(boolean condition);,
while(boolean condition){Statements}, and
for(initialization; terminating condition; post-operation){Statements}.
Listing 8 shows a program to print all numbers from 10 to 100 using all three
looping constructs.
6
if(condition) {Statements} else {Statements}
Switch-case. break is used to break the flow of program once a case is
satisfied.
An example program to check if a given number is even or odd is implemented
using both conditional constructs in listing 9.
Compile and execute the program of listing 9. After that remove the break of line
21 and again execute the program. What is the difference?
Write a java program to print all prime numbers between 10 and 1000 (including
10 and 1000 both).
7
When we pass an object as an argument to another function, we only pass
reference/handle of that object. This reference is also passed as value but
because this is a reference hence any change in the called function using this
reference changes the original object as well.
It is to be noted that the declaration of primitive type (like int, float etc.)
variables does not create reference/handle but creates the actual storage for that
variable. When a primitive type variable is passed as an argument to another
function, it is passed by value. But because actual value is copied to the
called function, instead of the reference, hence any change done to this copy is
not reflected back in the original copy of this variable in calling function. Let
us try to understand it with the help of an example in listing 10.
Listing 10: Parameters are always passed by value; Objects are no exception
1 int [] record ;
2 float [] points ;
3 Student [] sectionb ;
Notice that you can not specify number of elements in array by only declaring
the array variable. A declaration as in listing 11 only declares that the variable
is an array of given type.
int[] record = new int[5];
8
declares that the variable record is an array of integer type and also allocates
the space of 5 integers in this array. Similarly,
int[] record = {1,2,3};
declares that the variable record is an array of integer type and contains ele-
ments 1,2 and 3. Its size has been fixed by this declaration to three elements.
Similarly,
Student[] sectionb = new Student[5];
declares that the variable sectionb is an array of Student type and also allo-
cates the space of 5 Student objects in this array. Given an array variable, say
record, the length of the array is given by the field length, as in listing 12.
9
where name is a reference to an object of string type. To create actual string
object and assign that to the reference name, we need to do the following,
Consider an example of listing 13. It reads a line from console and store it
in a string variable line. Then it iterates over all characters of this string
and check if the character at any index (using charAt function) is equal to
whitespace ( ). If it is not equal to whitespace then it concatenates the
string representation of that character (obtained by substring function) in a
temporary string newline. When loop terminates, newline points to a string
which is same as the original one without any whitespace. Function substring
takes two arguments, starting index and end index, and return the substring
present in between them. It does not include the character present at the end
index.
To get more useful functions on String class of Java, please refer to the
following link.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
This link/site host the documentation of all classes and associated functions of
Java language. If you want to know about any function of any utility class, say
Date, File, String etc., just go to the above link and look for the appropriate
class name and its member functions.
10
Vector Vector is equivalent to expandable array. You can create a Vector
object without defining the length of it. The length of the Vector objects keeps
on adjusting based on the current size of this Vector object. To specify that a
Vector object contains objects of a particular type, we instantiate the object
as following,
Vector<Integer> v = new Vector<Integer>();
It is to be noted that vector stores a set of objects derived from Object class and
because primitive types like int, float etc are not derived from Object class
therefore in that case we use corresponding wrapper classes Integer, Float etc.
Above syntax create a new Vector object to contain integers. Notice that we
do not specify the length of the vector. To add an element to a vector, we call
add function.
v.add(3);
v.add(4);
Java also provides a class called Collection which has a set of algorithm, like
sort, swap etc. These algorithms give a very concise way of operating on Vector
class for sorting, swapping and other functions. For example the program in
listing 14 sorts a vector of integers and then reverse the order of elements in a
vector.
More about collection class and the associated algorithms can be read from the
following link.
http://docs.oracle.com/javase/tutorial/collections/
http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html
11
A very important concept in Java, for handling traversal of container classes
like Set, List, Vector, HashMap etc., is the notion of Iterator. An iterator over
a container class is an object of class Iterator which allows us to traverse over
the elements of that container class without revealing the internal structure. For
example, a List class might be constructed using array or linked list, but the
user of class List can traverse it with the help of Iterator object of that class.
The function hasNext() of Iterator object allows us to check if a container
contains any more element or not. Another function next() returns the next
element (with respect to the current position of iterator in that container).
Program in listing 15 traverses a vector using Iterator.
There are few things to be noted about Iterator as shown in listing 15.
The type of Iterator must match with the type of elements in the
container class which is to be traversed. Therefore in line 12 of
listing 15, we declare it as a reference of Iterator class and this class
is instantiated with Integer class. This is because we want to store the
iterator of the vector v, which is instantiated with Integer type, in it.
Function it.next() returns the element at the current position of iterator
in v and increment the current position.
12
creates an object of HashMap type such that the key is of Integer type and the
value is of String type. Listing 16 shows a program which uses HashMap to
store Integer-String pair. It also uses iterator to iterates over all elements of a
HashMap.
Function get returns the value associated with the given key, if any. If
there is no value stored in hashmap for this key then null is returned. (as
checked in line 10 and 16 of listing 16).
Function keySet() returns the set of keys stored in a hashmap. In line
22, we get the iterator of this set and store it in it. After that we iterate
over this set, as we did in listing 15, to find all key-value pairs stored in
hashmap hm.
13
What happens if we modify the last while loop of listing 16 as below.
Returns:
The absolute pathname string denoting the same file or directory
as this abstract pathname
Throws:
SecurityException - If a required system property value cannot be
accessed.
When such function is called then the caller has to make sure that if this func-
tion fails and throws an exception then that exception must be handled properly
in the caller. Java provides try-catch syntax to handle this issue. Any call to
a method, which can thrown an exception, must be surrounded by try-catch
block as shown in listing 18.
14
5 {
6 int [] data = new int [20];
7
8 try {
9 for ( int i =0 ; i < 21; i ++)
10 data [ i ] = 2* i ;
11 }
12 catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n en )
13 {
14 System . err . println ( " error in accessing array index " );
15 }
16 }
17 }
File handling Example program in listing 19 print the content of this file.
See the similarity of the code of listing 19 with the code of listing 7. In
listing 7 we were reading from console (standard input) and hence we
instantiated Scanner object with System.in object.
In listing 19 we want to read from file and therefore we first open a file
input stream as in line 8. After that we pass this object to Scanner class
to instantiate a new Scanner object, in line 9.
After that we use a while loop to print all lines present in the given file.
15
It is clear that you must have a file named file.txt in current directory
in which you are going to execute this program. If it is not the case then
you will see the error message of catch block (File not found).
In the program of listing 20, we first create an output stream object (we
created an input stream object for reading in listing 19).
Constructor of FileOutputStrem class takes two arguments. First one
specifies the filename that must be opened for writing. If the second
argument is true it means that the new content must be appended to the
existing content of this file (when true). When this argument is false, it
implies that the new content will overwrite the old content of this file.
After that we pass this object fs of FileOutputStream class to PrintStream
class constructor and create a new object p, in line 9.
For further reading on file IO in Java, please look at the following link.
http://docs.oracle.com/javase/tutorial/essential/io/fileio.html
Object oriented part of Java Even a modest introduction of Java will not
be complete without discussing that part of its syntax which helps in object
oriented programming. In this last part of lab session, we wish to give an
overview of syntax and semantics of OOPs concepts in Java.
16
Inheritance It must be clear now that a java program is a collection of class-
es/objects which work together (by means of method invocation) to implement
a given specification. Each class is essentially a collection of a set of fields
(data) and a set of methods operating on this data. The functionality of a class
is mainly determined by the methods defined in that class. Sometime, we need
a class which borrows most of its required functionalities from some existing
class. In that case we have two choices; either to copy paste those methods
from existing class to this newly created class or to inherit the new class from
this existing class. Inheritance is a mechanism which allows a class to borrow
already implemented functionalities in another class without copying the code.
It is to be noted that the concept of Inheritance is central to nearly all object
oriented programming languages. Each language might only differ in the syntax
for implementing inheritance. In java, we use a keyword extends to inherit
the functionalities of a class as given below.
class newc extends oldc
{
}
Here newc is a derived class/ subclass of the base class/super class/
parent class oldc. After inheritance, all public fields and public methods of
the base class are inherited by the derived class. If derived class has a function
f having same name and argument types as in the base class then function f
is said to override the base class implementation. Consider the program of
listing 21.
Listing 21: Inheritance and function overriding example
1 class first {
2 public int data ;
3 public void test (){
4 System . out . println ( " Function : test of base class " );
5 }
6 }
7
8 public class second extends first {
9 public void newtest (){
10 System . out . println ( " Newly added function in derived class " );
11 }
12
13 public void test (){
14 System . out . println ( " Function : test of derived class " );
15 }
16
17 public static void main ( String args [])
18 {
19 first basec = new second ();
20 first based = new first ();
21
22 basec . test ();
23 based . test ();
24 }
25
26 }
17
In above example (listing 21), we first create a class first with public
field data and public method test.
Function call in line 22 invokes test method of derived class even though
the reference was of base class. This is an example of changing the be-
haviour (invoking different functions) based on the actual object (second
in this case) stored in the reference variable (basec in this case). This is
an example of Function Polymorphism.
Function call in line 23 invokes test method of base class because the
actual object stored in based reference is also of type first.
Other subtle points involved in Inheritance and Polymorphism can be read from
the following link.
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Function overloading In Java, you can define more than one function hav-
ing same name in a class. This will not produce a compiler error as long as
all arguments of these functions are not of same types. While invoking such
function, compiler picks the correct function based on the type of arguments
passed to these functions. This concept is referred to as function overloading
and is a well known concept of object oriented programming languages.
18
17
18 }
Function overloading works only when the argument list of two functions,
having same name, does not match.
It is not possible to overload a function with another function having
same name and argument list but different return type, as shown by above
exercise.
1 interface myinterface
2 {
3 public void test ();
4 }
5
6 class secondimpl implements myinterface {
7
8 public void test (){
9 System . out . println ( " Function : test in second implemented class " );
10 }
11
12 }
13
14
15 public class interfaceex implements myinterface {
16
17 public void test (){
18 System . out . println ( " Function : test in first implemented class " );
19 }
20
21 public static void main ( String args [])
19
22 {
23 myinterface fun = new interfaceex ();
24 myinterface fun2 = new secondimpl ();
25 fun . test ();
26 fun2 . test ();
27 }
28
29 }
For further reading about interface please look at the following link.
http://docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
This precisely completes the broad overview/tutorial of java features which
you might require during your assignments. In case of any difficulty in Java,
internet (googling) is your best friend.
20