Programming Fundamentals in Java
1. Review: Java Basics
A quick recap of basic concepts (originally covered in 1st Year):
- Variables & Data Types: Primitives include
int,float,double,char,boolean. A variable is a named memory location. - Operators: Arithmetic (+, -, *, /, %), Relational (==, !=, >, <), Logical (&&, ||, !), and Assignment (=).
- Control Structures:
- Conditional:
if/else,switch. - Looping:
for,while,do-while.
- Conditional:
2. Access Specifiers (Modifiers)
Definition: Access specifiers are keywords in Object-Oriented Programming that control the visibility or accessibility of class members (variables and methods) from other parts of a program.
There are four access specifiers in Java:
- public: Accessible from anywhere. It has the widest scope (same class, same package, subclass, different package).
- private: Accessible only within the same class. Used for data hiding and encapsulation.
- protected: Accessible within the same class, same package, and by subclasses (even if the subclass is in a different package). Vital for inheritance.
- default (Package-Private): When no keyword is specified. Accessible only within classes of the same package.
| Access Specifier | Same Class | Same Package | Subclass (Different Package) | Different Package |
|---|---|---|---|---|
public |
Yes | Yes | Yes | Yes |
protected |
Yes | Yes | Yes | No |
| default (no modifier) | Yes | Yes | No | No |
private |
Yes | No | No | No |
3. Classes and Objects
Class: A blueprint or template that defines the attributes (data members) and behaviors (methods) of an entity.
Object: An instance of a class. It is the actual physical or logical entity occupying memory.
class Student {
private int rollno; // private data member
String name; // default access
public int marks; // public data member
public void display() { // public method
System.out.println(rollno + " " + name + " " + marks);
}
}
// Creating an object:
Student s1 = new Student();
s1.name = "Rohan";
s1.marks = 90;
s1.display();
- Constructor: A special method with the exact same name as the class and no return type. It is called automatically when an object is created to initialize it.
- Default Constructor: Created by Java if no constructor is explicitly defined.
- Parameterized Constructor: Takes parameters to initialize an object with specific values.
thiskeyword: Refers to the current object invoking the method or constructor. Helpful in resolving naming collisions between instance variables and parameters.
4. Encapsulation
Definition: The mechanism of wrapping data (variables) and code acting on that data (methods) together as a single unit (class). It is the basis for data hiding.
- Data Hiding: Achieved by declaring class variables as
private. - Getter Methods: A
publicmethod used to read the value of a private variable (e.g.,getRollno()). - Setter Methods: A
publicmethod used to write/update the value of a private variable (e.g.,setRollno(int r)).
5. Inheritance
Definition: The mechanism by which one class acquires the properties and methods of another class. It promotes the "IS-A" relationship and enables code reusability.
- Superclass (Parent class): The class whose properties are inherited.
- Subclass (Child class): The class that inherits. It uses the
extendskeyword.
class Animal { // Superclass
String name;
public void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal { // Subclass
public void bark() {
System.out.println("Woof!");
}
}
// Dog object uses inherited and own methods:
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Own method
Types of Inheritance in Java:
- Single Inheritance: Class B extends Class A.
- Multilevel Inheritance: Class C extends Class B, which extends Class A.
- Hierarchical Inheritance: Class B and Class C both extend Class A.
- Multiple Inheritance: NOT supported directly in Java for classes to prevent ambiguity (the Diamond Problem). It is implemented using interfaces instead.
- Method Overriding: When a subclass redefines a method present in the superclass with the exact same signature (name and parameters). Usually denoted with the
@Overrideannotation. superkeyword: Used to refer to the immediate parent class object.super()invokes the parent class constructor.super.method()calls a parent class method.
6. Commonly Used Java Libraries
a) String Class Methods (java.lang.String)
Strings in Java are objects and are immutable (cannot be changed once created).
| Method Syntax | Description | Example |
|---|---|---|
toString() |
Returns the string representation of an object. | Integer.toString(42) → "42" |
concat(String s) |
Appends s to the end of the string. |
"Next".concat("Note") → "NextNote" |
length() |
Returns total number of characters. | "CHSE".length() → 4 |
toLowerCase() |
Converts all characters to lowercase. | "ODISHA".toLowerCase() → "odisha" |
toUpperCase() |
Converts all characters to uppercase. | "java".toUpperCase() → "JAVA" |
trim() |
Removes leading and trailing whitespace. | " Exam ".trim() → "Exam" |
substring(int beginIndex) |
Returns substring from beginIndex to end. | "Information".substring(4) → "rmation" |
substring(int begin, int end) |
Returns substring from begin to (end - 1). | "Information".substring(0, 4) → "Info" |
charAt(int index) |
Returns character at the specified index. | "HTML".charAt(1) → 'T' |
equals(String s) |
Checks content equality (case-sensitive). | "A".equals("a") → false |
Other notable string methods: indexOf(String s), equalsIgnoreCase(String s), replace(old, new), contains(String s), startsWith(s) / endsWith(s).
b) Math Class Methods (java.lang.Math)
Math.pow(double base, double exponent): Returns the value of the base raised to the power of the exponent.
Example:Math.pow(2, 3)returns8.0Math.round(double a): Rounds the argument to the nearest whole integer (returns along).
Example:Math.round(3.7)returns4.Math.round(3.4)returns3.- Other methods:
Math.sqrt(n)(square root),Math.abs(n)(absolute positive value),Math.max(a,b),Math.min(a,b).
7. Accessing Database using JDBC/ODBC
| Feature | ODBC (Open Database Connectivity) | JDBC (Java Database Connectivity) |
|---|---|---|
| Definition | Microsoft standard API for connecting to databases. | Java API (in java.sql package) specifically for Java programs. |
| Language Dependency | Language independent, mainly used for C/C++ on Windows. | Platform independent, strictly for Java applications. |
| Drivers | Requires OS-level database specific ODBC driver. | Requires database specific JDBC driver (usually a .jar file). |
Steps for JDBC Connection in Java:
- Load the Driver:
Class.forName("com.mysql.cj.jdbc.Driver"); - Establish Connection:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "user", "pass"); - Create Statement:
Statement stmt = con.createStatement(); - Execute Query:
ResultSet rs = stmt.executeQuery("SELECT * FROM student"); - Process Results: Loop through using
while(rs.next()) { ... } - Close Connection:
rs.close(); stmt.close(); con.close();
PreparedStatement allows pre-compiled SQL queries with ? placeholders. It offers better performance and prevents SQL Injection attacks.
HTML Based Web Pages
1. Introduction to HTML
HTML (HyperText Markup Language) is a markup language used for creating and structuring web pages. It is NOT a programming language (it lacks logic like loops and if/else).
- Uses tags wrapped in angle brackets:
<tagname>content</tagname>. - It is case-insensitive, but lowercase is recommended (standard in HTML5).
- Attributes provide additional information and are written as key="value" inside the opening tag.
2. Basic HTML Document Structure
<!DOCTYPE html> <!-- HTML5 Document declaration -->
<html lang="en"> <!-- Root element -->
<head> <!-- Metadata section (invisible) -->
<title>Page Title</title>
<meta charset="UTF-8">
</head>
<body> <!-- Visible page content goes here -->
<h1>Welcome</h1>
</body>
</html>
3. Text Formatting Tags
| Tag | Purpose |
|---|---|
<h1> to <h6> | Headings. h1 is the largest/most important; h6 is the smallest. Only use one h1 per page. |
<p> | Paragraph. Adds top and bottom margin automatically. |
<br> | Line break. It is a self-closing (empty) tag. |
<hr> | Horizontal rule (separator line). Attributes: width, size, color. |
<b> / <strong> | Bold text. (Strong implies high importance semantically). |
<i> / <em> | Italicized text. (Em implies emphasis semantically). |
<u> | Underlined text. |
<sub> / <sup> | Subscript (H2O) and Superscript (x2). |
<pre> | Preformatted text. Preserves whitespace, line breaks, uses a monospace font. |
4. Font Tag (Legacy)
The <font> tag is used to change text appearance. Note: Deprecated in modern HTML in favor of CSS.
Syntax: <font face="Arial" size="4" color="red">Text</font>
- face: The font family name.
- size: Values range from 1 to 7.
- color: Named color or hex code (#FF0000).
5. Hyperlinks and Images
Links (Anchor Tag): <a href="URL">Click Here</a>
- href: Specifies the destination URL (absolute or relative path).
- target="_blank": Opens the link in a new tab.
- mailto: Used for emails (e.g.,
href="mailto:[email protected]").
Images: <img src="image.jpg" alt="Description" width="300" height="200">
- src: The path to the image file.
- alt: Alternative text displayed if the image fails to load (essential for accessibility and SEO).
- The
imgtag is self-closing; no</img>required.
6. Tables
Tables are created using the <table> element.
<tr>: Defines a table row.<th>: Defines a header cell (bold and centered by default).<td>: Defines a standard data cell.colspan/rowspan: Attributes used to merge columns or rows respectively.<caption>: Sets the title of the table.
7. HTML Lists
- Unordered List (
<ul>): Displays items with bullets.
Attribute:type="disc|circle|square" - Ordered List (
<ol>): Displays items with numbers/letters.
Attributes:type="1|A|a|I|i",start="number". - Definition List (
<dl>): A dictionary-like list. Uses<dt>for the term and<dd>for the description.
8. HTML Forms
The <form> element collects user input. Key form attributes:
- action: The URL of the script that processes the form submission (e.g., "submit.php").
- method: Specifies how to send form data.
| Feature | GET Method | POST Method |
|---|---|---|
| Data Visibility | Data appended to URL (visible to everyone). | Data sent inside the HTTP body (hidden). |
| Security | Low (Not for passwords or sensitive data). | High (Suitable for sensitive data). |
| Data Limit | Limited (approx. 2000 characters). | No size restrictions. |
| Usage | Safe for searching/retrieving data. | Used for updating, inserting, or file uploads. |
Important Form Controls:
<input type="text">: Single-line text.<input type="password">: Masks typed characters.<input type="radio">: Radio button. Mutually exclusive selection (ensure they share the samename).<input type="checkbox">: Multiple selection boxes.<textarea rows="5" cols="40"></textarea>: Multi-line text field.<select>&<option>: Creates a dropdown list.<input type="submit">&<input type="reset">: Buttons to send or clear data.<input type="hidden">: Stores data invisibly to be sent to the server.
9. DHTML (Dynamic HTML)
DHTML is not a language but a combination of technologies—HTML, CSS, and JavaScript—used to create interactive and animated web sites.
- It modifies the page content dynamically without reloading the page.
- DOM (Document Object Model): JavaScript uses the DOM tree to access and alter elements.
Example:document.getElementById("myText").innerHTML = "Hello"; - Event Handlers: JavaScript functions triggered by user actions. Examples:
onclick,onmouseover,onmouseout,onkeyup,onload.
10. XML (Extensible Markup Language)
XML is designed to store and transport data, unlike HTML which is designed to present data.
- It is self-descriptive and uses user-defined tags (you invent your own tags like
<student>). - Well-formed XML Rules:
- Must have exactly one root element.
- All tags must be properly closed and properly nested.
- Tags are strictly case-sensitive.
- Attribute values must always be enclosed in quotes.
| HTML | XML |
|---|---|
| Used for formatting and displaying data. | Used for storing and transporting data. |
Has predefined tags (e.g., <p>, <table>). |
Has user-defined tags (extensible). |
| Case-insensitive. | Strictly case-sensitive. |
| Lax syntax (unclosed tags sometimes work). | Strict syntax (must be "well-formed"). |
Key Exam Points (Unit 2)
- The default access specifier is applied when no keyword is used; it allows package-level access.
- Multiple inheritance in Java is NOT supported for classes to avoid the diamond problem. It is achieved via Interfaces.
thisrefers to the current object, whilesuperrefers to the parent class object.- String methods
substring(start, end)stops at end - 1. Example:substring(0,3)on "CHSE" returns "CHS". Math.round(4.5)returns 5, whereasMath.round(4.4)returns 4. Result type islong.- JDBC prevents SQL injection by utilizing
PreparedStatementover regularStatement. - HTML is a markup language, not a programming language. It doesn't contain logical operators.
- The
altattribute in<img>is compulsory for accessibility and broken links. colspanmerges columns (horizontally),rowspanmerges rows (vertically).- A form
GETmethod appends data to the URL. UsePOSTfor sensitive/large data. - Radio buttons must share the exact same
nameattribute to be mutually exclusive. - A well-formed XML document strictly requires one single root element and case-sensitive matching tags.
Official CHSE Odisha IT Question Bank — Unit 2 Solved Paper
Complete exam-oriented solutions (Paper-I & Paper-II) with textbook errata corrections for Class 12 Board Exams.Paper-II Full Long Subjective Answers (CHSE Board Pattern)
Below are five fundamental HTML tags with syntax and clear exam explanations:
<html>...</html>(Root Tag): Encloses the entire HTML web page document. Browser treats everything inside as HTML markup.<head>...</head>(Document Header): Contains metadata not rendered directly in the viewport (<title>,<meta>,<style>).<title>...</title>(Page Title): Sets the document title displayed in the browser tab bar and search engine bookmarks.<body>...</body>(Document Body): Holds all visible page elements — headings, paragraphs, images, tables, forms, and links.<p>...</p>(Paragraph Tag): Formats blocks of prose text with automatic vertical spacing before and after each paragraph.
<html>
<head><title>CHSE Odisha Class 12 IT</title></head>
<body bgcolor="#f8fafc">
<h1>Welcome Students</h1>
<p>This is a complete HTML document structure.</p>
</body>
</html> Definition: Access Modifiers (Specifiers) in Java control who can access a class, constructor, variable, or method, enforcing encapsulation and data hiding.
| Modifier | Same Class | Same Package | Subclass (Diff Pkg) | World / Everywhere |
|---|---|---|---|---|
private | Yes | No | No | No |
default (none) | Yes | Yes | No | No |
protected | Yes | Yes | Yes (via inheritance) | No |
public | Yes | Yes | Yes | Yes |
package school;
public class Student {
private int secretPin = 1234; // only inside Student
int rollNo = 101; // default: package school only
protected String grade = "A+"; // school + external subclasses
public String name = "Aarav"; // accessible anywhere
} Inheritance allows a child class (subclass) to acquire fields and methods of an existing parent class (superclass) using the extends keyword, promoting code reusability.
- 1. Single Inheritance: One subclass inherits from one superclass (
A → B). Example:class Dog extends Animal {}. - 2. Multilevel Inheritance: A chain of inheritance (
A → B → C). Example:Vehicle → Car → ElectricCar. - 3. Hierarchical Inheritance: Multiple subclasses share one common parent (
A → BandA → C). - 4. Multiple & 5. Hybrid Inheritance (via Interfaces only): Java prohibits multiple class inheritance (to avoid the diamond ambiguity), so classes achieve multiple/hybrid inheritance by implementing multiple
interfaces viaimplements.
class Animal { void eat() { System.out.println("Eating..."); } }
class Dog extends Animal { void bark() { System.out.println("Barking"); } } // Single
class Puppy extends Dog { void weep() { System.out.println("Weeping"); } } // Multilevel Solved Paper-I Workbook Questions — MCQs, Blanks & 1-Mark (83 Qs) Click to Toggle
new A() instantiation (used in Singleton / utility classes).public, static, and final (a class constant).final keyword to a class declaration (e.g., final class String) prevents any subclass from extending it.extends.class)extends keyword for class-to-class inheritance (implements is only for interfaces).super()) first so base fields are initialized before the subclass constructor executes.extends once + implements zero or more interfaces; an interface uses extends for parent interfaces.final class forbids inheritance; abstract and Object classes are specifically designed to be subclassed.final method CAN be inherited by child classes, but CANNOT be overridden by any subclass.super()).(a) and (c) are true while (b) is imprecise (protected is visible across the entire package AND all subclasses). Workbook key selects (d) All.final stops all subclassing (final and abstract cannot even be combined on a class!).java.lang.Object sits at the root of Java’s class hierarchy; every class inherits directly or indirectly from Object.Cloneable override Object.clone() to duplicate object fields.java.lang.Object is protected clone() (closest option is (d) with lowercase c). Workbook key mistakenly prints (c) Objectclone ().final keyword stops class inheritance, method overriding, and variable reassignment.abstract."CHSE".equalsIgnoreCase("chse") returns true.equalsIgoreCase()). In Java exams always write exact spelling: equalsIgnoreCase()."odisha".toUpperCase() returns "ODISHA"." Java ".trim() returns "Java".Math.abs(-15) returns 15.s1.compareTo(s2) returns < 0 if s1 < s2, 0 if equal, and > 0 if s1 > s2 (lexicographical Unicode comparison).s1.equals(s2) returns boolean true or false (strict case-sensitive character match)."Hello ".concat("IT") returns "Hello IT"."CHSE".charAt(1) returns 'H'.substring(startIndex) and substring(startIndex, endIndex) (stops at endIndex - 1)."notes.pdf".endsWith(".pdf") returns true (startsWith() checks prefixes).-1
1
1, 10 means 1 shared static copy and 10 per-object instance copies.public or package-private (default), never protected or private (only nested inner classes allow protected/private).<br> is an empty/void tag that inserts a single line break.<p>...</p> defines a paragraph block with top/bottom spacing.<br> and <hr> are empty (singular) tags, whereas <p>...</p> is a container tag (workbook key specifies (a)).<b> and semantic <strong> render text in bold..gif, .jpg/.jpeg, .png, .svg, .webp, NOT Kodak Photo CD .pcd.<img> elements per document.X<sup>n</sup> displays superscripts/exponents; <sub> displays subscripts like H<sub>2</sub>O.mailto: URI scheme inside <a href="..."> launches the default email client."[email protected]"; standard valid HTML requires href="mailto:[email protected]".<h1> (largest) down to <h6> (smallest).(d) (<h6>), contradicting Q47 on the very next page ("What represents the largest heading tag? <h1>"). The true largest heading is (a) <h1>!<font> supports color, size, and face (bgcolor belongs to <body> or <table>).<li> (List Item) works identically inside both <ol> (Ordered) and <ul> (Unordered) lists.<ol> inside both <ul> and <ol>, starting with <ol> and ending with </ol>.<input> supports checkbox, radio, submit, and reset.<img src="pic.jpg" alt="Description">.<strong> emphasizes strong importance and renders in bold.<img> is a singular/empty tag with no closing </img> tag..html pages.name="value" pairs controlling tag behavior.<tag> and a closing </tag>.<hr> draws a thematic horizontal divider line across the page.<head> describes the document rather than appearing inside the document canvas.<head>...</head> section holds metadata, <title>, <style>, and <meta> not rendered in the page body.<hr> creates a horizontal thematic break.<html> is the root container element enclosing <head> and <body>.<ol> defines ordered/numbered lists, <ul> defines unordered/bulleted lists, and <li> defines each list item.< ... > angle brackets.<body vlink="purple">).link (unvisited), alink (active while clicked), and vlink (already visited).<a> with its href attribute (<a href="page2.html">...</a>) [Workbook key writes <href>]<a href="URL">Link Text</a>.href is an attribute, not a standalone tag! Always write <a href="..."> in exams.<b>...</b><tag> and </tag>.<br>, <hr>, <img><h1> down to <h6>.<code> / CSS in HTML5).<h1> has the highest hierarchy/size and <h6> has the lowest.<h6> renders the smallest default browser heading font size.<h1> renders the largest default browser heading font size.Solved Paper-II Short Objective Questions (17 Qs) Click to Expand
1.
public — Accessible everywhere (same class, same package, subclasses, outside packages).2.
protected — Accessible within the same package AND in subclasses outside the package.3.
default (package-private, no keyword) — Accessible only to classes inside the same package.4.
private — Accessible strictly inside the declaring class only.• MySQL SQL:
SELECT SUBSTRING('hello', 2, 3); → Output: llo (1-indexed start=2, length=3).• Java String:
"hello".substring(1, 4); → Output: "ell" (0-indexed start=1 inclusive, end=4 exclusive).• Dynamic Web Pages: Content changes per user, time, or DB state; served by Web Server + Application Server (PHP/Java) + Database (MySQL).
LCASE(str) / LOWER(str): Converts all characters to lowercase. Example: SELECT LCASE('HELLO'); → 'hello'.•
UCASE(str) / UPPER(str): Converts all characters to uppercase. Example: SELECT UCASE('hello'); → 'HELLO'.RIGHT(str, n): Extracts the rightmost n characters. Example: SELECT RIGHT('hello', 3); → 'llo'.•
RTRIM(str): Removes trailing spaces from the right side of a string. Example: SELECT RTRIM('hello '); → 'hello'.<tagname>) that instruct the web browser how to structure, format, and display content.<br>, <hr>, <img>, <input>) perform standalone layout tasks and do not require an end/closing tag.<h1> (largest heading) down through <h2>, <h3>, <h4>, <h5>, to <h6> (smallest heading).<a> with the href attribute: <a href="https://nextnote.in">Visit NextNote</a>.Default link states: Unvisited = blue & underlined; Visited = purple; Active = red.
<table>...</table> along with <tr> (table row), <th> (header cell), and <td> (table data cell).<ol>): Numbered sequence (1, 2, 3 or A, B, C / I, II).2. Unordered List (
<ul>): Bulleted list (disc, circle, square), using <li> for items.3. Description List (
<dl>, <dt>, <dd>).<p> or </p>), whereas an HTML **Element** includes the opening tag + inner content + closing tag (<p>Hello</p>).<a href="..."> tag around BOTH text and images (<a href="page.html"><img src="btn.png"></a>).<marquee>Scrolling Text</marquee> is an HTML container tag used to automatically scroll text or images horizontally/vertically across a web page.background attribute inside the <body> opening tag right after </head>: <body background="image.gif"> (or modern CSS background-image: url('image.gif');).
Discussion & Queries 0
Post a Comment or Doubt