DSA Module 5 Structures

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Unit 5: Structures

Unit 5
Structures

Introduction

A structure helps you to make a single variable hold related data of


various data types. The struct keyword is used for creating a structure.
It can contain a parameterized constructor, static constructor,
constants, fields, methods, properties, indexers, operators, events, and
nested types.

Unit Learning Outcomes


At the end of the unit, you will be able to:
a. define what a structure is;
b. differentiate a structure from an array
c. create and execute structure

Topic 1: Structure Within a Structure


Time Allotment: 6 Hours

Learning Objectives

At the end of the session, you will be able to:


a. declare a structure type
b. declare variables as structures
c. initialize structure members
d. access structure members

Activating Prior Knowledge


Write your idea/s about structures on the space provided.

1
Unit 5: Structures

Presentation of Contents
Structures

Structure is a collection of objects having different data types. Also known as record.
Each object in the structure is called a field.

Declaring a structure
The structure is declared by using the keyword class followed by a structure name, also
called a tag. Then the structure members (variables) are defined with their type and
variable names inside the open and close curly braces. Finally the closed curly brace end
with a semicolon; following the statement. The structure declaration is also called a
Structure Specifier.

Example:

keyword
class Customer Structure name
{
int custnum;
int salary; Structure members
float commission;
};

In the above example, it is seen that variables of different types such as int and float are
grouped in a single structure name Customer.
Arrays behave in the same way, declaring structures does not mean that memory is
allocated. Structure declaration gives a skeleton or template for the structure.
After declaring the structure, the next step is to define a structure variable.

Java Classes and Objects

Java is an object-oriented programming language.


Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

2
Unit 5: Structures
Create a Class
To create a class, use the keyword class:

Create a class named "MyClass" with a variable x:


public class MyClass {
int x = 5;
}
Remember from the Java Syntax chapter that a class should always start with an
uppercase first letter, and that the name of the java file should match the class
name.

Create an Object
In Java, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object
name, and use the keyword new:

Example
Create an object called "myObj" and print the value of x:
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}

Output:
5

Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of MyClass:
public class MyClass {
int x = 5;

public static void main(String[] args) {


MyClass myObj1 = new MyClass(); // Object 1
MyClass myObj2 = new MyClass(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}

3
Unit 5: Structures

Output:
5
5

How to declare Structure Variable?


This is similar to variable declaration. For variable declaration, data type is defined
followed by variable name. for structure variable declaration, the data type is the name of
the structure followed by the structure variable name.

In the given example, structure variable cust is defined as:

Customer cust[ ] = new Customer[10];

Structure Name Structure variable name

What happens when this is defined? When structure is defined, it allocates or reserves
space in memory. The memory space allocated will be cumulative of all defined structure
members. In the given example, there are 3 structure members: custnum, salary, and
commission. Of these, two are type int and one is of type float.

Java Field
A Java field is a variable inside a class. For instance, in a class representing an
employee, the Employee class might contain the following fields:
 name
 position
 salary
 hiredDate

The corresponding Java class could be defined like this:

public class Employee {


String name;
String position;
int salary;
Date hiredDate;
}

Field Declaration Syntax


A Java field is declared using the following syntax:

[access_modifier] [static] [final] type name [= initial value] ;

The square brackets [ ] around some of the keywords mean that this option is
optional. Only type and name are required.

4
Unit 5: Structures
First an access modifier can be declared for a Java field. The access modifier
determines which object classes that can access the field. In
the Employee example above there were no access modifiers.

Second, a data type for the Java field must be assigned. In the Employee example
above the data types String, int and Date were used.

Third, the Java field can be declared static. In Java, static fields belongs to the
class, not instances of the class. Thus, all instances of any class will access the
same static field variable. A non-static field value can be different for every object
(instance) of a class.

Fourth, the Java field can be declared final or not. A final field cannot have its
value changed. A final field must have an initial value assigned to it, and once set,
the value cannot be changed again. A final field is often also declared static. A
field declared static and final is also called a "constant".

Fifth, the Java field is given a name. You can choose this name freely, but there
are some restrictions on what characters the name can contain.

Sixth, you can optionally set an initial value for the field.
Some of the above options are described in more detail in the following sections.

Java Field Access Modifiers


The Java field access modifier determines whether the field can be accessed by
classes other than the the class owning the field. There are four possible access
modifiers for Java fields:
 private
 package
 protected
 public

The private access modifier means that only code inside the class itself can access
this Java field.

The package access modifier means that only code inside the class itself, or other
classes in the same package, can access the field. You don't actually write the
package modifier. By leaving out any access modifier, the access modifier
defaults to package scope.

The protected access modifier is like the package modifier, except subclasses of
the class can also access the field, even if the subclass is not located in the same
package.

The public access modifier means that the field can be accessed by all classes in
your application.

5
Unit 5: Structures

Here are a few examples of fields declared with access modifiers. The modifiers
are in bold.

public class Customer {

private String email;


String position; //no modifier = package access modifier
protected String name;
public String city;

The above use of Java field access modifiers are for the sake of this example only.
You would probably not use all access modifiers in the same class. Most often
you use private and protected. For simple, data carrying classes you may declare
all fields public.

Static and Non-static Fields


A Java field can be static or non-static.

A static field belongs to the class. Thus, no matter how many objects you create
of that class, there will only exist one field located in the class, and the value of
that field is the same, no matter from which object it is accessed. Here is a
diagram illustrating static fields:

Static Java fields are located in the class, not in the instances of the class.
You define a static field by using the static keyword in the field declaration, like
this:
public class Customer {

static String staticField1;

6
Unit 5: Structures

Static fields are located in the class, so you don't need an instance of the class to
access static fields. You just write the class name in front, like this:
Customer.staticField1 = "value";

System.out.println(Customer.staticField1);

Non-static Java fields, on the other hand, are located in the instances of the class.
Each instance of the class can have its own values for these fields. Here is a
diagram illustrating non-static fields:

Non-static Java fields are located in the instances of the class.

You define a non-static Java field simply by leaving out the static keyword. Here
is an example:

public class Customer {

String field1;

To access a non-static field you need an instance of the class (an object) on which
you can access it. Here is an example:
Customer customer = new Customer();

customer.field1 = "value";

System.out.println(customer.field1);

Final Fields
A Java field can be declared final. A final field cannot have its value changed,
once assigned. You declare a field to be final by adding the final keyword to the
field declaration. Here is an example:

public class Customer {

7
Unit 5: Structures

final String field1 = "Fixed Value";

The value of the field1 field cannot be changed now. That means, that even if the
field belongs to objects (class instances), you cannot vary the value of the field
from object to object.
When you cannot change the value of a final field anyways, in many cases it
makes sense to also declare it static. That way it only exists in the class, not in
every object too. Here is an example:

public class Customer {

static final String field1 = "Fixed Value";

Since static final fields are often used as constants, the naming convention is to
write the field name in all uppercase, and to separate the words with underscore
_ . Here is a Java static final field example:

public class Customer {

static final String CONSTANT_1 = "Fixed Value";

Naming Java Fields


The name of a Java field is used to refer to that field from your code. Here is an
example:

Customer customer = new Customer();


customer.city = "New York";
System.out.println(customer.city);

The first line creates a new Customer object (an instance of the Customer class),
and stores it in a variable called customer. The second line assigns
the String value New York to the Customer objects city field. The third line prints
out the value of the city field to the console output.
The naming restrictions and naming conventions for fields are the same as for any
other type of variable.

Initial Field Value


A Java field can have be given an initial value. This value is assigned to the field
when the field is created in the JVM. Static fields are created when the class is

8
Unit 5: Structures
loaded. A class is loaded the first time it is referenced in your program. Non-static
fields are created when the object owning them are created.
Here is an example of a Java field being declared with an initial value:

public class Customer {

String customerType = "OnlineCustomer";

Whether you want to initialize your Java fields (and other variables) to an initial
value is up to you. I have made it a habit to always initialize my variables to some
sensible value, but it is just a habit. It is not necessary to do so.

How to access structure members?


To access structure members, the operator used is the dot operator denoted by (.)

import java.util.*;
import java.io.*;

class Record
{
int grade;
String studentName;
}

public class structPractice


{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);

Record[] student = new Record[10];

System.out.println("Please enter the name of the student, press enter then enter his
grade.");
for(int i =0; I < student.length; i++)
{
student[i] = new Record();
System.out.print(“Student “ + (i+1) + “:”);
student[i].studentName = input.next();
System.out.print(“Grade “ + (i+1) + “:”);
student[i].grade = input.nextInt();
}

for( int i =0; i<student.length; i++)


{
System.out.println(student[i].studentName);
System.out.println(student[i].grade);
}

9
Unit 5: Structures
}

Application
1. Write a program that declare a simple structure, declare at least two
variables with different data type.

2. Write a program to declare a structure and inside it is method that


returns the area of a rectangle.

Test Data and Sample Output:


Input the dimensions of a rectangle:
Length: 60
Width: 30
Expected Output:
Length: 60
Width: 30
Area: 1800

Feedback
I. TRUE or FALSE
Instruction: Determine whether the statements are TRUE or FALSE. Write
T if the statement is correct, otherwise, write F and the word or words that
make the statement false. Write your answer on the space provided.

_____T___ 1. A collection of objects having different data types, also known as record
is Structure.

________ 2. Inside a structure, we can initialize a field.

__F______ 3. To create a class, use the keyword struct.

___T_____ 4. A Java field is a variable inside a class.

________ 5. A structure determines whether the field can be accessed by classes


other than the class owning the field.

________ 6. To access structure members, the operator used is the plus operator.

For items 7 to 10, identify the parts of a structure declaration.

7.

10
Unit 5: Structures

8.

public class Book 9.


{
private String Title;
private int pages;
private double price; 10.
}

For items 11-15, read each statement carefully. Select the best answer from the
given choices. Write the letter oy your answer on the space provided for before
each item.

_____ 11. Predict the output of following Java program

class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.i);
}

a. 0
b. garbage value
c. compiler error
d. runtime error

_____ 12. Predict the output of following Java program

class demo
{
int a, b;
demo()
{
a = 10;
b = 20;
}
public void print()
{
System.out.println ("a = " + a + " b = " + b + "\n");
}
}

class Test
{
public static void main(String[] args)
11
Unit 5: Structures
{
demo obj1 = new demo();
demo obj2 = obj1;

obj1.a += 1;
obj1.b += 1;

System.out.println ("values of obj1 : ");


obj1.print();
System.out.println ("values of obj2 : ");
obj2.print();
}
}

a. Compile error

b. values of obj1:
a = 11 b = 21
values of obj2:
a = 11 b = 21

c. values of obj1:
a = 11 b = 21
values of obj2:
a = 10 b = 20

d. values of obj1:
a = 11 b = 20
values of obj2:
a = 10 b = 21

_____ 13. A Java field is declared using the following syntax:

[access_modifier] [static] [final] type name [= initial value];

a. True
b. False

_____ 14. Which of the following does NOT belong to the group?

a. private
b. package
c. protected
d. class

_____ 15. The public access modifier means that the field can be accessed by all
classes in your application.

a. True

12
Unit 5: Structures
b. False

II. Output Tracing. What will be the output of the following code?

class MyStruct {
public int a;
public int b;

public void PassAB(int x, int y) {


a = x;
b = y;
}
}

class MyClient {
public static void Main() {
MyStruct ms = new MyStruct();
ms.a = 10;
ms.b = 20;
ms.PassAB(50,100);
int sum = ms.a + ms.b;
System.out.println("The sum is ", sum);
}
}

13
Unit 5: Structures

Reflection

Answer briefly the given questions based on your own understanding. Write your
answer on the space provided.
When should you use a structure? Why?

Structure is a collection of objects having different data types. Also known


as record. Each object in the structure is called a field.
A structure is defined using struct keyword. Using struct keyword one can
define the structure consisting of different data types in it.
A structure can also contain constructors, constants, fields, methods,
properties, indexers and events.

14
Unit 5: Structures

Retried from https://www.programiz.com/java-programming/class-objects

Retried from http://tutorials.jenkov.com/java/fields.html#:~:text=In%20Java%2C


%20static%20fields%20belongs,be%20declared%20final%20or%20not.

Retried from https://stackoverflow.com/questions/23165611/java-creating-an-


array-inside-of-an-object-class/23165717

Retried from https://stackoverflow.com/questions/23165611/java-creating-an-


array-inside-of-an-object-class/23165717

15

You might also like