L
LLLOS.ai
Learn
L

Chapter 6 — Data processing in Java

Class 9 · Computer Applications

Overview

This unit explains how to process data using the Java programming language. It begins with the basic ideas of data and how programs accept, store, change and produce data. Students learn Java data types, variables, operators and control structures that let a program make decisions and repeat actions. The unit then shows how to hold collections of data with arrays and ArrayList, how to work with text using strings, and how to split a program into methods for clearer processing. Practical input and output are taught using the Scanner class and file streams so students can build programs that read from and write to the keyboard and files. Finally, the unit introduces simple exception handling to make programs safer. This unit matters because data processing is the core job of most programs: everything from simple calculators to school records relies on reading, transforming and saving data. By learning these concepts and the Java tools that implement them, students gain skills to write correct and useful programs, debug errors, and prepare for larger projects in later classes.

Learning Objectives

  • Explain what data processing means and why it is important in programs.
  • Declare and use primitive data types and variables correctly in Java.
  • Read input from the user and display output using standard Java classes.
  • Apply operators, conditional statements and loops to transform data.
  • Store and access collections of data using one-dimensional and two-dimensional arrays.
  • Manipulate text data using Java String methods.
  • Write and call methods with parameters and return values to structure a program.
  • Read from and write to text files, handling common file I/O tasks.
  • Handle simple runtime errors using try-catch blocks and understand when exceptions occur.

Topics in this chapter

18 topics · tap a topic title to jump straight to it.

📊1

Introduction to data processing and Java

What is data processing?
Data processing means collecting raw data, applying operations or rules to it, and producing information or results that are useful. In programming, this often appears as a sequence of steps: read input, compute or transform values, and finally present or store the output. Data processing can be as small as summing three numbers or as large as maintaining a school database with many records.

Core ideas for students
When you design a data processing program, think in three parts: Input, Processing and Output. Input is where data comes from—keyboard, file, sensor, or network. Processing is where the program applies arithmetic operations, makes decisions, repeats tasks with loops, and organises data into structures like arrays or objects. Output is how the program shows results to the user or saves them for later.

Java as a teaching language
Java is widely used and combines clear rules with a large standard library. It enforces a structured approach: every program has classes and a main method where execution begins. Java’s strong typing and useful built-in classes help students understand data types and how to avoid common mistakes. Java also runs in many environments, making programs portable.

Simple program structure
A minimal Java program includes a class and a main method: public class Program { public static void main(String[] args) { /* statements */ } } Inside main you place statements to read input, process data, and print results. A statement ends with a semicolon and blocks of statements are grouped with braces { }.

From problem to program
Good data processing starts with careful problem analysis. Read the problem, list the inputs and outputs, and think what processing steps are needed. Write small examples by hand to check the logic. Then convert those steps into code, test with sample data and refine. This habit prevents many errors.

Testing and debugging
Always test with normal cases and special cases like empty input or very large numbers. Use clear prompts and messages so a user knows what to enter. Comment your code to explain difficult parts and use meaningful names for variables and methods. Clear code is easier to debug, mark and reuse.

Practical examples
Start by writing small programs: add numbers from the keyboard, compute averages from a list, or read and write a simple text file. Each small task reinforces the Input->Process->Output structure and prepares you for larger assignments.

Summary
In this unit you will practise writing small Java programs that read values, process them using types, variables, operators, decisions and loops, and then present results. These fundamentals are the basis for more advanced work later in the course.

📌 Examples
  • Add two numbers entered by the user and display the sum.
  • Read five test marks into an array, compute the average and print it.
🧮 Formulas
  1. Program structure: class ClassName { public static void main(String[] args) { /* statements */ } }
  2. Basic processing steps: Input -> Process -> Output
📊 Visual ideas
A flowchart showing Start -> Read input -> Process (calculate) -> Output -> End
A block diagram with three boxes labelled Input, Processing, Output connected left to right
💻2

Setting up Java and using an IDE or editor

Installing Java and selecting tools
To write Java programs you need a Java Development Kit (JDK) installed on your computer. The JDK provides the compiler which translates your source files into bytecode, and the Java Virtual Machine which runs the compiled programs. Many schools provide an installer or instructions; follow those carefully for your operating system. Once the JDK is installed, you can either use command-line tools or use an Integrated Development Environment (IDE).

Using a text editor and command line
A simple way to start is to write code in a plain text editor and use the command prompt or terminal to compile and run. Save your file with the .java extension where the public class name matches the file name. From the terminal run javac FileName.java to compile; if successful, run java FileName to execute. Read compiler messages and fix errors indicated by line numbers. This approach helps you learn what the compiler does and how the Java runtime works.

Advantages of an IDE
An IDE bundles an editor, compiler and run tools into one window and adds helpful features like syntax highlighting, code completion, error markers and an integrated console. It usually provides project management so your files are organised. Popular choices for beginners include BlueJ, NetBeans and Eclipse. An IDE speeds up development and makes debugging easier with step-by-step execution and variable inspection.

Writing your first program
Create a new project in your IDE or a new file in your editor. Start with a simple Hello World program to test the setup: create a class with a public static void main method and use System.out.println("Hello"); to print output. Compile and run. If the program runs successfully, your environment setup is complete.

Debugging basics
When the compiler shows errors, read the messages from top to bottom; often the first error causes later ones. Pay attention to common mistakes: missing semicolons, mismatched braces, wrong class file name, or case-sensitivity issues. If a program compiles but behaves incorrectly, use print statements or the debugger to check variable values at different points.

Project and file management
Keep related files in a project folder. Use descriptive file and class names. Back up your work regularly and keep earlier working versions when making big changes. Use comments at the start of each file to state the purpose of the program, inputs and outputs. Good organisation saves time and prevents mistakes when you return to a program later.

Sharing and submission
When you submit code for assessment, include source files and any input files required to run the program. Provide a short readme describing how to compile and run the program. Ensure your code compiles on a standard setup to avoid environment-specific issues.

Summary
Understanding how to set up Java and use tools is the first step to learning programming. Practice creating, compiling and running small programs until the workflow becomes routine; later you will focus on solving problems rather than on setup steps.

📌 Examples
  • Create HelloWorld.java, compile with javac HelloWorld.java, run with java HelloWorld.
  • Open an IDE project, add a class Sum.java with main, and run to test user input.
🧮 Formulas
  1. Compile: javac FileName.java -> produces FileName.class
  2. Run: java FileName
📊 Visual ideas
A diagram showing Source File (.java) -> Compiler (javac) -> Bytecode (.class) -> Java Virtual Machine (java) -> Output
IDE window sketch with editor pane, console pane and project explorer
📊3

Primitive data types and literals

Understanding primitive types
Java provides primitive data types to store simple values directly. The commonly used primitives are int for whole numbers, double for decimal numbers, char for single characters and boolean for true/false values. There are also byte, short and long for integers of different sizes, and float for a single-precision decimal type. Choosing the correct type matters for memory, range of values and how operations behave.

Integer types and ranges
int is the default integer type and is sufficient for most school problems. long is used when numbers exceed int range. short and byte are smaller and rarely needed for beginners. Integer literals are written without decimal points: 10, -3, 0. To explicitly write a long literal append L: 100000L. Underscores can be placed inside numeric literals for readability: 1_000_000.

Floating-point numbers
Use double for decimal values like 3.14 or -0.5. By default decimal literals are double; use an f or F suffix to write a float literal like 2.5f. Floating-point arithmetic follows rules of rounding and precision; be aware that comparing doubles for exact equality can be unreliable due to small rounding errors.

Character and boolean
char stores a single Unicode character enclosed in single quotes: 'A', '7', '\n'. Use boolean to control decisions and loops with the values true or false. Many conditions in code evaluate to boolean results from relational or logical operators.

Type conversion and casting
Java performs automatic (widening) conversions when a smaller type is used where a larger compatible type is expected: int to double is allowed automatically. Narrowing conversions (double to int) must be done explicitly using a cast: int x = (int) 3.9; which truncates the fractional part. Casting can lose information; use it only when appropriate.

Literals and notation
Integer and floating literals can use underscores to improve readability. Character literals use single quotes and string literals use double quotes. Boolean literals are simply true or false. Be mindful of suffixes: L for long and f for float.

Practical advice
Pick int for counts and index values, double for averages and measurements, char for single characters, and boolean for logic checks. Document assumptions about ranges to avoid overflow. Test operations near boundary cases (e.g., large numbers, division by zero) to see how types behave.

Summary
Understanding primitives and literals is essential for correct calculations and memory use. These types are the building blocks of data processing; knowing their behaviour prevents many errors and helps you write reliable programs.

📌 Examples
  • int age = 14; double price = 49.99; char grade = 'A'; boolean pass = true;
  • double d = 5; // int 5 is converted to double 5.0 automatically
🧮 Formulas
  1. Widening conversion: int -> long -> float -> double
  2. Narrowing conversion requires cast: double to int: int x = (int) 3.9;
📊 Visual ideas
A tower diagram showing byte -> short -> int -> long -> float -> double (widening direction)
A sketch showing a char box with 'A' and a boolean box with true/false
💻4

Variables, constants and identifiers

What is a variable?
A variable is a named location in memory that stores a value while a program runs. You must declare its type before using it. For example: int marks; declares a variable named marks that can hold integers. You can give it an initial value at the same time: int marks = 78; Variable values can change during program execution.

Naming rules and conventions
Identifiers are names for variables, methods and classes. They must begin with a letter, underscore or dollar sign, and may contain letters, digits and underscores. Java is case-sensitive so score and Score are different identifiers. Use meaningful names like totalMarks or studentName. By convention class names start with an uppercase letter and variables/methods start with a lowercase letter.

Constants using final
When a value should not change, declare it as final: final double PI = 3.14159; A final variable cannot be reassigned after initialisation. Constants are usually written in uppercase with underscores to make them stand out, for example final int MAX_STUDENTS = 30.

Scope and lifetime
Scope determines where an identifier can be used. Local variables declared inside a method exist only within that method and are not visible elsewhere. Variables declared inside braces { } such as for loops or if blocks are limited to that block. Instance variables defined inside a class but outside methods belong to objects and can be accessed by methods of that class (unless declared private). Understanding scope prevents accidental reuse or shadowing of names.

Initialisation
Local variables must be given a value before use, otherwise the compiler reports an error. Instance and static variables get default values (0 for numeric types, false for boolean, null for object references) if not explicitly initialised, but it is better to set meaningful initial values to avoid logic errors.

Best practices
Choose descriptive names, avoid single-letter names except for short loop counters, and keep variable scope as small as possible. Use final for values that must not change. Comment unusual uses and keep variable declarations close to where they are first used to improve readability and maintainability.

Examples of scope issues
A variable declared inside an if block cannot be used outside. Redeclaring a variable in an inner block hides the outer variable which can cause confusion. Avoid such shadowing by selecting distinct names.

Summary
Variables, constants and identifiers are the tools you use to label and store data in programs. Clear naming, correct scope and careful initialisation reduce errors and make your code easier to follow.

📌 Examples
  • int totalMarks = 0; final int MAX_STUDENTS = 30; String name = "Rita";
  • for (int i = 0; i < 5; i++) { int temp = i * 2; } // temp is not available outside loop
🧮 Formulas
  1. Declaration and initialisation: type name = value;
  2. Constant: final type NAME = value;
📊 Visual ideas
A picture of a method showing local variable boxes inside the method block and not visible outside
A class box showing instance variables inside the class and methods accessing them
💻5

Input and output: Scanner and System.out

Standard output with System.out
System.out.println() is the basic way to display text on the console. It prints the given expression and moves to the next line. Use System.out.print() if you want to remain on the same line. You can combine text and values using the + operator: System.out.println("Sum = " + sum); For formatted output, System.out.printf or String.format can limit decimal places and format text neatly.

Reading input with Scanner
The Scanner class from java.util is convenient for reading user input or files. Create a Scanner to read from the keyboard: Scanner sc = new Scanner(System.in); Then use methods like sc.nextInt(), sc.nextDouble(), sc.next() and sc.nextLine() to read different kinds of data. Always close the Scanner when finished using sc.close() to free system resources. For reading files use new Scanner(new File("file.txt")).

next() vs nextLine() and common pitfalls
sc.next() reads the next token separated by whitespace; sc.nextLine() reads the remainder of the current line including spaces until the newline. A frequent trap is mixing nextInt() and nextLine(): after nextInt() the newline remains in the input buffer so the following nextLine() reads an empty string. To avoid this call an extra sc.nextLine() to consume the leftover newline, or read all input lines with nextLine() and parse values.

Prompting and validation
Always prompt the user with a clear message before reading input. Validate inputs such as ranges and formats. If invalid input is given, either ask again or handle the error gracefully. For numeric input you can read as a string and attempt to parse it in a try-catch block for safer validation.

Formatting and escape sequences
Use escape sequences like \n for newline and \t for tab when you need special formatting. For numeric output show a fixed number of decimal places using printf: System.out.printf("%.2f", value); This produces consistent and readable output.

Using input in processing
After reading input, store it in variables or arrays for further processing. Prompt the user with clear instructions, check values for correctness, and then apply processing such as calculations, sorting or searching. Print informative results and, if appropriate, write outputs to files for later use.

Summary
Scanner and System.out form the basic input/output tools in Java. Learn to use them carefully, handle common issues like leftover newlines, and validate input so your data processing programs are robust and user friendly.

📌 Examples
  • Scanner sc = new Scanner(System.in); System.out.print("Enter age: "); int age = sc.nextInt(); System.out.println("Age recorded: " + age); sc.close();
  • System.out.print("Enter name: "); sc.nextLine(); String name = sc.nextLine(); System.out.println("Hello " + name);
🧮 Formulas
  1. Print: System.out.println(expression);
  2. Scanner creation: Scanner sc = new Scanner(System.in); Read int: sc.nextInt(); Read line: sc.nextLine();
📊 Visual ideas
A console window sketch showing prompts and user-typed responses
A flow showing Program -> Prompt -> User types -> Program reads with Scanner -> Process
💻6

Operators: arithmetic, relational and logical

Arithmetic operators and numeric behaviour
Java supports basic arithmetic operators: +, -, *, / and % (modulo). Parentheses control order of operations. When both operands are integers, division / computes integer division and truncates any fractional part: 7 / 2 yields 3. To get a decimal result use double operands like 7.0 / 2 yielding 3.5. The modulo operator % gives the remainder of integer division (7 % 2 is 1).

Assignment and shorthand operators
Use = to assign values: x = 5. Shorthand forms combine arithmetic and assignment: x += 3 means x = x + 3; x *= 2 means x = x * 2. The increment and decrement operators ++ and -- adjust a value by one. Be aware of prefix (++x) versus postfix (x++) forms: prefix increments then yields the value, postfix yields the value and then increments.

Relational operators
Relational operators compare values and produce boolean results: == (equal), != (not equal), >, <, >=, <=. These are used in conditions for decisions and loops. For objects like String, use equals() to compare content rather than == which checks reference equality.

Logical operators for combining conditions
Logical operators combine boolean expressions: && (AND), || (OR), and ! (NOT). Use them to express compound conditions, for example (marks >= 40 && attendance >= 75). Java uses short-circuit evaluation: in A && B, B is not evaluated if A is false. This can prevent errors when the second expression would cause an exception.

Operator precedence and clarity
Operators have a hierarchy of precedence. Parentheses override this and should be used to make intent clear, especially in complex expressions. Typical precedence: arithmetic (*, /, %) before (+, -), then relational, then logical operators, with assignment last.

Type mixing and promotion
When different numeric types are combined in an expression, Java promotes smaller types to larger ones (widening) so the result preserves precision. For example int + double yields double. Be careful with overflow: large integer operations can wrap around; choose the appropriate type or check ranges.

Practical suggestions
Write expressions simply and test intermediate results when debugging. Avoid relying on side effects inside complex expressions. Use clear parentheses and meaningful variable names. Remember to use equals() for string comparison and be careful with floating-point equality tests due to rounding.

📌 Examples
  • int a = 7, b = 2; int q = a / b; int r = a % b; // q = 3, r = 1
  • boolean ok = (marks >= 40) && (attendance >= 75); // true only if both are true
🧮 Formulas
  1. Shorthand: x += y means x = x + y; x++ means x = x + 1
  2. Relational: expressions produce boolean: a == b, a != b, a > b
📊 Visual ideas
A precedence ladder diagram showing parentheses at top, then *, /, %, then +, -, then relational, then logical, then assignment
A truth table sketch for A && B, A || B, and !A
👑7

Decision making: if, if-else and switch

Using if to make choices
The if statement lets the program execute a block of code only when a condition is true. Its basic form is: if (condition) { statements } The condition must be a boolean expression. Use if to check simple conditions such as whether a number is positive or a student has passed.

If-else for two-way decisions
If you need to choose between two actions, use if-else: if (condition) { // when true } else { // when false } This is useful for binary choices like displaying "Eligible" or "Not eligible" based on age or score.

Multiple choices with else-if
When there are several possible actions, chain else-if blocks: if (cond1) { } else if (cond2) { } else if (cond3) { } else { } The conditions are evaluated in order and the first true branch runs. This pattern is common when assigning grades based on ranges of marks. Keep the order from most specific to most general to avoid incorrect matches.

Using switch for many discrete values
Switch statements compare a single value against multiple constant cases. Syntax: switch(value) { case 1: statements; break; case 2: statements; break; default: statements; } Use break to stop fall-through unless you intentionally want multiple cases to share code. In class 9 you typically use switch with integers or characters to implement menus or map values to labels.

Nested decisions and maintainability
You can nest if statements inside other if or else blocks, but deep nesting reduces readability. Instead, combine conditions with logical operators or extract parts into methods. Keep each decision handling small and well documented.

Common mistakes

  • Omitting braces {} for multi-line blocks can cause only the first statement to be controlled by the if; always use braces to avoid bugs.
  • Using = instead of == for comparison is a common error; Java will not compile if types do not match, but be careful with boolean assignments.

Practical use in data processing
Decisions are used to validate data (e.g., reject negative marks), categorise values (assign grades), and control flow (menu selections). Combine relational and logical operators to form clear conditions. When a decision becomes complex, write a descriptive method name and move the condition into that method for clarity.

Summary
If, if-else and switch let your program choose actions based on data. Use them to implement rules and validations so your data processing adapts correctly to different inputs.

📌 Examples
  • if (marks >= 90) { grade = 'A'; } else if (marks >= 75) { grade = 'B'; } else { grade = 'C'; }
  • switch(option) { case 1: System.out.println("Add"); break; case 2: System.out.println("Delete"); break; default: System.out.println("Invalid"); }
🧮 Formulas
  1. If: if (condition) { statements }
  2. If-else: if (condition) { } else { }
  3. Switch: switch(value) { case constant: statements; break; default: statements; }
📊 Visual ideas
A decision tree showing a condition leading to two branches: true and false
A switch block sketch showing value compared to case constants and arrows to actions
💻8

Loops: for, while and do-while

The role of loops
Loops let you repeat a block of code multiple times, which is essential when processing lists of data, computing totals, or implementing repeated user interactions. Java provides for, while and do-while loops that suit different situations.

For loop for counted repetition
The for loop is ideal when you know or can determine the number of iterations in advance. Its form is: for (initialisation; condition; update) { statements } For example, for (int i = 0; i < n; i++) { sum += arr[i]; } is a common pattern for iterating over an array. The loop variable i is typically used as an index.

While loop for condition-controlled repetition
Use while when repetition depends on a condition rather than a fixed count: while (condition) { statements } The condition is checked before each iteration so the body may not run at all if the condition is false initially. A typical use is reading input until a sentinel value is seen.

Do-while loop to ensure one execution
Do-while checks the condition after running the loop body, ensuring the body runs at least once: do { statements } while (condition); This is useful for menu-driven programs where you want to display the menu once and then repeat only if the user chooses to continue.

Control statements: break and continue
break exits the loop immediately and transfers control after the loop; continue skips the rest of the current iteration and proceeds to the next iteration. Use these sparingly to avoid confusing loop logic. For example, use continue to skip invalid items while summing a list, or break when a search finds the desired element.

Avoiding infinite loops
An infinite loop occurs when the loop condition never becomes false. Ensure loop variables are updated correctly and that conditions will eventually fail. Use print statements or a debugger to inspect progress when a loop does not behave as expected.

Common loop patterns

  • Traversing arrays: for (int i = 0; i < arr.length; i++) { process arr[i]; }
  • Accumulation: int sum=0; for (...) sum += value;
  • Sentinel-controlled input: while (value != sentinel) { process; read next; }

Practical tips
Prefer for loops for indexed traversals and enhanced for loops for simple iteration over collections: for (int x : arr) { ... } When modifying a collection while iterating, use an iterator or iterate backwards by index to avoid skipping elements.

Summary
Loops are powerful tools for data processing. Understanding when to use each loop type and how to control them safely will make your programs more efficient and correct.

📌 Examples
  • for (int i = 1; i <= 10; i++) { System.out.println(i); } // prints 1 to 10
  • int sum = 0; int x = sc.nextInt(); while (x != -1) { sum += x; x = sc.nextInt(); } // reads until -1 sentinel
🧮 Formulas
  1. For: for (initialisation; condition; update) { statements }
  2. While: while (condition) { statements }
  3. Do-while: do { statements } while (condition);
📊 Visual ideas
A flowchart loop showing condition -> if true run body and return to condition, if false exit
A for-loop timeline showing i values from start to end with update arrow
📊9

One-dimensional arrays for data storage

What is a one-dimensional array?
An array is a collection of values of the same type stored under a single name. A one-dimensional array holds items in sequence and is ideal for storing lists such as student marks, daily temperatures or inventory counts. Each element is accessed by an index starting from 0 up to length-1.

Declaring and creating arrays
To declare an array you state the type and use square brackets, for example: int[] marks; This only declares the variable. To allocate storage you use new with a size: marks = new int[30]; You can also declare and initialise in one step: int[] nums = {2, 4, 6, 8}; The size must be known or calculated at creation time.

Accessing and modifying elements
Use the index in square brackets to access or change elements: marks[0] = 75; int first = marks[0]; Always ensure the index is within 0..marks.length-1, otherwise an ArrayIndexOutOfBoundsException occurs. Use loops to read and write many elements efficiently.

Common operations on arrays
Typical operations include computing the sum or average, finding minimum or maximum values, counting elements that meet a condition, and copying or reversing arrays. Use a for loop or enhanced for loop to traverse elements. For example, to compute the sum: int sum = 0; for (int i = 0; i < arr.length; i++) sum += arr[i]; double avg = (double)sum / arr.length;

Passing arrays to methods
Arrays can be passed as parameters to methods to separate logic: public static int total(int[] a) { ... } Changes to array elements inside the method affect the original array because the method receives a reference to the same array.

Initial values and default contents
When you create an int[] array its elements are initialised to 0 by default. For other types defaults are 0.0 for double, false for boolean and null for object references. It is good practice to set meaningful initial values as needed.

Limitations and alternatives
An array’s size is fixed after creation. If you need a collection that grows or shrinks use ArrayList. Arrays are memory-efficient and fast for indexed access, making them suitable when size is known or can be computed beforehand.

Summary
Learning to use one-dimensional arrays is a key step toward handling larger datasets. Practice common patterns such as traversal, accumulation and indexing to become comfortable processing lists of data in Java.

📌 Examples
  • int[] marks = {78, 85, 62, 90, 71}; for (int i = 0; i < marks.length; i++) sum += marks[i];
  • int[] a = new int[4]; a[0] = 5; a[1] = 3; // access and assign by index
🧮 Formulas
  1. Declaration: type[] name = new type[size];
  2. Length: name.length gives array size
📊 Visual ideas
A row of boxes labelled arr[0], arr[1], arr[2] ... with indexes below each box
A loop arrow walking across the boxes from index 0 to index length-1
💻10

Two-dimensional arrays and simple tables

Two-dimensional arrays as grids
A two-dimensional (2D) array represents data in rows and columns like a table or matrix. It is declared with two sets of brackets and each element is accessed using two indices: name[row][col]. 2D arrays are useful for seating plans, timetables, marks for several subjects, or small matrices in math problems.

Declaration, creation and initialisation
Example: int[][] marks = new int[5][3]; creates 5 rows and 3 columns. You can initialise with nested lists: int[][] mat = {{1,2,3}, {4,5,6}, {7,8,9}}; Access element at row r and column c with mat[r][c]. Rows and columns both use zero-based indexing. To find row count use mat.length and column count use mat[0].length for rectangular arrays.

Navigating with nested loops
Process all elements with nested loops: for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[i].length; j++) { // process mat[i][j] } } The outer loop iterates rows and the inner loop iterates columns. Use nested loops to compute row totals, column totals, or to print the table neatly.

Rectangular versus jagged arrays
2D arrays are often rectangular, but Java allows jagged arrays where each row can have a different length. This is useful if data per row varies, such as variable numbers of exam marks per student.

Common tasks and examples
Typical operations include summing each row to get student totals, summing each column for class averages per subject, finding the maximum mark and its coordinates, or transposing a matrix. When printing, format columns so numbers line up for readability.

Memory and performance
2D arrays require more memory; choose sizes according to problem constraints. For large matrices consider more advanced techniques, but for typical class examples a few rows and columns suffice to learn the pattern.

Practical advice
Always check indices to avoid out-of-bounds errors and prefer mat.length and mat[i].length rather than hard-coded numbers. Test nested loops on small examples and print intermediate values to understand traversal order.

Summary
Two-dimensional arrays let you model tabular data naturally. Practice nested loops and common operations like row/column sums to build confidence in handling tables of data.

📌 Examples
  • int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; for (int i=0;i<matrix.length;i++) for (int j=0;j<matrix[i].length;j++) System.out.print(matrix[i][j]+" ");
  • int[][] marks = new int[3][4]; // 3 students, 4 subjects: populate and compute each student's total
🧮 Formulas
  1. Declaration: type[][] name = new type[rows][cols];
  2. Row count: array.length, Column count: array[0].length (for rectangular arrays)
📊 Visual ideas
A grid diagram with rows and columns labelled and a highlighted element at [2][1]
Nested-loop flow: outer loop for rows, inner loop for columns with arrows showing traversal order
💻11

Strings and text processing

Understanding strings
Strings are sequences of characters used to store text. In Java, String is a class whose objects represent text. String literals are enclosed in double quotes: "Hello". Strings are immutable: methods that seem to change a string actually return a new String object. This immutability has consequences for performance when building long strings in loops; in such cases use StringBuilder for efficiency.

Common String methods
Important methods include length() which returns the number of characters, charAt(index) to get a single character, substring(start, end) to extract a portion, indexOf(sub) to find the position of a substring, equals() and equalsIgnoreCase() to compare text, toUpperCase()/toLowerCase() to change case, and trim() to remove leading and trailing spaces. split(regex) divides a string into tokens based on a pattern such as a comma or space.

Concatenation and formatting
Join strings using +, for example first + " " + last. For formatted output use String.format or System.out.printf: System.out.printf("%s scored %d\n", name, marks); This allows control over spacing and numeric precision. To convert numbers to strings use String.valueOf(number) or simply number + "".

Parsing and conversion
To use numeric values stored as text, parse them: Integer.parseInt(s) converts a string to int, Double.parseDouble(s) to double. Parsing may throw NumberFormatException for invalid input, so handle parsing inside try-catch blocks or validate the string before conversion.

Tokenising and processing lines
When reading a line of data such as CSV (comma-separated values), use split(",") to get fields or Scanner with a delimiter. After tokenising, trim whitespace and convert field types as needed. Normalise case with toLowerCase() or toUpperCase() before comparing to make checks case-insensitive.

Searching and manipulation
Use indexOf to search substrings and contains() to check presence. Replace parts of a string with replace(old, new) or replaceAll with regular expressions for more powerful replacements. For counting words, split on whitespace and count tokens, taking care to skip empty tokens.

Efficiency tips
Avoid repeated string concatenation inside large loops; prefer StringBuilder which allows appending efficiently. Reuse parsed values when possible and avoid unnecessary creation of temporary strings.

Summary
String methods give you tools to validate, search, split and format text data. Text processing is vital in data processing tasks like reading CSV files, validating input and creating readable reports.

📌 Examples
  • String s = "Hello World"; System.out.println(s.length()); System.out.println(s.substring(6)); // prints "World"
  • String line = "Rita,85,92"; String[] parts = line.split(","); // parts[0] = "Rita"
🧮 Formulas
  1. Length: s.length()
  2. Substring: s.substring(start, end), Index start inclusive, end exclusive
  3. Compare: s.equals(t) for exact match
📊 Visual ideas
A string shown as a sequence of character boxes with indices 0..n-1 below
A diagram showing split() dividing a line into tokens
💻12

Methods (functions): parameters, return values and modular code

Why use methods?
Methods break a program into smaller units, each performing a specific task. This modular approach improves readability, makes testing easier and avoids duplication of code. For example, a method to compute average can be reused wherever an average is needed. Well-named methods describe their purpose and clarify the main program flow.

Method structure and syntax
A method has a declaration with modifiers, return type, name and parameter list, followed by a body enclosed in braces. Example: public static int sumArray(int[] a) { int s = 0; for (int i = 0; i < a.length; i++) s += a[i]; return s; } The return type indicates the type of value the method sends back to the caller; use void if nothing is returned.

Parameters, arguments and pass-by-value
Parameters are variables listed in the method header. When you call a method you provide arguments. Java uses pass-by-value: for primitive types the actual value is copied; for objects and arrays the reference is copied but still points to the same object. Therefore a method can modify the contents of an array parameter but cannot change the caller's reference to point to a new array.

Designing good methods
Each method should do one clear job: readData(), computeResults(), printReport(). Keep methods short and focused. Give methods descriptive names and document their purpose, parameters and return values with comments. Avoid methods that depend on global state; prefer passing required data via parameters.

Overloading and reuse
Java allows method overloading: methods with the same name but different parameter lists. This is useful when similar operations are needed for different types, for example print(String s) and print(int n). Overloading improves readability by using the same action name for related tasks.

Testing methods independently
Test helper methods separately with known inputs to ensure they return correct outputs before integrating them into the main program. This reduces debugging time because errors are isolated to small parts of the program.

Practical examples in data processing
Create methods to validate input, compute averages, sort arrays, or read records from files. Use return values to pass results back and exceptions to report errors that cannot be handled locally. Modular design allows easier changes later, for instance replacing a sorting method without changing other parts of the code.

Summary
Methods help you organise code, make it reusable and easier to understand. Mastering method design is essential for building larger, well-structured data processing programs.

📌 Examples
  • public static double average(int[] arr) { int s=0; for(int x:arr) s+=x; return (double)s/arr.length; }
  • public static void printMenu() { System.out.println("1.Add 2.Display 3.Exit"); } // no return value
🧮 Formulas
  1. Method syntax: [modifiers] returnType name(parameter-list) { // body }
  2. Return: use return expression; to send value back
📊 Visual ideas
A box labelled method with arrows in for parameters and an arrow out for the return value
Program structure diagram showing main calling helper methods like readData(), processData(), writeData()
💻13

Basic file input and output (text files)

Importance of files
Files allow a program to store data permanently so information can be reused across runs. Text files are easy to create and inspect with a text editor, which makes them suitable for storing simple records, lists and configuration data. In data processing tasks you will often read input from a file and write results or reports back to another file.

Reading text files with Scanner
Use java.io.File together with Scanner to read files: Scanner sc = new Scanner(new File("input.txt")); Then read tokens or lines with sc.next() or sc.nextLine(). Common practice is to loop while sc.hasNextLine() and process each line. Reading files may throw FileNotFoundException, so surround the code with try-catch to handle the case where the file does not exist.

Writing text files with PrintWriter and FileWriter
To write text, use PrintWriter or FileWriter. Example: PrintWriter out = new PrintWriter(new File("output.txt")); out.println("Hello"); out.close(); By default PrintWriter overwrites the file. To append, use FileWriter(file, true) wrapped by PrintWriter. Always close streams to flush data to disk. Writing operations can throw IOException, so handle them appropriately.

Choosing formats
Decide on a simple format for records such as CSV (comma-separated values) where each line represents a record and fields are separated by commas. For example: Rita,85,92. When reading back, use split(",") to separate fields. Avoid using commas in field values unless you implement quoting rules; keep formats simple for class exercises.

Handling resources safely
Files may fail due to missing permissions, incorrect names, or full disks. Use try-catch-finally blocks to close resources in finally, or preferably try-with-resources where the stream is closed automatically after the try block. Always give the user a helpful message if a file cannot be opened.

Validation when reading
Validate file contents for expected structure: correct number of fields, numeric fields parse correctly, and values are in acceptable ranges. If an invalid line is found, skip it with a warning or attempt correction depending on the program’s purpose.

Examples of file tasks
Typical exercises include reading student records from a file, computing totals and averages, and writing a report to another file. Another example is reading a list of numbers, sorting them, and writing the sorted list to disk.

Summary
File I/O extends programs beyond the console and is essential for real data processing. Learn to read and write simple text formats, handle errors gracefully, and structure file operations so data remains reliable and easy to work with.

📌 Examples
  • Reading: Scanner sc = new Scanner(new File("marks.txt")); while (sc.hasNextLine()) { String line = sc.nextLine(); // process line } sc.close();
  • Writing: PrintWriter out = new PrintWriter(new File("report.txt")); out.println("Student,Total"); out.close();
🧮 Formulas
  1. Open file for reading: Scanner sc = new Scanner(new File("file.txt"));
  2. Open file for writing: PrintWriter out = new PrintWriter(new File("file.txt")); out.println(...); out.close();
📊 Visual ideas
A diagram showing Program -> File (input.txt) read by Scanner and Program -> File (output.txt) written by PrintWriter
A sample CSV line shown as fields separated by commas
💻14

Exception handling: try, catch and finally

What are exceptions and why handle them?
Exceptions are runtime events that indicate errors or unusual conditions, such as dividing by zero, trying to open a non-existing file, or accessing an array with an invalid index. If not handled, exceptions cause the program to terminate abruptly. Handling exceptions allows your program to respond, report the problem clearly and, where possible, continue safely or shut down gracefully.

Try and catch blocks
Wrap code that might throw an exception in a try block and follow it with one or more catch blocks specifying the exception type: try { // risky code } catch (ExceptionType e) { // handle error } Catch blocks execute only if an exception of the specified type occurs. Use specific exception types like FileNotFoundException or ArithmeticException where possible so you can handle each case appropriately.

Finally block for cleanup
The finally block runs after try and catch blocks whether an exception occurred or not. It is useful to release resources such as closing files or scanners: try { /* open file */ } catch (FileNotFoundException e) { /* handle */ } finally { /* close file */ } In later Java versions, try-with-resources is preferred because it automatically closes resources.

Checked vs unchecked exceptions
Checked exceptions (e.g., IOException) must be declared or handled; the compiler enforces this. Unchecked exceptions (RuntimeException and subclasses) such as NullPointerException or ArrayIndexOutOfBoundsException usually indicate programming errors and should be prevented with correct logic. Handle checked exceptions where recovery or a user message is appropriate.

Good practices when handling exceptions

  • Catch specific exceptions rather than a single generic Exception to avoid masking bugs.
  • Provide helpful messages to the user, not cryptic stack traces.
  • Log details for debugging while showing a simple message to the user.
  • Do not use exceptions for normal control flow; they are for exceptional conditions.

Examples and usage
When reading a file, catch FileNotFoundException to inform the user and possibly request a different file. When parsing integers from text, catch NumberFormatException and prompt for correction. For arithmetic operations, catch ArithmeticException for divide-by-zero cases and handle them appropriately.

Summary
Exception handling makes programs more robust and user-friendly. Learn to identify points where exceptions may occur and handle them cleanly with try, catch and finally so your data processing programs are reliable.

📌 Examples
  • try { Scanner sc = new Scanner(new File("data.txt")); } catch (FileNotFoundException e) { System.out.println("File not found"); }
  • try { int x = a / b; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Attempted division"); }
🧮 Formulas
  1. Try-catch: try { /* code */ } catch (Type e) { /* handler */ } finally { /* cleanup */ }
📊 Visual ideas
A flow showing try block then either normal exit or exception path to catch, then finally always runs
A diagram of a resource opened in try and closed in finally
📊15

Basic collections: ArrayList for dynamic data

Why use collections instead of arrays?
Arrays have a fixed size determined at creation. For many real tasks you do not know how many items will appear beforehand—for example reading lines from a file until the end. Collections like ArrayList provide dynamic sizing: they grow and shrink at runtime and offer useful methods for adding, removing and accessing elements.

ArrayList basics
ArrayList is part of the java util package. Create an ArrayList for a specific type of element, for example an ArrayList that stores integers or strings. The type parameter ensures all elements are of the same type and removes the need for casting. Use add(value) to append an element, get(index) to retrieve an element, set(index, value) to replace, remove(index) to delete, and size() to get the current number of elements.

Iterating over an ArrayList
You can iterate with a standard for loop using indices: for (int i = 0; i < list.size(); i++) { Integer v = list.get(i); } or use an enhanced for loop: for (Integer v : list) { // use v } When removing elements while iterating, use an Iterator or iterate backwards by index to avoid skipping elements caused by shifts.

Useful methods and features
ArrayList supports contains(element) to check presence, indexOf(element) to find the first index, clear() to remove all elements, and add(index, element) to insert at a position. It manages resizing automatically and stores elements in order of insertion by default.

Performance considerations
Adding at the end is generally efficient, but inserting or removing in the middle requires shifting elements and can be slower. For class 9, focus on correct usage rather than deep performance details. Use ArrayList when flexibility is needed and arrays when a fixed-size structure is sufficient and slightly more efficient.

Converting between arrays and lists
You can convert an array to a list and vice versa if needed. For small programs, choose the structure that simplifies the logic. Use ArrayList when dealing with unknown counts of data such as lines from a file or user entries.

Summary
ArrayList simplifies handling collections with variable sizes. Learn to add, access, remove and iterate elements, and be careful when modifying the list during iteration.

📌 Examples
  • ArrayList of String names = new ArrayList(); names.add("Asha"); names.add("Vik"); for(String s : names) System.out.println(s);
  • ArrayList of Integer nums = new ArrayList(); nums.add(5); nums.add(10); nums.remove(0); // removes first element
🧮 Formulas
  1. Create: ArrayList of Type name = new ArrayList();
  2. Common methods: add(e), get(i), set(i,e), remove(i), size()
📊 Visual ideas
A row of boxes that can extend with arrows showing add() appending a new box at the end
A diagram showing conversion: array -> ArrayList and ArrayList -> array
💻16

Searching and simple sorting techniques

Searching methods
Searching locates a target value within a collection. The simplest method is linear search which inspects each element in sequence until the item is found or the end is reached. Linear search works on unsorted data and is easy to implement but can be slow for large collections (it checks up to n elements).

Binary search for sorted data
Binary search is an efficient method for sorted arrays. It maintains a low and high index and compares the target with the middle element. If equal, return mid; if target is smaller, search the left half by setting high = mid - 1; otherwise search the right half by setting low = mid + 1. Repeat until low > high. Binary search finds elements in O(log n) time, much faster than linear search on large sorted lists, but it requires the data to be sorted first.

Simple sorting algorithms
Selection sort repeatedly selects the minimum element from the unsorted portion and swaps it with the first unsorted position. Bubble sort repeatedly passes through the array, swapping adjacent out-of-order elements so larger values bubble towards the end. Both algorithms are easy to understand and implement but have worst-case time complexity O(n^2), making them inefficient for large lists.

Steps for selection sort
For i from 0 to n-2 find index min of the smallest element in i..n-1, then swap arr[i] and arr[min]. Repeat until the array is sorted. Selection sort does about n*(n-1)/2 comparisons and up to n swaps.

When to use built-in methods
Java provides efficient library methods such as sort functions in standard classes. These implement faster algorithms suitable for real tasks. However, implementing simple sorts by hand is useful for learning and understanding algorithm behaviour.

Choosing the right method
For small datasets or learning exercises use linear search and simple sorts. For larger datasets or performance-sensitive tasks, use binary search on sorted data and library sort methods. Always consider the cost of sorting before choosing binary search: sorting itself may be more expensive than a single linear search if you need only one search.

Summary
Searching and sorting are fundamental operations in data processing. Learn linear and binary search and implement simple sorts to build intuition about algorithm efficiency and practical trade-offs.

📌 Examples
  • Linear search: for (int i=0;i<arr.length;i++) if (arr[i]==key) return i;
  • Selection sort: for (i=0;i<n-1;i++) { min=i; for (j=i+1;j<n;j++) if (arr[j]<arr[min]) min=j; swap(arr,i,min); }
🧮 Formulas
  1. Binary search loop: while (low <= high) { mid = (low+high)/2; if target==arr[mid] return mid; else adjust low/high }
  2. Selection sort: for i from 0 to n-2 select min from i..n-1 and swap with i
📊 Visual ideas
A number line of array indices showing mid calculation and halves selected in binary search
A diagram showing passes of bubble sort with larger elements bubbling to the right
📊17

Using classes and simple objects for data records

Grouping related data into classes
When an item has several attributes it is clearer to group them in a class rather than using parallel arrays. For example, a student has a name, roll number and marks. A Student class bundles these fields and related methods (such as total or average) so each student record becomes an object with both data and behaviour. This approach reduces errors from mismatched arrays and makes code more expressive.

Defining a simple class
A class declares fields and methods and typically a constructor to create instances. Example: public class Student { public String name; public int roll; public int[] marks; public Student(String name, int roll) { this.name = name; this.roll = roll; } public int total() { int s=0; for (int m:marks) s+=m; return s; } } Fields can be public for simplicity in early learning, though later you will learn to make them private for encapsulation.

Creating and using objects
In main you create objects: Student s1 = new Student("Asha", 12); s1.marks = new int[]{78, 85}; int tot = s1.total(); Objects can be stored in arrays or a list of Student for processing multiple records. This allows operations like sorting students by total or searching by roll number using comparator logic on object fields.

Design considerations
Keep methods inside the class focused on tasks directly related to the record, such as computing totals, printing a formatted line or validating fields. Provide constructors that accept necessary initial values. When objects are stored in collections, provide methods to compare or represent them for sorting and display.

Advantages over parallel arrays
Using classes avoids errors where indices can get misaligned between arrays of names, rolls and marks. It makes code more intuitive because operations on a student live with the student’s data. This object-oriented style prepares you for larger programs and clearer data modelling.

Simple operations with objects
Common tasks include reading records from a file into a list of objects, computing derived values like totals, sorting by a field, and writing objects back to a file in a chosen format. Practice creating small classes and using them in programs to handle structured data effectively.

Summary
Classes let you model real-world records cleanly. Learning to design simple classes and use objects in arrays or lists is a major step toward writing organised data processing programs.

📌 Examples
  • class Book { String title; String author; double price; public Book(String t,String a,double p) { title=t; author=a; price=p; } } // create: Book b = new Book("Maths","Rao",195.0);
  • Student[] students = new Student[3]; students[0] = new Student("Rita",1); students[0].marks = new int[]{78,85};
🧮 Formulas
  1. Class with constructor: public class Name { fields; public Name(params) { this.field = param; } }
  2. Create object: ClassName obj = new ClassName(arguments);
📊 Visual ideas
A class box labelled Student with fields name, roll, marks and a constructor method; an object instance shown with specific values
An array of Student objects illustrated as boxes each containing a student record
📊18

Putting it together: designing a data processing program

From problem to program
Designing a data processing program begins with analysing the problem carefully: identify inputs, required processing steps and desired outputs. Write a list of inputs (type and source), outputs (format and destination) and any constraints such as valid ranges. Sketch a few sample inputs and expected outputs to validate your understanding before coding.

High-level design and decomposition
Divide the program into modules or methods with clear responsibilities: input reading, data validation, core processing, and output generation. For example, separate methods could be readData(), computeResults(), and writeReport(). This modular approach simplifies testing: you can test each method independently and then combine them.

Choosing data structures
Decide how to store data: use simple variables for single values, arrays for fixed-size lists, dynamic lists for variable-size collections and classes to represent records with multiple attributes. Choosing the proper structure simplifies processing and reduces the amount of code needed to manipulate data.

Flowcharts and pseudocode
Draw a flowchart or write pseudocode before implementing. A flowchart helps visualise the main branches and loops; pseudocode captures the algorithm in readable steps without language syntax. These artefacts are useful to show your approach to teachers and to debug logic before coding.

Validation and error handling
Include input validation to handle incorrect or missing data. Use try-catch for file and parsing errors and display user-friendly messages. Decide how to handle bad records: skip with a warning, request correction, or stop processing. Document these choices so users know program behaviour.

Testing strategy
Test with normal cases, boundary cases (empty input, very large values, minimums), and invalid cases. Unit-test small methods where possible. Use sample files and console input to verify results. Debug using print statements or an IDE debugger to inspect values during execution.

Putting features together
A complete example project might read student CSV records into a list of student objects, compute totals and grades with methods in Student, sort students by total using library sort, and write a ranked report to an output file. Each step corresponds to the modules designed earlier and keeps code well organised.

Documentation and maintenance
Comment your code to explain non-obvious steps and document assumptions. Use meaningful names for variables and methods. Clean, well-documented programs are easier to mark and maintain. Keep backups and versioned copies when making large changes.

Summary
Designing data processing programs combines problem analysis, modular code, appropriate data structures, validation and testing. Practise by building small projects such as a marks processor or inventory list to apply these concepts end-to-end.

📌 Examples
  • Design: read student CSV file -> parse into Student objects -> compute totals -> sort by total -> write report.csv
  • Pseudocode: readInput(); computeResults(); writeOutput(); where each is a separate method
🧮 Formulas
  1. Design pattern: Input -> Processing (methods/classes) -> Output
  2. Testing checklist: normal case, boundary case, invalid input
📊 Visual ideas
A high-level flowchart showing Read -> Process -> Sort -> Write
A module diagram showing main calling methods readData(), processData(), outputResults()

Key Concepts

Data processing
The sequence of reading input, transforming it with instructions, and producing output or stored results.
Primitive data type
A built-in type such as int, double, char or boolean that stores simple values.
Variable
A named storage location in memory that holds a value while a program runs.
Scanner
A Java class used to read input from the keyboard or files.
Array
A fixed-size collection of elements of the same type accessed by index.
ArrayList
A dynamic resizable list from java.util that can grow and shrink at runtime.
String
An object in Java that represents a sequence of characters.
Method
A named block of code that performs a task and may return a value.
Exception
An event signalling an error or unexpected condition during program execution.
File I/O
Reading from and writing to files for persistent storage of data.
Control structure
Statements like if, for and while that control the flow of execution.
Linear search
A search method that checks each element in sequence until a match is found.
Binary search
A fast search on sorted arrays that repeatedly halves the search interval.
Selection sort
A simple sorting algorithm that repeatedly selects the minimum element and places it in order.
Encapsulation (basic)
Grouping related data and methods in a class to represent a real-world entity.

Practice Questions

  1. Write a Java program to read three integers and print their sum. / तीन पूर्णांक पढ़कर उनका योग लिखने वाला Java प्रोग्राम लिखिए।
    Show answer

    English answer: Use Scanner to read three integers, add them and print the sum: Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); System.out.println(a+b+c); sc.close(); / हिंदी उत्तर: Scanner का उपयोग कर तीन पूर्णांक पढ़ें, उन्हें जोड़ें और योग प्रिंट करें: Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); System.out.println(a+b+c); sc.close();

  2. How do you declare and create an array of 10 integers in Java? / Java में 10 पूर्णांकों की एक array कैसे घोषित और बनाई जाती है?
    Show answer

    English answer: Declare with int[] arr = new int[10]; This creates space for 10 integers indexed 0 to 9. / हिंदी उत्तर: इस प्रकार घोषित करें: int[] arr = new int[10]; यह 0 से 9 तक index वाले 10 पूर्णांकों के लिए स्थान बनाता है।

  3. Explain the difference between next() and nextLine() in Scanner. / Scanner में next() और nextLine() के बीच अंतर समझाइए।
    Show answer

    English answer: next() reads the next token up to whitespace, while nextLine() reads the rest of the current line including spaces and consumes the newline. Mixing nextInt() and nextLine() can lead to skipping; consume the leftover newline before using nextLine(). / हिंदी उत्तर: next() अगला टोकन (whitespace तक) पढ़ता है, जबकि nextLine() वर्तमान पंक्ति की बाकी सामग्री (spaces सहित) पढ़ता है और newline को हटाता है। nextInt() और nextLine() को मिलाकर उपयोग करने पर लाइन छूट सकती है; इसलिए nextLine() से पहले बचे हुए newline को खपत कर लें।

  4. Describe how you would compute the average of values stored in an int[] array. / int[] array में स्थित मानों का औसत कैसे निकालेंगे, वर्णन कीजिए।
    Show answer

    English answer: Sum all elements using a loop, then divide the sum by the array length converting to double to avoid integer division: int sum=0; for(int i=0;i<arr.length;i++) sum+=arr[i]; double avg = (double)sum/arr.length; / हिंदी उत्तर: एक लूप से सारे तत्वों का योग करें और फिर कुल को array की length से विभाजित करें; integer division से बचने के लिए double करें: int sum=0; for(int i=0;i<arr.length;i++) sum+=arr[i]; double avg = (double)sum/arr.length;

  5. Write pseudocode or Java steps to read a text file line by line and print each line. / किसी टेक्स्ट फ़ाइल को पंक्ति दर पंक्ति पढ़कर प्रत्येक पंक्ति प्रिंट करने के लिए उप-कोड या Java चरण लिखिए।
    Show answer

    English answer: Use Scanner with File: try { Scanner sc = new Scanner(new File("input.txt")); while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println(line); } sc.close(); } catch (FileNotFoundException e) { System.out.println("File not found"); } / हिंदी उत्तर: Scanner और File का उपयोग करें: try { Scanner sc = new Scanner(new File("input.txt")); while (sc.hasNextLine()) { String line = sc.nextLine(); System.out.println(line); } sc.close(); } catch (FileNotFoundException e) { System.out.println("File not found"); }

  6. What is the output of the following code fragment? int a = 7/2; double b = 7/2; double c = 7.0/2; System.out.println(a + " " + b + " " + c); / निम्नलिखित कोड का आउटपुट क्या होगा? int a = 7/2; double b = 7/2; double c = 7.0/2; System.out.println(a + " " + b + " " + c);
    Show answer

    English answer: Integer division 7/2 is 3. So a = 3, b = 3.0 (int result converted to double), c = 3.5. The printed line: 3 3.0 3.5 / हिंदी उत्तर: 7/2 का पूर्णांक भाग 3 है। इसलिए a = 3, b = 3.0 (double में बदल कर), c = 3.5। प्रिंट: 3 3.0 3.5

  7. Give a simple example where you would use a class to store records instead of parallel arrays. / किसी स्थिति का सरल उदाहरण दें जहाँ आप parallel arrays की बजाय records को स्टोर करने के लिए class का उपयोग करेंगे।
    Show answer

    English answer: For student data with name, roll and marks use a Student class with fields name, roll and marks array. Create Student objects and store them in an ArrayList of Student. This avoids keeping separate arrays for names, rolls and marks which can get out of sync. / हिंदी उत्तर: नाम, रोल और मार्क्स वाले छात्र डेटा के लिए Student class बनाएं जिसमें fields name, roll और marks हों। Student ऑब्जेक्ट बनाकर उन्हें ArrayList of Student में रखें। इससे अलग-अलग arrays (names[], rolls[], marks[]) रखने की समस्या नहीं होगी।

  8. Describe how selection sort works and give its worst-case time complexity. / Selection sort कैसे काम करता है और इसका worst-case time complexity क्या है, वर्णन कीजिए।
    Show answer

    English answer: Selection sort repeatedly finds the minimum element from the unsorted part and swaps it with the first unsorted position, moving the boundary one step. It does about n*(n-1)/2 comparisons in the worst case, so time complexity is O(n^2). / हिंदी उत्तर: Selection sort असॉर्टेड भाग से न्यूनतम तत्व ढूंढकर उसे पहले असॉर्टेड स्थान के साथ स्वैप करता है और सीमा को बढ़ाता है। worst case में लगभग n*(n-1)/2 तुलनाएँ होती हैं इसलिए समय जटिलता O(n^2) है।

  9. How would you handle invalid numeric input entered by the user to avoid the program crashing? / उपयोगकर्ता द्वारा दर्ज अवैध संख्यात्मक इनपुट से प्रोग्राम क्रैश न हो इसके लिए आप कैसे हैंडल करेंगे?
    Show answer

    English answer: Surround input reading with try-catch to catch InputMismatchException, show an error message and prompt again. Alternatively read as a line and use Integer.parseInt inside try-catch to validate. Example: try { int x = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Enter a valid integer"); sc.nextLine(); } / हिंदी उत्तर: इनपुट पढ़ने वाले को try-catch में रखें और InputMismatchException पकड़ कर उपयोगकर्ता को त्रुटि संदेश दिखाएं और पुनः विनती करें। विकल्प के रूप में पंक्ति के रूप में पढ़कर Integer.parseInt को try-catch में उपयोग करें। उदाहरण: try { int x = sc.nextInt(); } catch (InputMismatchException e) { System.out.println("Enter a valid integer"); sc.nextLine(); }

  10. Write a function signature in Java for a method that takes an array of integers and returns the index of the largest element. / उस method का Java में function signature लिखिए जो int के array को ले और सबसे बड़े तत्व का index लौटाए।
    Show answer

    English answer: public static int indexOfMax(int[] arr) { /* body returns index */ } The method returns -1 for empty array or the index of the maximum value. / हिंदी उत्तर: public static int indexOfMax(int[] arr) { /* body returns index */ } यह method खाली array के लिए -1 लौटा सकता है या अधिकतम मान का index दे सकता है।

Related Laws & Principles

Explore all

Foundational laws & principles connected to this chapter — tap to open in the Laws Explorer.

Loading related laws…
Sourced from 0 content files · LLOS Learn · browse all chapters