0% found this document useful (0 votes)
4 views15 pages

Java T-3

The document covers fundamental concepts of arrays and classes in Java, including definitions, initialization methods, and examples of programs to calculate sums and medians. It also differentiates between 1D and 2D arrays, explains the for-each loop syntax, and discusses the differences between strings and arrays. Additionally, it defines classes and objects, providing examples of a Student class and a Circle class with relevant methods.

Uploaded by

dheeraj72006
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)
4 views15 pages

Java T-3

The document covers fundamental concepts of arrays and classes in Java, including definitions, initialization methods, and examples of programs to calculate sums and medians. It also differentiates between 1D and 2D arrays, explains the for-each loop syntax, and discusses the differences between strings and arrays. Additionally, it defines classes and objects, providing examples of a Student class and a Circle class with relevant methods.

Uploaded by

dheeraj72006
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

Tutorial 3: Arrays and Class Fundamentals

1. Arrays

a) Define array. [R]

An array is an object that acts as a container to hold a fixed number of values of


a single data type. The elements in an array are stored in contiguous memory
locations, and all elements can be accessed using an index, starting from 0.

b) Explain how the values can be initialized into an array. [U]

Values can be initialized into an array in Java in several ways:

1. Declaration, Instantiation, and Initialization: Values are assigned at the time


the array is created.

Java

int[] numbers = new int[5];

numbers[0] = 10;

numbers[1] = 20;

// ... and so on

2. Using an Array Initializer: A shorthand way to declare, instantiate, and initialize


an array in one step. The size is implicitly determined by the number of values
provided.

Java

int[] numbers = {10, 20, 30, 40, 50}; // Size is 5

3. Using a Loop: Values can be assigned dynamically, typically from user input or a
calculated value, using a for loop or similar structure.

Java

int[] numbers = new int[5];

for (int i = 0; i < [Link]; i++) {

numbers[i] = i * 10 + 10; // Assigns 10, 20, 30, 40, 50

}
c) Develop a Java program to display sum of even positioned prime numbers
present in an array. [Ap]

The prompt uses as an example where and are "even positioned" (index 1 and 3, if
position 1 is odd), and the sum is . This implies "even positioned" refers to
the index being an odd number if the problem statement uses 1-based
indexing (position 2, 4, 6...) or the index being an even number (0, 2, 4...) if the prompt
mistakenly interpreted the example.

Given that array indexing starts at , and for :

 Index 0: 10 (Odd position 1)

 Index 1: 20 (Even position 2)

 Index 2: 30 (Odd position 3)

 Index 3: 40 (Even position 4)

 Index 4: 50 (Odd position 5)

I will assume "even positioned" means elements at indices (the 2nd, 4th,
6th, element), as this matches the example's selection of (index 1) and (index 3).
However, and are not prime numbers. Since the instruction explicitly states "sum of
even positioned prime numbers," but the example uses non-prime numbers, I will
implement the code to check for primality while selecting elements at odd indices (i %
2 != 0).

Java

public class EvenPositionedPrimeSum {

// Helper method to check for primality

public static boolean isPrime(int n) {

if (n <= 1) {

return false;

for (int i = 2; i <= [Link](n); i++) {

if (n % i == 0) {

return false;

}
}

return true;

public static void main(String[] args) {

// Test array with prime numbers at even positions (odd indices 1, 3)

int[] A = {10, 13, 30, 17, 50};

// The array provided in the example: int[] A = {10, 20, 30, 40, 50};

long sum = 0; // Use long for sum

[Link]("Array A: {10, 13, 30, 17, 50}");

[Link]("Checking elements at odd indices (1, 3, 5, ...):");

for (int i = 0; i < [Link]; i++) {

// Check for even position (odd index: 1, 3, 5, ...)

if (i % 2 != 0) {

if (isPrime(A[i])) {

[Link](" Found prime at index " + i + ": " + A[i]);

sum += A[i];

[Link]("Sum of even positioned prime numbers: " + sum);

// Output for the provided example {10, 20, 30, 40, 50}

int[] exampleA = {10, 20, 30, 40, 50};


long exampleSum = 0;

for (int i = 0; i < [Link]; i++) {

if (i % 2 != 0) {

if (isPrime(exampleA[i])) {

exampleSum += exampleA[i];

// If the problem meant *any* number at that position, the sum would be 20+40=60.

// If it MUST be prime, the sum is 0.

[Link]("\nUsing the original example A[]={10,20,30,40,50}: Sum is 0 (as


20 and 40 are not prime).");

2. 1D Array vs. 2D Array and Median

a) Di erentiate 1D array with 2D array. [U]

Feature 1D Array (Single-Dimensional) 2D Array (Multi-Dimensional/Array of


Arrays)

Structure A linear list or sequence of A matrix-like structure representing


elements. rows and columns.

Indexing Requires only one index to access Requires two indices to access an
an element (e.g., A[i]). element (e.g., A[row][col]).

Representation Conceptually, a single row or Conceptually, a table or grid of data.


column of data.
Feature 1D Array (Single-Dimensional) 2D Array (Multi-Dimensional/Array of
Arrays)

Declaration type[] arrayName; or type type[][] arrayName; or type


arrayName[]; arrayName[][];

b) Develop a Java program to display median of element of each row of 2D matrix.


[Ap]

To find the median:

1. Sort each row.

2. If the number of elements is odd, the median is the element at index .

3. If is even, the median is the average of the two middle elements, at indices and .

The example is used for testing.

Java

import [Link];

public class TwoDMedianCalculator {

public static void main(String[] args) {

int[][] A = {{1, 7, 2, 6}, {10, 9, 12, 3}};

[Link]("Input 2D Array:");

for (int[] row : A) {

[Link]([Link](row));

[Link]("\nMedians of each row:");

for (int i = 0; i < [Link]; i++) {

// 1. Sort the current row

int[] row = A[i];


[Link](row);

int n = [Link];

double median;

if (n % 2 != 0) {

// Odd number of elements

median = row[n / 2];

} else {

// Even number of elements

int middle1 = row[n / 2 - 1];

int middle2 = row[n / 2];

median = (double) (middle1 + middle2) / 2.0;

[Link]("Row %d (Sorted %s): Median = %.1f\n", i + 1,


[Link](row), median);

// For the example row {1, 7, 2, 6}: Sorted {1, 2, 6, 7}. Median = (2+6)/2 = 4.0

// For the example row {10, 9, 12, 3}: Sorted {3, 9, 10, 12}. Median = (9+10)/2 = 9.5

3. For-Each Loop and Array Sum

a) What is the syntax of for each loop. [R]

The enhanced for loop, or for-each loop, is designed for iterating through all elements
in collections or arrays without needing an explicit index.

The syntax is:

Java
for (DataType element : collectionOrArray) {

// Statements to execute for each element

 DataType: The data type of the elements in the array/collection.

 element: A variable that temporarily holds the value of the current element in the
iteration.

 collectionOrArray: The array or collection to be iterated over.

b) Develop a Java program to find sum of two 1D array elements. [Ap]

The program should add corresponding elements of two arrays, and , and store the
result in a new array, . This requires that and have the same length.

Example: , , Output: .

Java

import [Link];

public class ArrayElementSum {

public static void main(String[] args) {

int[] A = {1, 2, 3};

int[] B = {7, 8, 9};

// Check if arrays have the same length

if ([Link] != [Link]) {

[Link]("Error: Arrays must have the same length for element-wise


sum.");

return;

int[] Result = new int[[Link]];

for (int i = 0; i < [Link]; i++) {


Result[i] = A[i] + B[i];

[Link]("Array A: " + [Link](A));

[Link]("Array B: " + [Link](B));

[Link]("Output: Result[] = " + [Link](Result));

4. String vs. Array and Character Occurrence

a) How string di ers from array in Java. [R]

Feature String Array

Data Type A sequence of characters. A sequence of any single data


type (primitives or objects).

Mutability Immutable (cannot be changed after Mutable (elements can be changed after
creation). Operations create new String creation).
objects.

Fixed Size Size (length) is fixed once the String Size (length) is fixed once the array is
object is created. instantiated.

Library [Link] class provides rich Built-in language feature; manipulation


methods (e.g., substring(), equals()). often requires explicit looping or
the [Link] utility class.

b) Develop a Java program to find the occurrence of digits and alphabets present in
a given string. [Ap]

The program should count the occurrence of each unique digit and alphabet in the
string.

Java

import [Link];
import [Link]; // Use TreeMap to keep output sorted by key

public class CharOccurrenceCounter {

public static void main(String[] args) {

String input = "1CSM 3CSN 3CSO 5CSM 7CSM 5CSO";

[Link]("Input String: \"" + input + "\"");

// Maps to store counts for digits and alphabets

Map<Character, Integer> digitCounts = new TreeMap<>();

Map<Character, Integer> alphabetCounts = new TreeMap<>();

// Convert string to uppercase for case-insensitive counting of alphabets

String upperInput = [Link]();

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

if ([Link](ch)) {

// If it's a digit

[Link](ch, [Link](ch, 0) + 1);

} else if ([Link](ch)) {

// If it's an alphabet (counted case-insensitively)

[Link](ch, [Link](ch, 0) + 1);

// Ignore spaces and other characters

[Link]("\n--- Digit Occurrence ---");


for ([Link]<Character, Integer> entry : [Link]()) {

[Link]([Link]() + " -> " + [Link]());

[Link]("\n--- Alphabet Occurrence ---");

for ([Link]<Character, Integer> entry : [Link]()) {

[Link]([Link]() + " -> " + [Link]());

// Example Output Check:

// Digits: 1 (2), 3 (2), 5 (2), 7 (1) - Correct.

// Alphabets: C(6), S(6), M(3), N(1), O(2)

5. Class and Object Definition

a) Define the class and object. [R]

 Class: A class is a template or a blueprint for creating objects. It defines the


characteristics (data fields/variables) and behaviors (methods/functions) that an
object of that class will possess. It is a logical construct that does not consume
memory when created.

 Object: An object is a basic runtime entity. It is an instance of a class. An object


has state (values of its variables) and behavior (implementation of its methods)
and occupies memory.

b) Develop a Java program to simulate the real world object called Student where
his marks has to be get updated whenever he writes the exam. [Ap]

The Student class will contain attributes like rollNumber, name, section, a map
for subjects and marks, and a method to update the marks.

Java

import [Link];

import [Link];
public class Student {

private int rollNumber;

private String name;

private String section;

private Map<String, Integer> marks; // Stores Subject -> Mark

// Constructor

public Student(int rollNumber, String name, String section) {

[Link] = rollNumber;

[Link] = name;

[Link] = section;

[Link] = new HashMap<>();

// Method to update marks (simulate writing an exam)

public void updateMark(String subject, int mark) {

if (mark >= 0 && mark <= 100) {

[Link](subject, mark);

[Link](name + "'s mark for " + subject + " updated to " + mark);

} else {

[Link]("Error: Mark must be between 0 and 100.");

// Method to display student details

public void displayDetails() {

[Link]("\n--- Student Details ---");


[Link]("Roll Number: " + rollNumber);

[Link]("Name: " + name);

[Link]("Section: " + section);

[Link]("Subjects and Marks: " + marks);

public static void main(String[] args) {

// Creating a Student object (real-world object simulation)

Student s1 = new Student(42, "Rahul Verma", "3CSE4");

[Link]();

// Simulating the student writing exams and updating marks

[Link]("OOPJ", 85);

[Link]("DBMS", 92);

// Re-writing an exam

[Link]("OOPJ", 88);

[Link]();

6. Instance of a Class and Circle Class

a) What is instance of a class. [R]

An instance of a class is the same as an object. It is a concrete realization of the class


blueprint.

When a program executes the new operator followed by the class name (e.g., new
Student(...)), a memory block is allocated, and the constructor is called. The reference
to this newly created entity in memory is the instance of that class. Every instance
maintains its own copy of the class's instance variables (state).

b) Circle is a geometrical object... Develop a java program to create a class called


Circle... [Ap]

The Circle class needs to implement:

 Instance variable: radius

 Methods: getRadius(), setRadius(), getArea(), and getPerimeter().

 Constants: ([Link]).

Java

public class Circle {

private double radius;

// Default Constructor

public Circle() {

[Link] = 0.0;

// Parameterized Constructor

public Circle(double radius) {

[Link] = radius;

// --- Getter and Setter for radius ---

// Getter method for radius

public double getRadius() {

return radius;

}
// Setter method for radius

public void setRadius(double radius) {

if (radius > 0) {

[Link] = radius;

[Link]("Radius set to: " + radius);

} else {

[Link]("Error: Radius must be positive.");

// --- Computation Methods ---

// Method to compute and return the area (Area = π * r²)

public double getArea() {

return [Link] * radius * radius;

// Method to compute and return the perimeter (Perimeter = 2 * π * r)

public double getPerimeter() {

return 2 * [Link] * radius;

public static void main(String[] args) {

// Create an instance of the Circle class

Circle circle1 = new Circle(5.0);

[Link]("--- Circle 1 Initial Details ---");

[Link]("Radius: %.2f\n", [Link]());


[Link]("Area: %.2f\n", [Link]());

[Link]("Perimeter: %.2f\n", [Link]());

// Update the radius using the setter

[Link](7.5);

[Link]("\n--- Circle 1 Updated Details ---");

[Link]("Radius: %.2f\n", [Link]());

[Link]("Area: %.2f\n", [Link]());

[Link]("Perimeter: %.2f\n", [Link]());

You might also like