0% found this document useful (0 votes)
28 views67 pages

Lab1 6

This document provides an introduction to the Eclipse IDE, covering installation, user interface overview, and creating a simple Java program. It includes step-by-step instructions for setting up a Java project, creating classes, and running Java code, along with examples of command line arguments. Additionally, it outlines exercises for practicing Java programming concepts.

Uploaded by

vibhorbarguje2nd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views67 pages

Lab1 6

This document provides an introduction to the Eclipse IDE, covering installation, user interface overview, and creating a simple Java program. It includes step-by-step instructions for setting up a Java project, creating classes, and running Java code, along with examples of command line arguments. Additionally, it outlines exercises for practicing Java programming concepts.

Uploaded by

vibhorbarguje2nd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE, PILANI

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.

2.2 Start Eclipse

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

Figure-1: Workspace Launcher


Eclipse will start and show the Welcome screen [see Figure-2 given below].

Figure-2: Eclipse Welcome Screen

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

3.3. Views and Editors


A view is typically used to navigate a hierarchy of information or to open an editor. Changes in a view
are directly applied.Editors are used to modify elements. Editors can have code completion,
undo/redo, etc. To apply the changes in an editor to the underlyingresources, e.g. Java source file, you
usually have to save.

4. Create your first Java program


The following will describe how to create a minimal Java program using Eclipse. It will be the
classical "Hello World" program. Our program willwrite "Hello Eclipse!" to the console.

4.1. Create project


Select from the menu File -> New-> Java project. Maintain "oop.eclipse.ide.first" as the project name
and press the next button [See Figure-3 below].

Figure-3: Create New Java Project

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

4.3. Create Java class

Right click on src and select New -> Class [See Figure-5 below]

Figure-5: Create a Java class

Create MyFirstClass, select the flag "public static void main (String[]args)" [See
Figure-6 below].
Figure-6: Specify Class Name

Maintain the following code.

Figure-7: Your first java program

Include the following statement in the “main” method:

System.out.println(“Hello Eclipse”);

4.4. Run your project in 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

Figure-9: Finished! You should see the output in the console

5. Java Examples

Example-1(a): Compilation and Execution of java code from command prompt

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.

1. Go to D Drive, create a new Text Document and name it Bicycle.java


2. Type the following code in this file and save the file:

/* Bicycle class */
class Bicycle {

int speed=100;
intnoOfGears=5;
int cadence=40;
publicvoidprintState() {
System.out.println("Bicycle [cadence=" + cadence +
", noOfGears=" + noOfGears+ ", speed=" + speed +
"]");
}

publicstaticvoid main(String[] args) {

/*create instance of Bicycle class */


Bicycle b1 = new Bicycle();

/*Invoke method object b1 of type Bicycle*/


b1.printState();

}
}
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]

Example-1(b): Compilation and Execution of java code with Eclipse IDE

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.

Example-2: Command Line Arguments (From command prompt) –

1. Go to D Drive, create a new Text Document and name it CommandLine Arg1.java

2. Type the following code in this file and save the file:

/* This program expects some string as command line arguments ,


then it simply outputs the command line arguments to the
console*/

class CommandLineArg1 {
publicstaticvoid main(String[] args) {
for(inti=0; i<args.length; i++){
System.out.println("args["+ i +"] =" + args[i]);
}
}
}

3. Execute the following command


D:\>javac CommandLine Arg1.java[This command compiles the java code]
4. Execute the following command
D:\> java CommandLine Arg1 My First Command Line Program in Java
This command executes your java program, the whole string “My First Command Line Program
in Java”, goes as command line arguments to your java program.

Example 3: Write one more program [as given below], compile and execute it from command
prompt.

/* This program takes 10 integer arguments as an input from


command line, parse the command line arguments to integers,
finds the sum of these 10 numbers and print the sum */

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

Example-4: Command Line Arguments from Eclipse IDE–

1. Create a java class file named CommandLineArguments in your workspace [Code given below].

/* This program takes 10 integer arguments as an input from


command line, parse the command line arguments to integers,
finds the sum of these 10 numbers and print the sum */

public class CommandLineArg2 {


public static void main(String[] args) {
int sum = 0;
for(inti=0; i<args.length; i++){
sum += Integer.parseInt(args[i]);
}
System.out.println("Sum = " + sum);
}
}

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

Run the program and watch the output in the console.

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:

public class HarmonicSum{ // saved as "HarmonicSum.java"


public static void main (String[] args) {
int maxDenominator = 50000;
double sumL2R = 0.0; // sum from left-to-right
double sumR2L = 0.0; // sum from right-to-left

// for-loop for summing from left-to-right


for (int denominator = 1;
denominator <= maxDenominator;
denominator++) {
......
// Beware that int/int gives int.
}
// for-loop for summing from right-to-left
......
// Find the difference and display
......
}//end of main
}//end of HarmonicSum
********* END OF LAB-1 **********
BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE, PILANI
CS F213
LAB-2 [Class Design Basics - Part-1]
DATE: 18/01/2025 TIME: 02 Hours
1. How to read user inputs in a typical java application?
1.1. Use BufferedReaderclass (See Example1.java and Exercise1.java)
1.2. Use Scanner class (See Example2.java and Exercise2.java)
2. How to design a simple class with proper Attribute(s) and Method(s).

Blue colored lines are to be added to your code for reading


user input from the keyboard they will be explained later,
for the purpose of this lab just remember to add these
lines.

1. How to read user inputs in a typical java application?


There are two ways how you can read user inputs from the keyboard (referred by stdin in
C and System.in in Java).First method is by using the instance of BufferedReader class
and the second method is by using the instance of Scanner class.

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.

import java.io.*; // java.io package is imported


// for using BufferedReaderclass
class Example1{

public static void main(String args[])throws IOException{


/* instantiate InputStreamReader class and pass
System.in to its constructor */
InputStreamReader isr =
new InputStreamReader(System.in);
/* instantiate BufferedReader class and pass the
reference variable isrwhich id of type
InputStreamReader created in the previous lineto the
constructor of BufferedReader */

BufferedReaderbr= new BufferedReader(isr) ;

System.out.println("Enter Your First Name: ");

/* call readLine method on brreference variable which


is of type BufferedReader */
String name = br.readLine();
System.out.println("Yourname is: " + name);
} // End of main
}// End of class Example1

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;

/* instantiate scanner class by passing System.in


to its constructor */
Scanner in = new Scanner(System.in);

System.out.println("Enter an integer: ");


num1 = in.nextInt(); //reads an int from keyboard
System.out.println("You entered: " + num1);

System.out.println("Enter a double: ");


double1=in.nextDouble();//reads an int from keyboard
System.out.println("You entered: " + double1);

System.out.println("Enter your first name ");


numStr1 = in.next();
System.out.println("Your name is " + numStr1);

System.out.println("Enter your surname");


numStr2 = in.nextLine();
System.out.println("Your surname is " + numStr2);

}// End of main() method


}// End of class Example2

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. Class Design Basics

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.

2.3 Write a Test class named TestStore.java which


a) Creates one Customer instance. [You can assume any value for name, idNo and
balance fields]
b) Creates any two Item instances. [You can assume any value for ItemName, ItemidNo,
ItemQuantity and ItemPrice fields]
c) Display the details of the Items ordered by the customer and customer balance after
order.

Note: Assume only one item (any number of quantities) can be ordered at a time by
the customer.

Exercises3: Write the java implementation for a class named ‘TaxOnSalary’ to


calculate tax on salary. The class TaxOnSalary is described as follows:

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.

2.3 Write a Test class named TestTax.java which


a) Creates two instances of tax1 and tax2 of the class TaxOnSalary with different
initializations [see point (i) in the description of Methods].
b) Takes salary as an input from the user [using keyboard] for both the instances tax1
and tax2.
c) Calculate and display tax for both the instance tax1 and tax2.
BIRLA INSTITIUTE OF TECHNOLOGY AND SCIENCE, PILANI CS F213 LAB-3
[JUnit Basics - Part-1]
DATE: 25/01/2025 TIME: 02 Hours

JUnit Installation:

Step 1) Visit https://junit.org/junit4/ and click Download and Install JUnit 4.

Step 2) Click junit.jar

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

Step 5) Download the 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

JUnit Environment Setup

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.

JUnit - Plug with Eclipse


Step 1: Download JUnit Archive

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.

Step 2: Set Eclipse Environment


Open eclipse → right click on project and click on property > Build Path > Configure Build
Path and add the junit-4.10.jar in the libraries using the button Add External Jar.

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:

Create a java class file name TestJunit in C:\>JUNIT_WORKSPACE

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class TestJunit {


@Test
public void testAdd() {
String str = "Junit is working fine";
assertEquals("Junit is working fine",str);
}
}

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;

public class TestRunner {


public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);

for (Failure failure : result.getFailures()) {


System.out.println(failure.toString());
}

System.out.println(result.wasSuccessful());
}
}

Run the following commands using javac:


C:\JUNIT_WORKSPACE>javac TestJunit.java TestRunner.java
C:\JUNIT_WORKSPACE>java TestRunner

Output displayed will be “true”.


JUnit is an open-source testing framework for java programmers. The java programmer can
create test cases and test his/her own code. It is one of the unit testing framework.
To perform unit testing, we need to create test cases. The unit test case is a code which ensures
that the program logic works as expected. The org.junit package contains many interfaces and
classes for junit testing such as Assert, Test, Before, After etc.

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.

Basic Usage of JUnit

Create a java class to be tested, say, Message.java in C:\>JUNIT_WORKSPACE

public class Message {


private String message;
public Message(String message){
this.message = message;
}
public String printMessage(){
System.out.println(message);
return message;
}
}

Creating a Test Case:

Create a java class file name TestJunit.java in C:\>JUNIT_WORKSPACE.

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());
}
}

Create Test Runner Class


Create a java class file named TestRunner.java 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;

public class TestRunner {


public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}

Compile the MessageUtil, Test case and Test Runner classes using javac.

C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.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

Verify the output:


Hello World
true

Exercise: Update TestJunit in C:\>JUNIT_WORKSPACE so that the test fails.

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

Methods of Assert class

The common methods of Assert class are as follows:

1. void assertEquals(boolean expected,boolean actual): checks that two


primitives/objects are equal. It is overloaded.
2. void assertTrue(boolean condition): checks that a condition is true.
3. void assertFalse(boolean condition): checks that a condition is false.
4. void assertNull(Object obj): checks that object is null.
5. void assertNotNull(Object obj): checks that object is not null.

You need to load junit4.jar and hamcrest-core.jar files (http://shorturl.at/fuJMX)

Create a java class file named TestAssertions.java in C:\>JUNIT_WORKSPACE.

import org.junit.Test;
import static org.junit.Assert.*;

public class TestAssertions {

@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;

String[] expectedArray = {"one", "two", "three"};


String[] resultArray = {"one", "two", "three"};
assertEquals(str1, str2);
assertTrue (val1 < val2);
assertFalse(val1 > val2);
assertNotNull(str1);
assertNull(str3);
assertSame(str4,str5);
assertNotSame(str1,str3);
assertArrayEquals(expectedArray, resultArray);
}
}

Now, create a java class file named TestRunner.java 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;

public class TestRunner2 {


public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestAssertions.class);

for (Failure failure : result.getFailures()) {


System.out.println(failure.toString());
}

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

Verify the output.


true

Annotations for Junit testing

The Junit 4.x framework is annotation based, so let's see the annotations that can be used while
writing the test cases.

@Test annotation specifies that method is the test method.

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

Example: Using Annotations.


Create a java class file named JunitAnnotation.java in C:\>JUNIT_WORKSPACE to test
annotation.

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class JunitAnnotation {

//execute before class


@BeforeClass
public static void beforeClass() {
System.out.println("in before class");
}

//execute after class


@AfterClass
public static void afterClass() {
System.out.println("in after class");
}

//execute before test


@Before
public void before() {
System.out.println("in before");
}

//execute after test


@After
public void after() {
System.out.println("in after");
}

//test case
@Test
public void test() {
System.out.println("in test");
}

//test case ignore and will not execute


@Ignore
public void ignoreTest() {
System.out.println("in ignore test");
}
}
Next, create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to
execute annotations.

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {


public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitAnnotation.class);

for (Failure failure : result.getFailures()) {


System.out.println(failure.toString());
}

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

Verify the output.


in before class
in before
in test
in after
in after class
true
BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE, PILANI
CS F213
LAB-4 [Class Design Basics - Part-2]
AGENDA DATE: 01/02/2025 TIME: 02 Hours
1. static variables, methods and static blocks
2. Objects as parameter to methods
3. Wrapper classes

1. static variables, methods and static blocks -

1.1 static variables -


a) It is a variable which belongs to the class and not to an object (instance).
b) Static variables are initialized only once, at the start of the execution. These variables will be
initialized first, before the initialization of any instance variables.
c) A single copy is shared by all instances of the class.
d) A static variable can be accessed directly by the class name and doesn’t need any object.
e) Syntax: <class-name>.<variable-name>; for example Math.PI;

1.2 static method


a) It is a method which belongs to the class and not to the object (instance).
b) A static method can access only static data. It cannot access non-static data (instance variables).
WHY?
c) A static method can call only other static methods and cannot call a non-static method from it.
WHY?
d) A static method can be accessed directly by the class name and doesn’t need any object.
e) Syntax: <class-name>.<method-name>;
f) A static method cannot refer to “this” or “super” keywords in anyway. WHY?

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.

Example-1: static variables & methods

1. class MyStatic {

2. int a; //initialized to zero


3. static int b; /*initialized to zero only when class is
loaded not for each object created.*/

4. //Constructor incrementing static variable b


5. MyStatic (){ b++; }
6. public void showData(){
7. System.out.println("Value of a = "+a);
8. System.out.println("Value of b = "+b);
9. }
10.
11. //public static void increment(){
12. //a++;
13. //}
14. }

15. class StaticDemo{


16. public static void main(String args[]){
17. MyStatic s1 = new MyStatic ();
18. s1.showData();
19. MyStatic s2 = new MyStatic ();
20. s2.showData();
21. // MyStatic.b++;
22. //s1.showData();
23. }
24. }

Run the StaticDemo class and observe the output.

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.

Example-2: Demo of static blocks

public class StaticExample{

static {
System.out.println("This is first static block");
}

public StaticExample(){
System.out.println("This is constructor");
}

public static String staticString = "Static Variable";

static {
System.out.println("This is second static block and "
+ staticString);
}

public static void main(String[] args){


StaticExample statEx = new StaticExample();
StaticExample.staticMethod2();
}

static {
staticMethod();
System.out.println("This is third static block");
}
public static void staticMethod() {
System.out.println("This is static method");
}

public static void staticMethod2() {


System.out.println("This is static method2");
}
}

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.

Example-3: Demo of constructor blocks

public class ConstructorBlockExample{

{ System.out.println("This is first constructor block"); }

public ConstructorBlockExample(){
System.out.println("This is no parameter constructor");
}

public ConstructorBlockExample(String param1){


System.out.println("This is single parameter
constructor");
}

{System.out.println("This is second constructor block");}

public static void main(String[] args){


ConstructorBlockExample constrBlockEx =
new ConstructorBlockExample();
ConstructorBlockExample constrBlockEx1 =
new ConstructorBlockExample("param1");
}
}
Run the code and observe the output.

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();

private static varType initializeClassVariable() {


//initialization code goes here
}
}

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

Advantages of static blocks


 If you need to do computation in order to initialize your static variables, you can declare a static
block which gets executed exactly once, when the class is first loaded.

Disadvantages for static blocks


 There is a limitation of JVM that a static initialization block should not exceed 64K.
 You cannot throw Checked Exceptions. (will be discussed later)
 You cannot use this keyword since there is no instance.
 You shouldn’t try to access super since there is no such a thing for static blocks.
 You should not return anything from this block.
 Static blocks make testing a nightmare.

Example-4: alternate use of static blocks

public class StaticBlock {

static int[] values = initializeArray(10);

private static int[] initializeArray(int N) {


int[] arr = new int[N];
for (int i = 0; i <arr.length; i++) {
arr [i] = i;
}
}
void listValues() {
for (int value : values) {
System.out.println(value);
}
}

public static void main(String[] args) {


StaticBlock example = new StaticBlock();
System.out.println("\nFirst object:");
example.listValues();

example = new StaticBlock();


System.out.println("\nSecond object:");
example.listValues();
}

Example-5 Consider the class Circle. It has methods to compute the radius and circumference of
a circle.

public class Circle{

static double PI; /* variables PI is a class variable, it


is not instance specific */
private double radius;

//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;}

//method to find the area


public double area() {return(PI * radius * radius);}

//static method's are not instance specific


public static void getCircumference(double radius) {
// here radius variable is a local variable
System.out.println("Circumference = " + 2 * PI * radius);
}
}// End of circle
class TestCircle{
public static void main(String args[]) {

Circle c1 = new Circle(2.3);


c1.area();

// accessing static method with class name


Circle.getCircumference(2.3);

Circle c2 = new Circle(3.45);


c2.area();
// accessing static method with references is discouraged
c2.getCircumference (3.45);

/* 1. Make the area function as static and observe the


output
2. Remove the formal argument from getCircumference()
method and observe the output
3. Rename static to final and observe the error(s) and
correctthem */
} // end of main
} // end of class

2. Objects as parameters to methods

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.

Example-6: Object as parameter to a method

public class Point{

private double x; // Instance field x-coordinate


private double y; // Instance field y-coordinate

Point(double x, double y){ this.x=x;this.y=y; }


public double getX() { return this.x; }
public double getY() { return this.y; }
public void setX(double x) { this.x = x; }
public void setY(double y) { this.y = y; }

public String toString() { return “X=”+x+” Y =”+y; }

public static void changeState(Point other){


other.setX(-20); // Here you can write other.z = 20 also
// because this code is inside the class
other.setY(-20); // Here you can write other.z = 20 also
// because this code is inside the class
// Note that changeState Method changing the state of the Passed
// object by using the same reference
// So this change in state will be reflected in caller method
// also
}

public static void changeReference(Point other){


Point other = new Point(-20,-20); // Will this change be
// reflected in caller method
// Note that this Method has changed the reference from
// incoming Point object to some other Point object
// So this change will not be reflected in caller method.
}

} // End of class Point

public class PointTest{


public static void main(String args[]){

// 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

} // End of Method main()


} // End of class PointTest
Example-7: Object as parameter to a method

public class BOX{


private double length, width, height; // Instance Fields

BOX(double l,double b,double h){ // Constructor Method


length = l; width = b; height =h;
}

// Mutator methods for Length, Width and Height


public void setLength(double l) { length = l;}
public void setWidth(double b) { width = b;}
public void setHeight(double h) { height = h;}

// Accessor Methods for Length, Width and Height


public double getLength() { return length;}
public double getWidth() { return width; }
public double getHeight() { return height;}

public String toString() {


return "Length:"+length+" Width:"+width+" Height:"+height; }

public double area() {


return 2 * (length * width + width*height +
height*length);
}

public double volume() { return length*width*height;}

public static void swapBoxes(BOX b1, BOX b2) {


BOX temp = b1; b1 = b2; b2 = temp;
}

}// End of BOX

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,

In Java, you define a subclass using the keyword "extends", e.g.,

class Cylinder extends Circle { ..... }


class Goalkeeper extends SoccerPlayer {...... }

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.

The Source code as follows:

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}

A Test Drive Program: TestCylinder.java


1// A test driver program for Cylinder class
2public class TestCylinder {
3 public static void main(String[] args) {
4 Cylinder cy1 = new Cylinder(); // Use constructor 1
5 System.out.println("Radius is " + cy1.getRadius()
6 + " Height is " + cy1.getHeight()
7 + " Color is " + cy1.getColor()
8 + " Base area is " + cy1.getArea()
9 + " Volume is " + cy1.getVolume());
10 Cylinder cy2 = new Cylinder(5.0, 2.0); // Use constructor 2
11 System.out.println("Radius is " + cy2.getRadius()
12 + " Height is " + cy2.getHeight()
13 + " Color is " + cy2.getColor()
14 + " Base area is " + cy2.getArea()
15 + " Volume is " + cy2.getVolume());
16 }
17}

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.

2.1 Method Overloading:


In same class, if name of the method remains common but the number and type of parameters are different,
then it is called method overloading in Java.
Overloaded methods:
 appear in the same class or a subclass
 have the same name but,
 have different parameter lists, and,
 can have different return types
Constructor Overloading:
 Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.
 The compiler differentiates these constructors by taking into account the number of parameters in the list
and their type.

2.1.1 Example for Method Overloading :


class Room{
double length,breadth,height;

Room(){//default construcor for class Room


length=-1;
breadth=-1;
height=-1;
}

//overloading the constructor


//3 Parameterised constructor for the class Room
Room(double l,double b,double h) {
length=l;
breadth=b;
height=h;
}

Room(double len) {// Single parametrised constructor


length=breadth=height=len;
}

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

2.2 Method Overriding:


 applies ONLY to inherited methods is related to polymorphism
 object type (NOT reference variable type) determines which overridden method will be used at runtime
 overriding method MUST have the same argument list (if not, it might be a case of overloading)
 overriding method MUST have the same return type; the exception is covariant return (used as of Java 5)
which returns a type that is a subclass of what is returned by the overridden method
 overriding method MUST NOT have more restrictive access modifier, but MAY have less restrictive one
 overriding method MUST NOT throw new or broader checked exceptions, but MAY throw fewer or
narrower checked exceptions or any unchecked exceptions
 abstract methods MUST be overridden
 final methods CANNOT be overridden
 static methods CANNOT be overridden
 constructors CANNOT be overridden

2.2.1 Example for Method Overriding :

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 + "\"";
}

// All shapes must has a method called getArea()


public double getArea() {
System.err.println("Shape unknown! Cannot compute area!");
return 0; // Need a return to compile the program
}
}

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.
*/

public class Country{


private String name;
private String capital;
private long population;

public Country(String name){


this.name = name;
}

public String getName(){ return name; }


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

public String getCapital() {return capital;}


public void setCapital(String capital) {this.capital = capital;}

public long getPopulation() { return population; }


public void setPopulation(long population) {this.population = population; }

@Override
public String toString() {
return "Country [name="+name + "capital=" + capital + ",
population=" + population + “]”;
}

public static void main(String args[]){


Country India = new Country("India");
India.setCapital("New Delhi");
India.setPopulation(1200000000);
System.out.println(India);
}
}

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

Employee(name : String, salary:double)


+Accessor Methods , + Mutator Methods
+toString() : String

Manager
-dept:String
Parametrized constructor
Accessor methods, Mutator Methods
+toString() : String

You have to write the code as per following description:


1. Write java implementations for classes Employee and Manager.
2. Write a Driver code which creates two Employee and Manager instances each and display their
attribute values on standard output using polymorphism.
3. Abstract Class :
 An abstract method is a method with only signature (i.e., the method name, the list of arguments and the
return type) without implementation (i.e., the method’s body).
 You use the keyword abstract to declare an abstract method.
 A class containing one or more abstract methods is called an abstract class.
 An abstract class must be declared with a class-modifier abstract.

3.1 Example for Abstract Class :


Rewrite the Shape class as an abstract class, containing an abstract method getArea() as
follows:
Shape.java

abstract 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 + "\"";
}

// All Shape subclasses must implement a method called getArea()


abstract public double getArea();
}

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

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());

// Cannot create instance of an abstract class


Shape s3 = new Shape("green");// Compilation Error!!
}}
3.2 Exercise –
Define an abstract class Worker that has a abstract method public double computePay(). Every
worker has a name and a salary_rate. Define two concrete classes FullTimeWorker, and
HourlyWorker. A full time worker gets paid the hourly wage for a maximum of 240 hours in a
month at the rate of Rs. 100/hour. An hourly worker gets paid the hourly wage for the actual number
of hours he has worked at the rate of Rs. 50/hour, he is not allowed to work for more than 60 hours in
a month. The complete UML class diagram is shown in Figure 1.

You have to write the code as per following specification:

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:

● Discover the structure of a class (its fields, methods, constructors, etc.).


● Access private fields and methods.
● Dynamically create objects and invoke methods at runtime.

4.1. Common Use Cases:

● Writing frameworks (like Spring, Hibernate).


● Testing, debugging, and extending libraries without accessing source code.
● Serialization and deserialization (e.g., in JSON or XML frameworks).

4.2. Key Reflection Classes in Java:

● Class<?>: The entry point for using Reflection to inspect a class.


● Field: Used to inspect and modify fields.
● Method: Used to inspect and invoke methods.
● Constructor<?>: Used to inspect and create instances of classes.

These classes are all part of the java.lang.reflect package.

4.3. Steps for Using Reflection:

● 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);
}
}

public class ReflectionExample1 {


public static void main(String[] args)
{ try {
// Obtain the Class object for the Person class Class<?
> personClass = Person.class;

// Print the class name


System.out.println("Class Name: " + personClass.getName());

// Get and print all declared fields (private, public, etc.)


Field[] fields = personClass.getDeclaredFields();
System.out.println("\\nDeclared Fields:");
for (Field field : fields) {
System.out.println(field.getName() + " of type " + field.getType());
}

// Get and print all declared methods


Method[] methods =
personClass.getDeclaredMethods();
System.out.println("\\nDeclared Methods:");
for (Method method : methods)
{ System.out.println(method.getName());
}

} catch (Exception e)
{ e.printStackTrace();
}
}
}
4.5. Example 2: Modifying Private Fields

Task: Modify the private fields of a class using Reflection.

Code Example 2:

// Save this as ReflectionExample2.java

import java.lang.reflect.Field;

class Employee {
private String name;
private double salary;

public Employee(String name, double salary)


{ this.name = name;
this.salary = salary;
}

public void displayInfo() {


System.out.println("Employee Name: " + name + ", Salary: " + salary);
}
}
public class ReflectionExample2 {
public static void main(String[] args)
{ try {
// Create an Employee object
Employee emp = new Employee("John", 50000);

// Display original info


emp.displayInfo();

// Obtain the Class object for the Employee class


Class<?> empClass = emp.getClass();

// Access the private field 'salary'


Field salaryField = empClass.getDeclaredField("salary");

// Set accessible to true to modify the private field


salaryField.setAccessible(true);

// Modify the 'salary' field


salaryField.set(emp, 75000);

// Display modified info


emp.displayInfo();

} catch (Exception e)
{ e.printStackTrace();
}
}
}

4.6. Practical Assignments:

1. Modify the first example to inspect constructors of the Person class.

2. Write a program that dynamically invokes a method using Reflection.


BIRLA INSTITIUTE OF TECHNOLOGY AND SCIENCE, PILANI
CS F213
LAB-6
AGENDA DATE: 21/09/2024 TIME: 02 Hours
ghfhj
1. Understand the concept of Arrays, passing arrays to a method
2. Strings, StringBuffer and StringTokenizer
3. Multi Dimensional Arrays
4. Ragged (Jagged) Arrays
5.
16.Single
What are dimensional
Ragged (Jagged)array
Arrays?and passing an array as parameter
Array concept is similar in javaisand
7. A ragged (or jagged) array an array of arrays,
c in many where
aspects. the inner
Array arrays can of
is a collection have different
homogeneous
8. lengths. This is different from a typical 2D array where each row has the same number of
items. An array object contains a number of variables. The number of variables may be zero, in
9. columns.
which
10. Forcase the array is said to be empty. The variables contained in an array have no names;
example:
instead
11. they are referenced by array access expressions that use non-negative integer index
values.
12. 1 2These
3 variables are called the components of the array. If an array has N components, we
13.N4is5 the
say 6 length of the array; the components of the array are referenced using integer indices
from 0 to9N - 1, inclusive.
14. 7 8
15.
16. 1 2 3
All the components of an array have the same type, called the component type of the array.
17. 4 5
If18.
the6component type of an array is T, then the type of the array itself is written T[].
19. This is useful when the data you need to store doesn&#39;t have a fixed structure across
Let usallconsider
rows. an example where in a retail shop we have various items which are identified by
20.
their item IDs and each of them have an amount associated with it. You have to write a program
to21. Declaring
print a Ragged
the amount Array an item based on the item index.
to purchase
22. In Java, ragged arrays are declared as an array of arrays. The syntax is:
23.
24. This creates a 2D array with ‘numOfRows’ rows, in which the number of columns in each
RetailStore
25. row is defined independently. Here the datatype
- itemId is the data type of elements in array,
:int[]
26. numOfRows is the number of rows -inprice the array
:double[] there are total of N columns in this
and
array. + computePrice(value:int): double
27. Each row is initialized to null by default.
28.Class has two array as variables and one method to compute the price.
The
29. Example: Declaring and Printing a Ragged Array
30. Here&#39;s an example program that demonstrates how to declare a ragged array, assign
values to
31. it, and print its contents using nested loops.
32. datatype[][] raggedArray = new datatype[numOfRows][];
33. arrayName[0] = new datatype[col1];
34. arrayName[1] = new datatype[col2];
35. .
36. .
37. arrayName[numOfRows-1] = new datatype[colN];
38.
39. 1. Create a new Java class named RaggedArray.
40. 2. Define the main method inside the class.
41. 3. Declare a 2-D jagged of integers named raggedArray with 3 rows.
42.
43. Output:
44.
45. Initialization using array literals:
Example 1

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];
}
}

// method which takes in the index and


// returns the price of the item
returnprice[value];
}

publicstaticvoid main(String[] args) {


//main method. Execution begins here
RetailStoreretailOne = newRetailStore();
System.out.println("price of item id 1002 is "
+retailOne.computePrice(1003));
System.out.println("price of item id 1004 is "
+retailOne.computePrice(1004));
/* System.out.println("price of item id 1009 is "
+retailOne.computePrice(1007));*/
/* un-comment the above line and see the output.
* Why there is no compilation error?*/
}
}

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.

The skeleton code for the class “Name” is given below:

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 {

public static Student[] list = new Student[10]; // list of students


public static int count =0; // count of students added in the list

publicstaticvoidaddStudent(Student std) {
if(count>= 20) return; // if count is already 20 or more then return
list[count] = std;
count++;
}

public static Student[] getStudentsWithAge(int age) {


/* This method returns all the students whose age is equal to age
parameter of this method. If no such student is found then it
returns null. */
// Write Your Code From Here
}

public static Student[] getStudentsWithLastName(String lastName) {


/* This method returns all the students whose last name attribute
value matches with lastName parameter of this method. If no such
students is found then it returns null. */
// Write Your Code From Here
}

public static Student[] getStudentsInRange(int minAge, int maxAge) {


/* This method returns all the students whose age falls between minAge
and maxAge (both parameters inclusive) */
// Write Your Code From Here
}
}// End of class StudentList

(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 } };

// above way shows the detailed initialization of array


int[][] mult2 = newint[5][];
for (inti = 0; i< 5; i++) {
mult2[i] = newint[10];
}

// above method shows initializing elements with for loop


int[][] multi3 = newint[5][];

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[];

/* The constructor is used here for the initialization purpose*/


public RetailStore() {
itemId = newint[] { 1001, 1002, 1003, 1004, 1005 };
price = newdouble[] { 950.00, 750.00, 450.00, 350.00, 250.00 };
itemName = newString[] {
"Yonex Tennis Racket-950","Yonex Badminton Racket-750",
"Silvers Badminton Racket-450","Cosco Badminton shuttle-350",
"Cosco Tennis Racket-250"
};
}

protected double computePrice(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) {
return price[i];
}

}
return price[value];
}

protected String fetchDescription(int value) {


// method to compute the description of the item. it returns the
// description
for (inti = 0; i<price.length; ++i) {
// note the use of price.length. it gives the length of the array
if (itemId[i] == value) {
return itemName[i];
}

}
return null;
}
}
RetailStoreExample.java
public class RetailStoreExample extends RetailStore {

public static void main(String[] args) {


int index;
RetailStore retailOne = new RetailStore();

String description = retailOne.fetchDescription(1004);

// below line illustrates the use of split function of String class


String StringArray[];
// below line split the string and stores the splitted values to an
// array
StringArray = description.split("\\s");

/* this commented code illustrates the use of StringTokenizer to achieve


* the same functionality of split method
*
* StringTokenizer st = new StringTokenizer(Description);
* StringArray = new String[st.countTokens()];
* for (int i=0; st.hasMoreTokens(); i++) {
* StringArray[i] = st.nextToken();
* }
*/
String type = StringArray[2];
System.out.println("the type of the item is " + type);
System.out.println("the charactor at starting position is "
+ type.charAt(0));

// below line will find the location of the symbol "-"


index = type.indexOf('-');

String stringFromSubstring = type.substring(index + 1);


System.out.println("the price computed using the substring method is "
+ stringFromSubstring);

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

What are 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

array can have rows of varying lengths:


123
45
6
This is useful when the data you need to store does not have a fixed structure across all rows.

Declaring a Ragged Array

In Java, ragged arrays are declared as an array of arrays. The syntax is:

datatype[][] raggedArray = new datatype[numOfRows][];


arrayName[0] = new datatype[col1];
arrayName[1] = new datatype[col2];
.
.
arrayName[numOfRows-1] = new datatype[colN];

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.

Example: Declaring and Printing a Ragged Array

Here is an example program that demonstrates how to declare a ragged array, assign values to
it, and print its contents using nested loops.

1. Create a new Java class named RaggedArray.

2. Define the main method inside the class.

3. Declare a 2-D jagged of integers named raggedArray with 3 rows.


Output:

Initialization using array literals:


Intitialization using Java 8 streams:

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.

In the previous example try using this method of declaration.

Note: Don’t forget to import necessary libraries to use, i.e., ‘java.util.stream.Stream’

Advantages of Ragged Array

Jagged arrays have several advantages over multidimensional arrays with a fixed size:

1. Memory Efficiency: Ragged arrays are more memory-efficient than


multidimensional arrays because they only allocate memory for the elements they
need. In a multidimensional array with a fixed size, all the memory is allocated, even
if some elements are unused.

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.

4. Easier to manipulate: Ragged arrays can be easier to manipulate than rectangular


arrays because they allow for more direct access to individual elements. With
rectangular arrays, you may need to use more complex indexing or slicing operations
to access subsets of the data.
4.1 Exercise:

Write a java program to take user input in an integer ragged array using nested loops.

4.2 Exercise:

1. Create a Ragged Array:


o Declare a ragged array with 4 rows.
o The first row should have 4 elements, the second should have 3 elements, the
third should have 2 elements, and the fourth should have 1 element.

2. Assign Values:

o Assign values to each element of the array (you can choose any values).

3. Find the Sum of All Elements:

o Write a method int sumRaggedArray(int[][] array) that takes the ragged array
as input and returns the sum of all the elements.

4. Print the Sum:


o Print the sum of the elements in the array.

Sample Output for Exercise:

If the ragged array looks like this:

1234
567
89
10

The sum of all elements should be 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55.

Tips:

a ragged array may have a different number of


elements.

elements in the i-th row.

You might also like