Professional Documents
Culture Documents
DSA Module 5 Structures
DSA Module 5 Structures
DSA Module 5 Structures
Unit 5
Structures
Introduction
Learning Objectives
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.
2
Unit 5: Structures
Create a Class
To create a class, use the keyword class:
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;
Output:
5
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of MyClass:
public class MyClass {
int x = 5;
3
Unit 5: Structures
Output:
5
5
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 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.
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.
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.
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 {
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:
You define a non-static Java field simply by leaving out the static keyword. Here
is an example:
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:
7
Unit 5: Structures
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:
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:
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.
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:
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.
import java.util.*;
import java.io.*;
class Record
{
int grade;
String studentName;
}
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();
}
9
Unit 5: Structures
}
Application
1. Write a program that declare a simple structure, declare at least two
variables with different data type.
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.
________ 6. To access structure members, the operator used is the plus operator.
7.
10
Unit 5: Structures
8.
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.
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
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;
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
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;
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?
14
Unit 5: Structures
15