Lab1 6
Lab1 6
CS F213
LAB-1 [Introduction to Eclipse IDE]
DATE: 13/01/2025 TIME: 02 Hours
Eclipse overview
Getting Started
Installation
Start Eclipse
Eclipse UI Overview
Workspace
Perspective
Views and editors
Create your first java program in Eclipse
Create project
Create a Java class
Run your project in Eclipse
Java Examples
Example-1: Command Line Arguments (From command prompt)
Example-2: Command Line Arguments (From Eclipse IDE)
Example-3: Bicycle class
Exercise (Write your own Java code)
1. Eclipse Overview
Eclipse is an open source community that builds tools and frameworks for creating general purpose
application. The most popular usage of Eclipse is as a Java development environment which will be
described in this article.
2. Getting Started
2.1 Installation
Download "Eclipse IDE for Java Developers" from its website and unpack it to a directory. This is
sufficient for Eclipse to be used; no additional installation procedure is required.
To start Eclipse double-click on the file eclipse.exe in your installation directory. The system will
prompt you for a workspace. The workspace is the place where you store your Java projects. Select a
suitable (empty) directory and press Ok [See Figure-1given below]. Don’t click and check the
checkbox that says “Use this as default and do not ask again”.
Close the welcome page by press in little x besides the Welcome screen.
3. Eclipse UI Overview
Eclipse provides perspectives, views and editors. Views and editors are grouped into perspectives. All
projects are located in a workspace.
3.1. Workspace
The workspace is the physical location (file path) you are working in. You can choose the workspace
during start-up of eclipse or via the menu(File-> Switch Workspace-> Others).All your projects,
sources files, images and other artefacts will be stored and saved in your workspace.
3.2. Perspective
A perspective is a visual container for a set of views and editors.You can change the layout within a
perspective (close/open views, editors, change the size, change the position, etc.)
For Java development you usually use the "Java Perspective".You can change the layout within a
perspective (close/open views, editors, change the size, change the position, etc.). Eclipse allows you
to switch to another perspective via the menu (Window->Open Perspective -> Other).
A common problem is that you closed a view and don't know how to re-open this view. You can reset
a perspective to its originalstate via the menu (Window -> Reset Perspective).
Click on the checkboxthat says, "Create separate source andoutput folders". This generates all your
.class files corresponding to the .java files in your workspace into a separate output folder.
Figure-4: Allow output folders for source folders
Press finish to create the project. A new project is created and displayed as a folder. Open the folder
"oop.eclipse.ide.first".
Right click on src and select New -> Class [See Figure-5 below]
Create MyFirstClass, select the flag "public static void main (String[]args)" [See
Figure-6 below].
Figure-6: Specify Class Name
System.out.println(“Hello Eclipse”);
Now run your code. Right click on your Java class and select Run-as-> Java application [See Figure-8
below].
Figure-8: Run your java program
5. Java Examples
We know that each object in java is described in terms of its states and behaviours. Also we know that
an object is an instance of a class, whereas a class is a blueprint. In this example we are going to
represent a real world Bicycle in Java code. We will create a class Bicycle which has three states,
speed, numberOfGears, and cadence and it has methods to print the values of instance fields of
Bicycle object.
/* Bicycle class */
class Bicycle {
int speed=100;
intnoOfGears=5;
int cadence=40;
publicvoidprintState() {
System.out.println("Bicycle [cadence=" + cadence +
", noOfGears=" + noOfGears+ ", speed=" + speed +
"]");
}
}
}
3. Click on start, go to run option, type cmd and then hit the enter key
4. Type D: on command prompt
5. Execute the following command
D:\>javacBicycle.java[This command compiles the java code]
6. Execute the following command
D:\> java Bicycle [This command executes your java code]
1. Create the Bicycle.java class in Eclipse IDE [follow the same guidelines that are used to create
MyFirstClass.javaabove]. Type the same java code for Bicycle class that is described in Example-
1(a).
2. Run your program in Eclipse and see the output in console window.
2. Type the following code in this file and save the file:
class CommandLineArg1 {
publicstaticvoid main(String[] args) {
for(inti=0; i<args.length; i++){
System.out.println("args["+ i +"] =" + args[i]);
}
}
}
Example 3: Write one more program [as given below], compile and execute it from command
prompt.
class CommandLineArg2 {
publicstaticvoid main(String[] args) {
int sum = 0;
for(inti=0; i<args.length; i++){
sum += Integer.parseInt(args[i]);
}
System.out.println("Sum = " + sum);
}
}
Compile and execute this program as shown below:
D:\>javac CommandLine Arg2.java
D:\> java CommandLine Arg2 1 2 3 4 5 6 7 8 9 10
1. Create a java class file named CommandLineArguments in your workspace [Code given below].
2. We can give command line arguments to our program in eclipse. For passing command line
arguments to your program go to (Project->Properties->Run/Debug settings) and then in the
launch configuration select your java file to which you want to pass command line arguments to
[See Figure below].
Step-1: Select Project Properties
Step-2: In Run/Debug Settings select the file CommandLineArgument and press Edit
Step-3: Select Arguments tab and enter 10 numbers separated by space then press OK
EXERCISES
1. Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n),
where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. Also compute their average. [Note: the
value 20 should be passed as a command line arguments]
The output shall look like:
The first 20 Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
The average is 885.5
2. Write a Java program called SumDigits to sum up the individual digits of a positive
integer, given in the command line.
The output shall look like:
>java SumDigits 12345
The sum of digits = 1 + 2 + 3 + 4 + 5 = 15
3. Write a program called HarmonicSum to compute the sum of a harmonic series, as
shown below, where n=50000. The program shall compute the sum from left-to-right
as well as from the right-to-left. Obtain the difference between these two.
Hints:
1.1 Using BufferedReader for text based user input from the keyboard- Type the
following code in Example1.java and save it in D:\Lab2.
Compile the above code. [Note down what happens during compilation].
Exercise1: Write a program in java to take 10 integer numbers as user input using
the BufferedReader and print the sum of these numbers [name the file as
Exercise1.java].
[CAREFUL: when reading input with BufferedReader, the input is always read as
String, therefore you are required to parse the input to its correct type. In this
Exercise use Integer.parseInt() method]
1.2 Using the Scanner class for text based user input from the keyboard - Type the
following code in Example2.java and save it in D:\Lab2.
import java.util.Scanner;
class Example2 {
public static void main(String args[]){
//variable declaration
int num1;
double double1;
String numStr1, numStr2;
Compile and run the above code and observe the output?
Exercise2: Write the program description given in Exercise1 in java using the Scanner
class [name the file as Exercise2.java]
2.1 Write java implementation for a class named ‘Item’ which encapsulates the
details of items to be purchased by the customer of the XYZ shop. The class Item is
described as follows:
Attributes description:
a) itemName:String [Name of the ordered Item of the Customer]
b) itemidNo:String [unique identification number of the ordered Item of the Customer]
c) itemQuantity:int [quantity of the ordered Item of the Customer]
d) itemPrice:double [price of the ordered Item of the Customer]
Methods description:
The class supplies the methods(s) as per the following specification:
a) Any Item instance can be created either by supplying the value for all the instance
fields in the order of itemName, itemidNo, itemQuantity and itemPrice OR by
supplying the value for itemName, itemidNo and itemQuantity fields only OR by
supplying the value for itemName, and itemidNo fields only. If an Item instance is
created by providing the value for itemName, itemidNo and itemQuantity fields only
then value for itemPrice is by default initialized to 500. If an Item instance is created
by providing the value for itemName and itemidNo fields only then value for
itemPrice is by default initialized to 500 and value for itemQuantity is by default
initialized to 1.
b) Accessor and mutator methods are provided for every instance field.
c) All instance field(s) have a private visibility and all methods have a public visibility.
2.2 Write the java implementation for a class named ‘Customer’ which encapsulates
the details of registered customers of the XYZ shop who buy Items (class is
described above in 2.1) online. The class Customer is described as follows:
Attributes description:
a) name:String [ Name of the Customer]
b) idNo:String [unique identification number of the Customer]
c) balance:double [balance amount of the Customer]
d) item: Item [item purchased by the Customer]
Methods description:
The class supplies the methods(s) as per the following specification:
a) Any Customer instance can be created either by supplying the value for all the
instance fields in the order of name, idNo and balance OR by supplying the value for
name and idNo fields only. If a Customer instance is created by providing the value
for name and idNo fields only then value for balance is by default initialized to 5000.
b) Accessor methods(s) are provided for every instance field.
c) Mutator methods(s) are provided for the instance field name and idNo.
d) Method print() to print the details of item (itemName, itemidNo, iemQuantity and
itemPrice) purchased by the customer and balance amount of the customer after
purchasing the item.
e) A method named buyItem(Item item) is supplied. This operation displays details of
the item bought and the current balance, if the customer has sufficient balance and the
quantity specified by the user is greater than or equal to one. If the customer don’t
have the sufficient balance, this method displays the message “Insufficient
balance” .If the quantity specified by the user is less than one, this method displays
the message “Order is not valid”.
f) All the fields have private visibility and all methods have a public visibility.
Note: Assume only one item (any number of quantities) can be ordered at a time by
the customer.
Attributes:
(i) salary: double // salary to calculate tax
(ii) isPANsubmitted:boolean // PAN submission status
Methods:
The class supplies the operation(s) as per the following specification:
(i) A TaxOnSalary instance can be created either by supplying the value for the
instance field isPANsubmitted OR without supplying value for any field. If
TaxOnSalary instance is created by providing the value for isPANsubmitted then
the value for salary is initialized with 1000.00 however it can be reinitialized
through the method inputSalary() [which is described below]. If TaxOnSalary
instance is created without supplying value for any field, then value for salary
andisPANsubmitted is by default initialized to 0.0 and false respectively.
(ii) Accessor methods(s) are provided for every instance field.
(iii) A method for computing the tax based on salary [caculateTax() : double] is
supplied. The tax is calculated as per the rules shown below:
a. if salary < 180000 and isPANsubmitted = true, then tax payable is zero
b. if salary < 180000 and isPANsubmitted = false, then tax payable is 5% of the
salary
c. if 180000 < salary < 500000, then tax payable is 10% of the salary
d. if 500000 < salary < 1000000, then tax payable is 20% of the salary
e. if 1000000 < salary, then tax payable is 30% of the salary
(iv) A method named inputSalary() is supplied to read the value for the salary as an
input from the user [consider reading this value from keyboard] and to assign
the value to the corresponding instance variable salary.
JUnit Installation:
Step 3) In the central repository you are shown all versions of Junit that can be downloaded.
Usually, you will select the latest version. Click on jar link to download Junit version 4.12 as
shown below
Step 4) Visit https://github.com/junit-team/junit4/wiki/Download-and-Install again. Click
hamcrest-core.jar
For JUnit installation, you need JUnit jars, and you can download the desired version of JUnit jar
file from JUnit official website http://www.junit.org
Here is the jars list:
● JUnit.jar
● hamcrest-core.jar
Step 1) You need to set JUNIT_HOME environment variable to point out the base location
where you have placed JUnit Jars.
For example, if you have created a JUnit folder in c: drive and placed jars there, then for
environment settings you need to open control panel ->advanced ->environment variable.
1. Under environment window clicks on “new” button.
When you click on new button in environment variables, it will open another window
Step 2) A “New System Variable” window will open:
1. Provide variable name as “JUNIT_HOME”.
2. Provide JUnit value as JUnit path where you have copied JUnit jar files.
3. Click on OK.
When you click on OK, it will create a new system variable with the given name and value.
Step 3) After creating JUNIT_HOME, create another variable with the name CLASSPATH.
Again go to Environment Variables and follow the below steps.
1. Click on “new” button. When you click on new in environment variables, it will open
another window.
Step 4) In this step, point out JUNIT_HOME to JUnit.jar which is placed in JUnit folder as
given below:
1. Variable Name: CLASSPATH
2. Variable Value: %CLASSPATH%;%JUNIT_HOME%\JUnit4.10.jar;.;
3. Click on the OK button.
Step 5) Once you click on the ‘OK’ button, you can verify that a new environment variable
named “CLASSPATH” can be seen under system variable.
Download a JUnit jar based on the operating system you have on your system.Assume you have
copied the above JAR file onto the folder C:\>JUnit.
We assume that your Eclipse has inbuilt JUnit plugin. If it is not available in C:\>eclipse\plugins
directory, then you can download it from JUnit Plugin. Unzip the downloaded zip file in the
plugin folder of the Eclipse. Finally, restart Eclipse. Now your Eclipse is ready for the
development of JUnit test cases.
Testing the JUnit Framework:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
Create a java class file name TestRunner in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Unit Testing:
Unit testing involves the testing of each unit or an individual component of the software
application. It is the first level of functional testing. The aim behind unit testing is to validate unit
components with its performance. A unit is a single testable part of a software system and tested
during the development phase of the application software.
The purpose of unit testing is to test the correctness of isolated code. A unit component is an
individual function or code of the application. White box testing approach used for unit testing
and usually done by the developers.
There are two ways to perform unit testing: 1) manual testing 2) automated testing.
1) Manual Testing
If you execute the test cases manually without any tool support, it is known as manual testing. It
is time consuming and less reliable.
2) Automated Testing
If you execute the test cases by tool support, it is known as automated testing. It is fast and more
reliable.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "Hello World";
Message messageUtil = new Message(message);
@Test
public void testPrintMessage() {
assertEquals(message,messageUtil.printMessage());
}
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
Compile the MessageUtil, Test case and Test Runner classes using javac.
Assert class
The org.junit.Assert class provides methods to assert the program logic. All the assertions are in
the Assert class: public class Assert extends java.lang.Object
import org.junit.Test;
import static org.junit.Assert.*;
@Test
public void testAssertions() {
//test data
String str1 = new String ("abc");
String str2 = new String ("abc");
String str3 = null;
String str4 = "abc";
String str5 = "abc";
int val1 = 5;
int val2 = 6;
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac TestAssertions.java TestRunner.java
Now run the Test Runner, which will run the test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
The Junit 4.x framework is annotation based, so let's see the annotations that can be used while
writing the test cases.
@Test(timeout=1000) annotation specifies that method will be failed if it takes longer than 1000
milliseconds (1 second).
@BeforeClass annotation specifies that method will be invoked only once, before starting all the
tests.
@Before annotation specifies that method will be invoked before each test.
@After annotation specifies that method will be invoked after each test.
@AfterClass annotation specifies that method will be invoked only once, after finishing all the
tests.
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
//test case
@Test
public void test() {
System.out.println("in test");
}
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(result.wasSuccessful());
}
}
Compile the Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac JunitAnnotation.java TestRunner.java
Now run the Test Runner, which will run the test case defined in the provided Test Case
class.
C:\JUNIT_WORKSPACE>java TestRunner
Side Note: main method is static, since it must be accessible for an application to run, before any
instantiation takes place.
Let’s learn the use of the static keywords by doing some exercises.
1. class MyStatic {
Following diagram shows, how reference variables & objects are created and static variables are
accessed by the different instances.
It is possible to access a static variable from outside the class using the syntax
ClassName.VariableName. Uncomment line# 21& 22in StaticDemo class. Save and run
the StaticDemo class and observe the output again.
Uncomment line 11, 12 & 13of the MyStatic class. Run the StaticDemo class and observe the
output again.What do you see as an output? ANSWER = Error. This is because it is not possible
to access instance variable “a” from static method “increment”.
1.3 static blocks
Static blocks are also called Static initialization blocks. A static initialization block is a normal block
of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class
body. The runtime system guarantees that static initialization blocks are called in the order that they
appear in the source code. And don't forget, this code will be executed when JVM loads the class.
JVM combines all these blocks into one single static block and then executes. Here are a couple of
points I like to mention:
If you have executable statements in the static block, JVM will automatically execute these
statements when the class is loaded into JVM.
If you’re referring some static variables/methods from the static blocks, these statements will be
executed after the class is loaded into JVM same as above i.e., now the static variables/methods
referred and the static block both will be executed.
static {
System.out.println("This is first static block");
}
public StaticExample(){
System.out.println("This is constructor");
}
static {
System.out.println("This is second static block and "
+ staticString);
}
static {
staticMethod();
System.out.println("This is third static block");
}
public static void staticMethod() {
System.out.println("This is static method");
}
What will happen when you execute the above code? Run the code and observe the output.
First all static blocks are positioned in the code and they are executed when the class is loaded into
JVM. Since the static method staticMethod() is called inside third static block, its executed before
calling the main method. But the staticMethod2() static method is executed after the class is
instantiated because it is being called after the instantiation of the class.
Again if you miss to precede the block with "static" keyword, the block is called "constructor block"
and will be executed when the class is instantiated. The constructor block will be copied into each
constructor of the class. Say for example you have four parameterized constructors, and then four
copies of constructor blocks will be placed inside the constructor, one for each. Let’s execute the
below example and see the output.
public ConstructorBlockExample(){
System.out.println("This is no parameter constructor");
}
Now let's go back to static blocks. There is an alternative to static blocks —you can write a private
static method.
class PrivateStaticMethodExample {
public static varType myVar = initializeClassVariable();
The advantage of private static methods is that they can be reused later if you need to reinitialize the
class variable. So get more flexibility with a private static method in comparison to the corresponding
static initialization block. This should not mislead that a 'public' static method can't do the same. But,
we are talking about a way of initializing a class variable and there is hardly any reason to make such a
method 'public'.
Example-5 Consider the class Circle. It has methods to compute the radius and circumference of
a circle.
//overloaded constructor
Circle(double radius) {
this.radius = radius;Circle.PI = 3.141;
}
//accessor method
public double getRadius() {return radius;}
//mutator method
public void setRadius(double radius) {this.radius = radius;}
When you are passing any Object as a parameter to a method then two values are passed: state of the
object as well as a reference variable of some type which is pointing to that object. An object is always
passed by reference with respect to its instance field values i.e. state of the object (it can be changed by
using the same reference variable).If you are changing the values of instance fields by using same
reference variable that has been passed from caller method then changes will be reflected in the caller
method also. This is what we mean by call by reference. Object reference itself is passed by value not
by reference. The called method if tries to change the reference of passed parameter to another object
of same type then that change remains local only and will not be reflected to caller method.
Consider the following program to calculate the distance between two points in a 2-dimensional
coordinate plane. Observe how we can pass objects as parameters to the methods.
// Pass By Reference
Point p1 = new Point(10,20);
System.out,println(p1); // See the o/p for this line
Point.changeState(p1);
System.out,println(p1); // See the o/p for this line
// Pass By value
Point p2 = new Point(100,200);
System.out,println(p2); // See the o/p for this line
Point.changeReference(p2);
System.out,println(p2); // See the o/p for this line
There are two driver classes being given for the Box class. Observe the output in each case.
First case Second Case
public class BOXTest{ class BOXtest{
public static void main(String args[]){ public static void main(String args[]){
BOX b1 = new BOX(10,40,60); BOX b1 = new BOX(10,40,60);
BOX b2 = new BOX(20,30,80); BOX b2 = new BOX(20,30,80);
System.out.println(b1); System.out.println(b1);
System.out.println(b2); System.out.println(b2);
BOX.swapBoxes(b1,b2); BOX temp = b1;
System.out.println(b1); b1 = b2;b2 = temp;
System.out.println(b2); System.out.println(b1);
} System.out.println(b2);
}//End of Main }
}//End of Main
3. Wrapper Classes and Primitive Types
Java supports 8 primitive types (byte, short, int, long, boolean, float, double, char). The primitive type
values are not implemented as objects. But there are certain situations when there is a need to convert
a primitive type value into an object type. e.g. we know that System.out.println() statement displays
the output by converting the arguments to string form. Now just think what happens for the following
statement:
System.out.println(10);
Can toString() from Object class can be applied to int type. No, toString() cannot be called thru a
primitive value. Rather compiler converts a primitive type value first to its corresponding wrapper type
object (Integer in this case) and then invokes toString() over Integer type object. So at compile time
the abovestatement is converted to
System.out.println(new Integer(10).toString());
Similarly there are many other situations where it is must to convert a primitive type value to a
wrapper type object. The table given below shows primitiveas well as their corresponding wrapper
classes.
Auto boxing is the process of converting a primitive type value to its corresponding wrapper type
object automatically and Similarly the process of getting a primitive type value back from a wrapper
type object is known as auto Unboxing. Latest java compiler supports both auto boxing / and
Unboxing automatically. But earlier java versions (1.3 and earlier) they do not support these features
automatically and in that version of java programmer has to perform these operations explicitly.
To know more about these operations try to compile and execute the following programs.
/* CASE-1 */
public class Test1{
public static void main(String args[]){
Integer I = new Integer(10);
Integer J = new Integer(20);
// Observe the output for following two
// statements carefully
System.out.println(I.intValue());
System.out.println(I);
// Observe the output for following two
// statements carefully
System.out.println(J.intValue());
System.out.println(J);
Integer K1 = new Integer(I.intValue()+J.intValue());
// What happens for the following statement
// (Auto Unboxing)
Integer K2 = I + J + K1; System.out.println(K2);
}
}
/* CASE-2 */
class Test2 {
public static void main(String args[]){
Integer I = 10; // what happens for this statement
Integer J = 20; // what happens for this statement
// Observe the output for following two
// statements carefully
System.out.println(I.intValue());
System.out.println(I);
// Observe the output for following two
// statements carefully
System.out.println(J.intValue());
System.out.println(J);
Integer K1 = new Integer(I.intValue()+J.intValue());
Integer K2 = I + J + K1;
System.out.println(K2);
}
}
BIRLA INSTIUTE OF TECHNOLOGY AND SCIENCE, PILANI
CS F213
LAB-5 [Class Design Basics - Part-3]
AGENDA DATE: 08/02/2025 TIME: 02 Hours
1. Inheritance
2. Polymorphism (method overriding and method overloading, Overriding the toString() method)
ghfhj
3. Abstract Class
4. Reflection
1 Inheritance
In OOP, we often organize classes in the hierarchy to avoid duplication and reduce redundancy. The
classes in the lower hierarchy inherit all the state variables and methods from the higher hierarchies.
A class in the lower hierarchy is called a subclass (or derived, child, extended class). A class in the
upper hierarchy is called a superclass (or base, parent class). For example,
UML Notation: The UML notation for inheritance is a solid line with a hollow arrowhead leading
from the subclass to its superclass. By convention, superclass is drawn on top of its subclasses as
shown.
1.1 An Example on Inheritance
In this example, we derive a subclass called Cylinder from the superclass Circle. The
class Cylinder inherits all the member variables (radius and color) and methods
(getRadius(), getArea(), among others) from its superclass Circle. It further defines a variable
called height, two public methods -getHeight() and getVolume()and its own constructors.
Circle.java
1// Define the Circle class
2public class Circle { // Save as "Circle.java"
3// Private variables
private double radius;
private String color;
6
7// Constructors (overloaded)
8 public Circle() { // 1st Constructor
9 radius = 1.0;
10 color = "red";
11 }
12 public Circle(double r) { // 2nd Constructor
13 radius = r;
14 color = "red";
15 }
16 public Circle(double r, String c) { // 3rd Constructor
17 radius = r;
18 color = c;
19 }
20// Public methods
public double getRadius() {
return radius;23
}
public String getColor() {
return color;26
}
public double getArea() {
return radius*radius*Math.PI;29
}
30}
Cylinder.java
1// Define Cylinder class, which is a subclass of Circle
2public class Cylinder extends Circle {
3 private double height; // Private member variable
4
5 public Cylinder() { // constructor 1
6 super(); // invoke superclass' constructor Circle()
7 height = 1.0;
8 }
9 public Cylinder(double radius, double height) { // Constructor 2
10 super(radius); // invoke superclass' constructor Circle(radius)
11 this.height = height;
12 }
13
14 public double getHeight() {
15 return height;
16 }
17 public void setHeight(double height) {
18 this.height = height;
19 }
20 public double getVolume() {
21 return getArea()*height; // Use Circle's getArea()
22 }
23}
Keep the "Cylinder.java" and "TestCylinder.java" in the same directory as "Circle.class" (because we
are reusing the class Circle). Compile and run the program. The expected output is as follows:
Radius is 1.0 Height is 1.0 Color is red Base area is 3.141592653589793 Volume is
3.141592653589793
Radius is 5.0 Height is 2.0 Color is red Base area is 78.53981633974483 Volume is
157.07963267948966
1.2 Exercise -
Compile and Execute the following code by completing it as per commented specification
given. Write the whole code in file
Ex3Test.java
class A { public int a =100; } // End of class A
class B extends A { public int a =80; } // End of class B
class C extends B { public int a =60; } // End of class C
class D extends C { public int a =40; } // End of class D
// NOTE : The variable named ‘a’ used in above classes is the instance field of each class
class E extends D{
public int a =10;
public void show(){
int a =0;
// Write Java statements to display the values of
// all a’s used in this file on System.out
} // End of show() Method
}// End of class E
class Ex3Test{
public static void main(String args[]){
new E().show(); // This is an example of anonymous object
A a1 = new E();
D d1 = (D) a1; // what’s wrong with this statement?
}// End of main()
}// End of class EX3Test
2. Polymorphism
Polymorphism means - One name many form.
Two ways by which java implements Polymorphism:
Compile time: Overloading. (The discussion on polymorphism in the class pertains here)
Run time: Overriding.
double volume() {
return length*breadth*height;
}
}
// Demonstrating the use of Overloaded constructors
class OverloadConstructors{
public static void main(String args[]){
Room a=new Room(20,30,40);
Room b=new Room();
Room c=new Room(10);
double vol;
vol=a.volume();
System.out.println("Volume of room a is " + vol);
vol=b.volume();
System.out.println("Volume of room b is " + vol);
vol=c.volume();
System.out.println("Volume of room c is " + vol);
}
}
Suppose that our program uses many kinds of shapes, such as triangle, rectangle and so on. We should design a
superclass called Shape, which defines the public interface (or behaviors) of all the shapes. For example, we
would like all the shapes to have a method called getArea(), which returns the area of that particular shape.
The Shape class can be written as follow.
Shape.java
// Define superclass Shape
public class Shape {
// Private member variable
private String color;
// Constructor
public Shape (String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape of color=\"" + color + "\"";
}
We can then derive subclasses, such as Triangle and Rectangle, from the superclass Shape.
Rectangle.java
// Define Rectangle, subclass of Shape
public class Rectangle extends Shape {
// Private member variables
private int length;
private int width;
// Constructor
public Rectangle(String color, int length, int width) {
super(color);
this.length = length;
this.width = width;
}
@Override
public String toString() {
return "Rectangle of length=" + length + " and width=" + width + ", subclass of
" + super.toString();}
@Override
public double getArea() { return length*width; }
}
Triangle.java
// Define Triangle, subclass of Shape
public class Triangle extends Shape {
// Private member variables
private int base;
private int height;
// Constructor
public Triangle(String color, int base, int height) {
super(color);
this.base = base;
this.height = height;
}
@Override
public String toString() {
return "Triangle of base=" + base + " and height=" + height + ", subclass of "
+ super.toString();
}
@Override
public double getArea() {return 0.5*base*height;}
}
The subclasses override the getArea() method inherited from the superclass, and provide the proper
implementations for getArea().
TestShape.java
In our application, we could create references of Shape, and assigned them instances of subclasses, as follows:
// A test driver program for Shape and its subclasses
public class TestShape {
public static void main(String[] args) {
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Shape s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
}
}
2.3 Overriding the toString():
/**
* Java program to demonstrate How to override toString() method in Java.
* This Java program shows How can you use IDE like Netbeans or Eclipse
* override toString in Java.
*/
@Override
public String toString() {
return "Country [name="+name + "capital=" + capital + ",
population=" + population + “]”;
}
2.4 Exercise –
Make a class Employee with attributes
– name:String
– salary: double.
This class supplies
(i) A parameterized constructor
(ii) Accessor and Mutator method(s) for every instance field and
(iii) toString() method which returns the values of instance fields by adding proper heading labels
and spaces.
Make a class Manager that inherits from Employee and add an instance field named –department:
String. This class also supplies parameterized constructor, accessor, and mutator methods and a
toString() method that returns the manager's name, department, and salary by adding proper labels
and spaces.
The complete UML class diagram representation for these classes is shown below:
Employee
- name : String
- salary : double
Manager
-dept:String
Parametrized constructor
Accessor methods, Mutator Methods
+toString() : String
// Constructor
public Shape (String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape of color=\"" + color + "\"";
}
Now create instances of the subclasses such as Triangle and Rectangle (Classes which we used
previously), and upcast them to Shape , (you cannot create instance of Shape).
1. Write the java implementations for classes Worker, HourlyWorker and FullTimeWorker
2. Write a Driver code in the same file TestWorker.java which demonstrates late binding.
Figure-1
4. Reflection :
Reflection is a powerful feature in Java that allows a program to inspect and modify its own structure at runtime.
Using Reflection, you can:
● Obtain the Class Object: Every Java class has a Class object associated with it, which provides
access to the class structure. You can obtain it in the following ways:
○ Using ClassName.class.
○ Using Object.getClass().
○ Using Class.forName("className") (useful for loading classes dynamically).
● Access Class Information: Once you have the Class object, you can inspect the class for fields,
methods, constructors, etc.
● Modify and Invoke: Using Reflection, you can modify fields (even private ones) and invoke
methods.
4.4. Example 1: Inspecting Fields and Methods of a Class:
Task: Write a program that uses Reflection to inspect the fields and methods of a class.
Code Example 1
// Save this as ReflectionExample1.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Person {
private String name;
private int age;
public Person(String name, int age)
{ this.name = name;
this.age = age;
}
public void greet() {
System.out.println("Hello, my name is " + name);
}
}
} catch (Exception e)
{ e.printStackTrace();
}
}
}
4.5. Example 2: Modifying Private Fields
Code Example 2:
import java.lang.reflect.Field;
class Employee {
private String name;
private double salary;
} catch (Exception e)
{ e.printStackTrace();
}
}
}
RetailStore.java
PublicclassRetailStore {
privateint[] itemId = {1001,1002,1003,1004,1005};
privatedouble[] price = {13.50, 18.00, 19.50, 25.50};
privatedoublecomputePrice(int value) {
// method to compute the price of the item.
// it returns the price
for (inti = 0; i<price.length; ++i) {
// note the use of price.length.
// it gives the length of the array
if (itemId[i] == value) {
returnprice[i];
}
}
1.1 Exercise -
Uncomment the last lines in the above code and see the output
Is there any error or runtime exception? [
Why compiler is not showing the error?.(hint:- you can check If the value passed in the
computePrice() method exists in the itemId array. In java there is no array bound checking. So
you have to be very careful while accessing the elements in an array. This runtime exception can
be avoided by ensuring that the array element to be accessed is already initialized)
2. Strings, StringBufffer and StringTokenizer.
class String
java.lang.String
The String class represents character strings. All string literals in Java programs, such as "abc",
are implemented as instances of this class. Strings are constant; their values cannot be changed
after they are created. String buffers support mutable strings. Because String objects are
immutable they can be shared. [You can refer to lecture slides or java API docs for more
details on String class, its constructors and methods]
class StringBufffer
java.lang.StringBuffer
A string buffer is like a String, but can be modified (mutable). At any point in time it contains
some particular sequence of characters, but the length and content of the sequence can be
changed through certain method calls. [Refer to lecture notes or java API docs for more
details on StringBuffer class, its constructors, and methods]
StringTokenizer
java.util.StringTokenizer
To use this class you have to import java.util.StringTokenizer. The string tokenizer class
allows an application to break a string into tokens. The StringTokenizer methods do not
distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip
comments. The set of delimiters (the characters that separate tokens) can be specified at the time
of instantiation. A token is returned by taking a substring of the string that was used to create
the StringTokenizer object. StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. [Refer to lecture notes or java API
docs for more details on StringBuffer class, its constructors, and methods]
2.1 Exercise -
You are given the skeleton code for four incomplete classes named Name, Student, StudentList
and a driver class named Test. You have to complete the code for all the classes as per the
following specifications:
(a) class Name: Name class encapsulates three attributes of a person.name such as firstname,
middle name and last name. This class supplies only one constructor which receives a string
value and this string value contains the values for all the three attributes either in comma (,) or
semicolon (;) separated format.
If the values are comma separated then the three attribute values are in the following order:
<First name>,<Middle Name>,<Last Name>
If the values are semicolon separated then the three attribute values are in the following order:
<Last name>;<Middle Name>;<First Name>
For example: If the value supplied for constructor parameter is “Rajesh,Kumar,Khanna” the
Firstname is “Rajesh”, Middle Name is “Kumar” and Last name is “Khanna” . If the value
supplied for constructor parameter is “Khanna;Kumar;Rajesh” then Last name is “Khanna”,
Middle name is “Kumar” and First name is “Rajesh”. [Assume stringparameter for constructor
either contains comma or semicolon in its value but not both. There is no need to check for
validity of the string parameter.]The Name class supplies accessor methods for every instance
field. The class also supplies a method getName() for retrieving the full name of a person. The
getName() method returns the fullname after concatenating and adding spaces between first
name, middle name and lastname fields in order. The class also supplies toString() method
which returns value after simply concatenating the values of first name, middle name and last
name fields.
class Name {
private String fname; // First Name
private String mname; // Middle Name
private String lname; // Last Name
// provide accessor methods as per the given specification
// provide implementation for getName() method as per the given
// specification
Name(String name) {
/* Complete the constructor by extracting the values of three name
fields. Note that name value may be either comma separated or
semicolon separated */
// Write Your Code Here
}
} // End of class Name.
(b) class Student: Student class has two attributes: name of type Name[note that Name is class
as mentioned above] and age of type int. The class supplies only one parameterized constructor
which receives the values for all instance fields of the class as parameters. First parameter is of
Name type and second is of type int. The class supplies accessor method for every instance field
and toString() method which returns a string after concatenating and adding spaces between
values of first name , middle name , lastname and age attributes for this instance. Provide the
implementation for the class “Student” as mentioned below as per the specification given
above.
class Student {
private Name name; // name of student
private int age;// age of student
/* Complete the Student class by adding proper constructor, accessor methods and
by adding any other method which are required as per specification */
// Write Your Code From Here
}// End of Student class
(c) class StudentList: This class encapsulates the list of size 10 of type Student. This class
contains only static fields and methods. The list of students is maintained as an array of type
Student[]. The skeleton code is given as follows:
class StudentList {
publicstaticvoidaddStudent(Student std) {
if(count>= 20) return; // if count is already 20 or more then return
list[count] = std;
count++;
}
(d) class Test: This class is the driver class. The incomplete code for the class is given below.
You have to complete methods readStudent() and main() of this class as per commented
specification.
cclass Test{
lpublic static Student readStudent() throws IOException{
a/* This method reads the student details and returns the Student instance.
sValues to be read from System.in are:
s1. First name of Student, 2. Middle name of student, 3. Last name of
Student, 4. Name format (1 for comma(,) separated and 2 for semicolon
Sseparated), 5. age of student
t*/
u} // End of readStudent() Method
dpublic static void main(String args[]) throws IOException{
e/* 1. Write java code for reading details of 10 students and add them
nin the static list ofStudentListclass.*/
t/* 2. Write java code for displaying the all the students with age 20 from
static list field of StudentList class*/
/* 3. Write java code for displaying the student details for all students
having last name “Sharma” from static list of StudentList class*/
/* 4. Write java code for displaying all the students whose age falls in
the range minAge = 16 and maxAge = 20 from static list of StudentList
class*/
}// End of main() Method
}// End of Test class
3. Two dimensional Array
For declaring 2 dimensional arrays there are many types of syntax available. Will show a set of
examples and you can try this code. Please note the various types of initialization syntax used below.
Example 2
TwoDExample.java
public class TwoDExample {
public static void main(String[] args) {
// main method
int[][] multi = new int[5][10];
// most commonly used way of initializing
int[][] multi1 = new int[][] {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
multi3[0] = newint[10];
multi3[1] = newint[10];
multi3[2] = newint[10];
multi3[3] = newint[10];
multi3[4] = newint[10];
/* using this above method the arrays are initialized only by mentioning
the row numbers first */
// note you can use nested for loop for printing the array
}
}
Example 3
The source code of above Example1 (RetailStore) is modified to include a new variable called
ItemName. Also note the use of constructor in the new code which is more suiting real world
scenario. Compare the codes and identify the difference in both.
Now create a new class RetailStoreExample which extends the RetailStoreClass. Remember that
the child class will be able to access the parent class’s members which are public and protected.
The detailed code is available below. Now run the RetailStoreExample class (Remember that
execution always starts from main method)
Also this new example covers the use of various Methods belonging to the classes String,
StringBuffer and StringTokenizer.
RetailStore.java
public class RetailStore {
private int[] itemId;
private double[] price;
private String itemName[];
}
return price[value];
}
}
return null;
}
}
RetailStoreExample.java
public class RetailStoreExample extends RetailStore {
String stringFromDouble =
Double.toString(newRetailStore().computePrice(1004));
System.out.println("the price of the item computed using double.toString
method is "+ stringFromDouble);
}
}
3.1 Exercise –
Include lines of code in the above program to compare the Strings stringFromDouble and
stringFromSubstring . We are required to show that both the Strings are representing the same
value. Use substring method and String comparison method (String.equals) and show that both
the strings represent the same value.
3.2 Exercise –
(A) Consider a class named ‘Address’ which encapsulates the address of any particular person
having attributes as:
– line1 : String
– line2 : String
– line3 : String
–city : char[]
–state : char[]
– pin : String .
The class supplies only one parameterized constructor which receives only one parameter of type
String which embeds the values of all the attributes in $ separated form as per following format:
“line1$line2$line3$city$state$pin”
$ Character is used as a separator to separate the values of line1, line2, line3, city, state and pin
attributes. The class supplies accessor methods for every instance field. All accessor methods
return only String type value. Implement the Address class in java as per mentioned
specification.
(b) Considering the availability of the code of class Address of (A) in this question, complete the
implementation of the following class named ‘AddressList’ as per commented specification
given below
class AddressList{
public static int countAddressWithCity(Adress[] addressList, String city){
/*This method returns the count of the addresses from addressList which have the city
attribute equals to city parameter passed for this method. If the length of any
passed argument is zero or value of any passed argument is null then it returns -1.*/
}// End of method countAddressWithCity()
public static int countAddressWithPin(Adress[] addressList, String strP){
/*This method returns the count of the addresses from addressList which have the pin
attribute starting with strP parameter passed for this method. If the length of any
passed argument is zero or value of any passed argument is null then it returns -1.*/
}// End of method countAddressWithCity()
public static Address[] getAddressWithCity(Adress[] addressList, String city){
/*This method returns all the addresses from addressList by storing them in String[]
which have the city attribute equals to city parameter passed for this method. If the
length of any passed argument is zeroor value of any passed argument is null th en it
returns null. If addressList does not contain any address with city attribute value
equal to city parameter passed for this method even then it returns null.*/
}// End of method getAddressWithCity()
public static Address[] getAddressWithPin(Adress[] addressList, String strP){
/*This method returns all the addresses from addressList by storing them in String[]
which have their pin attribute starting with strP parameter passed for this method.
If the length of any passed argument is zero or value of any passed argument is null
then it returns null. If addressList does not contain any address whose pins
attribute value starts with strP parameter passed for this method even then it
returns null.*/
}// End of method getAddressWithCity()
}// End of class AddressList
(c) Write a suitable driver class named Test for a class named ‘AddressList’ and test the behavior of
all the method.
4. Ragged (Jagged) Arrays
A ragged (or jagged) array is an array of arrays, where the inner arrays can have different
lengths. This is different from a typical 2D array where each row has the same number of
columns.
For example:
123
456
789
In Java, ragged arrays are declared as an array of arrays. The syntax is:
This creates a 2D array with ‘numOfRows’ rows, in which the number of columns in each
row is defined independently. Here the datatype is the data type of elements in array,
numOfRows is the number of rows in the array and there are total of N columns in this array.
Each row is initialized to null by default.
Here is an example program that demonstrates how to declare a ragged array, assign values to
it, and print its contents using nested loops.
With Java 8 streams, you can create and initialize a jagged array in a single line using the
Arrays.stream and toArray methods like this:
Here, we make a three-row jagged array with two elements in the first row, three in the
second row, and four in the third row. The Arrays.stream method converts each one-
dimensional array into a stream of integers, and then the toArray method collects the stream
into a jagged array.
Jagged arrays have several advantages over multidimensional arrays with a fixed size:
2. Flexibility: Ragged arrays are more flexible than multidimensional arrays because
they can have different sizes for each row. Ragged arrays enable the representation of
non-rectangular or irregular data structures.
3. More natural representation of data: In some cases, ragged arrays may be a more
natural representation of data than rectangular arrays. For example, when working
with irregularly shaped data such as geographic maps, a ragged array can be a more
intuitive way to represent the data.
Write a java program to take user input in an integer ragged array using nested loops.
4.2 Exercise:
2. Assign Values:
o Assign values to each element of the array (you can choose any values).
o Write a method int sumRaggedArray(int[][] array) that takes the ragged array
as input and returns the sum of all the elements.
1234
567
89
10
Tips: