Skip to content

Java C Hash Python

1. Principles of Object-Oriented Programming

Section titled “1. Principles of Object-Oriented Programming”

OOP is a programming paradigm based on the concept of objects which contain data (attributes) and methods (functions). It focuses on modularity, reusability, and abstraction.

a) Encapsulation

  • Bundling of data and methods operating on that data into a single unit (class).
  • Restricts direct access to internal data; access controlled via getters/setters.
    Example (Java):
class Student {
private int rollNo;
public void setRollNo(int r){ rollNo = r; }
public int getRollNo(){ return rollNo; }
}

b) Inheritance

  • Mechanism to derive new classes (subclasses) from existing ones (superclasses).
  • Promotes code reusability and hierarchical classification.
    Example (C#):
class Animal {
public void eat() { Console.WriteLine("Eating"); }
}
class Dog : Animal {
public void bark() { Console.WriteLine("Barking"); }
}

c) Polymorphism

  • Ability of different classes to respond differently to the same function call.
  • Compile-time polymorphism: method overloading.
  • Runtime polymorphism: method overriding via inheritance.
    Example (Python):
class Shape:
def area(self): pass
class Circle(Shape):
def area(self): return "Area of Circle"

d) Abstraction

  • Hiding implementation details and showing only essential features.
  • Achieved using abstract classes and interfaces.
    Example (Java):
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw(){ System.out.println("Drawing Circle"); }
}
  • Modularity and maintainability
  • Code reusability via inheritance
  • Flexibility and scalability
  • Enhanced data security via encapsulation
  • Class: Blueprint for objects.
  • Object: Instance of a class.
  • Constructor: Initializes object state.
  • Message Passing: Communication between objects via methods.

  • Java: Object-oriented, platform-independent (JVM-based).
  • C#: Object-oriented, component-based, runs on .NET Framework / .NET Core.
  • Python: Interpreted, dynamically typed, easy syntax, supports multiple paradigms.

Java

class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

C#

using System;
class Program {
static void Main() {
Console.WriteLine("Hello World");
}
}

Python

print("Hello World")
Type CategoryJavaC#Python
Integerint, longint, longint
Floatingfloat, doublefloat, doublefloat
Charactercharcharstr (single char)
Booleanbooleanboolbool
StringStringstringstr
  • Declaration

    • Java: int x = 10;
    • C#: int x = 10;
    • Python: x = 10
  • Constants

    • Java: final int X = 10;
    • C#: const int X = 10;
    • Python: conventionally uppercase: X = 10
  • Arithmetic: + - * / %
  • Relational: == != > < >= <=
  • Logical: && || ! (Java/C#), and or not (Python)
  • Assignment: = += -= *= /=
  • Increment/Decrement: ++ -- (Java/C# only)

If-Else

if(x > 0) System.out.println("Positive");
else System.out.println("Negative");
if(x > 0) Console.WriteLine("Positive");
else Console.WriteLine("Negative");
if x > 0:
print("Positive")
else:
print("Negative")

Looping

for(int i=0;i<5;i++) System.out.println(i);
for(int i=0;i<5;i++) Console.WriteLine(i);
for i in range(5):
print(i)
  • Java
int add(int a, int b){ return a + b; }
  • C#
int Add(int a, int b){ return a + b; }
  • Python
def add(a, b):
return a + b
  • Java: Scanner sc = new Scanner(System.in); int x = sc.nextInt();
  • C#: int x = Convert.ToInt32(Console.ReadLine());
  • Python: x = int(input())
  • Single-line: // (Java/C#), # (Python)
  • Multi-line: /*...*/ (Java/C#), '''...''' or """...""" (Python)

Java

try { int a=5/0; } catch(Exception e){ System.out.println(e); }

C#

try { int a=5/0; } catch(Exception e){ Console.WriteLine(e.Message); }

Python

try: a=5/0
except Exception as e: print(e)

User Interface (UI) enables interaction between user and application. In Java, C#, and Python, UI can be Graphical (GUI) or Web-based.

a) Swing

  • Part of javax.swing package.
  • Lightweight, platform-independent GUI toolkit.
  • Components: JFrame, JButton, JLabel, JTextField.
    Example
import javax.swing.*;
class MyFrame {
public static void main(String[] args){
JFrame f = new JFrame("Demo");
JButton b = new JButton("Click");
b.setBounds(100,100,80,30);
f.add(b);
f.setSize(300,200);
f.setLayout(null);
f.setVisible(true);
}
}

b) JavaFX

  • Modern GUI framework replacing Swing.
  • Uses FXML and CSS for UI design.
    Example
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class Main extends Application {
public void start(Stage stage){
Button b = new Button("Click");
Scene scene = new Scene(b, 200, 100);
stage.setScene(scene);
stage.show();
}
}

a) Windows Forms

  • Found in System.Windows.Forms namespace.
  • Event-driven, drag-and-drop support in Visual Studio.
    Example
using System;
using System.Windows.Forms;
class MyForm : Form {
Button b;
public MyForm(){
b = new Button();
b.Text = "Click";
b.Click += (s,e)=> MessageBox.Show("Hello");
Controls.Add(b);
}
[STAThread]
static void Main(){ Application.Run(new MyForm()); }
}

b) WPF (Windows Presentation Foundation)

  • Uses XAML for UI, supports data binding and animation.
    Example
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button Content="Click Me" Width="100" Height="40"/>
</Window>

a) Tkinter

  • Built-in Python GUI library.
  • Uses widgets like Button, Label, Entry, Frame.
    Example
import tkinter as tk
win = tk.Tk()
btn = tk.Button(win, text="Click", command=lambda: print("Hello"))
btn.pack()
win.mainloop()

b) PyQt / PySide

  • Advanced GUI library with Qt framework.
  • Supports UI Designer tool.
    Example
from PyQt5.QtWidgets import QApplication, QPushButton
app = QApplication([])
btn = QPushButton('Click')
btn.show()
app.exec_()
  • Event Handling: Actions triggered by user inputs (click, keypress).
  • Layout Managers: Arrange UI components (e.g., FlowLayout, GridLayout, pack() etc.).
  • MVC Pattern: Separates logic (Model), interface (View), and control (Controller).
  • Threading in UI: Long-running tasks should run on separate threads to keep UI responsive.

A thread is the smallest unit of a process that can run independently.
Multithreading allows concurrent execution of two or more threads to maximize CPU utilization.

a) Extending Thread class

class MyThread extends Thread {
public void run(){
for(int i=0;i<5;i++) System.out.println("Child Thread");
}
public static void main(String[] args){
MyThread t = new MyThread();
t.start(); // starts new thread
for(int i=0;i<5;i++) System.out.println("Main Thread");
}
}

b) Implementing Runnable interface

class MyRunnable implements Runnable {
public void run(){
for(int i=0;i<5;i++) System.out.println("Child Thread");
}
public static void main(String[] args){
Thread t = new Thread(new MyRunnable());
t.start();
for(int i=0;i<5;i++) System.out.println("Main Thread");
}
}
  1. New – Thread created but not started (new Thread()).
  2. Runnable – Ready to run after start().
  3. Running – Scheduler picks the thread to execute run().
  4. Blocked/Waiting – Waiting for resource or synchronization.
  5. Terminated – After execution completes.
MethodDescription
start()Starts execution of thread (calls run() internally)
run()Defines thread’s task
sleep(ms)Pauses thread for specified time
join()Waits for thread to finish
isAlive()Checks if thread is active
setPriority(int p)Sets priority (1–10)
getName() / setName()Gets or sets thread name
  • Range: 1 (MIN_PRIORITY) to `10 (MAX_PRIORITY)
  • Default: 5 (NORM_PRIORITY)
  • Used by scheduler for execution order, but not guaranteed.
  • Prevents multiple threads from accessing shared resources simultaneously.
    Example
class Counter {
int count = 0;
synchronized void increment(){ count++; }
}
  • synchronized ensures thread-safe access.
  • Methods: wait(), notify(), notifyAll() (used within synchronized blocks).
  • Used for coordination between threads.
  • Background threads that terminate when all user threads finish.
Thread t = new Thread(...);
t.setDaemon(true);
t.start();
  • Better CPU utilization
  • Faster program execution
  • Responsive UI
  • Simultaneous background processing

5. Database Connectivity using Java / C# / Python

Section titled “5. Database Connectivity using Java / C# / Python”

Database connectivity enables interaction between programs and databases (MySQL, SQL Server, Oracle, etc.) through APIs or libraries for CRUD operations (Create, Read, Update, Delete).

5.2 Java – JDBC (Java Database Connectivity)
Section titled “5.2 Java – JDBC (Java Database Connectivity)”

a) Steps

  1. Import packageimport java.sql.*;

  2. Load driverClass.forName("com.mysql.cj.jdbc.Driver");

  3. Establish connection

    Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/testdb","root","password");
  4. Create statement

    Statement st = con.createStatement();
  5. Execute query

    ResultSet rs = st.executeQuery("SELECT * FROM student");
  6. Process results

    while(rs.next())
    System.out.println(rs.getInt(1)+" "+rs.getString(2));
  7. Close connection

    con.close();

b) PreparedStatement Example

PreparedStatement ps = con.prepareStatement("INSERT INTO student VALUES(?,?)");
ps.setInt(1,101);
ps.setString(2,"Gaurav");
ps.executeUpdate();

a) Steps

  1. Import namespaceusing System.Data.SqlClient;

  2. Establish connection

    SqlConnection con = new SqlConnection(
    "Data Source=SERVER;Initial Catalog=TestDB;Integrated Security=True");
    con.Open();
  3. Execute command

    SqlCommand cmd = new SqlCommand("SELECT * FROM student", con);
    SqlDataReader dr = cmd.ExecuteReader();
    while(dr.Read())
    Console.WriteLine(dr[0] + " " + dr[1]);
  4. Close connection

    con.Close();

b) Using Parameters

SqlCommand cmd = new SqlCommand("INSERT INTO student VALUES(@id,@name)", con);
cmd.Parameters.AddWithValue("@id", 101);
cmd.Parameters.AddWithValue("@name", "Gaurav");
cmd.ExecuteNonQuery();
5.4 Python – DB API (Using MySQL Connector / SQLite3)
Section titled “5.4 Python – DB API (Using MySQL Connector / SQLite3)”

a) MySQL Connector Example

import mysql.connector
con = mysql.connector.connect(host="localhost", user="root", password="1234", database="testdb")
cur = con.cursor()
cur.execute("SELECT * FROM student")
for row in cur:
print(row)
con.close()

b) Parameterized Query

cur.execute("INSERT INTO student VALUES(%s, %s)", (101, "Gaurav"))
con.commit()

c) SQLite Example

import sqlite3
con = sqlite3.connect("test.db")
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS student(id INT, name TEXT)")
cur.execute("INSERT INTO student VALUES(1, 'Gaurav')")
con.commit()
for row in cur.execute("SELECT * FROM student"):
print(row)
con.close()
  • Connection Object: Represents DB connection.
  • Statement / Cursor / Command: Executes SQL queries.
  • ResultSet / Reader: Holds query results.
  • Prepared/Parameterized Statements: Prevent SQL injection.
  • Transaction Control: commit(), rollback() for consistency.