📚 Oracle SQL Syllabus

🧪 Oracle SQL Lab Tutorial Syllabus

Oracle SQL Lab Tutorial Syllabus

Objective: This lab-based Oracle SQL tutorial is designed to build a strong practical foundation in SQL programming using Oracle Database. Each lab includes step-by-step exercises, real-world scenarios, and SQL scripts for active learning.

🔍 Lab 1: Introduction & Basic Queries

📊 Lab 4: Grouping and Aggregation

  • GROUP BY, HAVING
  • CUBE, ROLLUP, GROUPING SETS
  • Practice: Salary summaries, department counts

🔁 Lab 5: Subqueries

  • Simple and Correlated Subqueries
  • EXISTS, NOT EXISTS, ANY, ALL
  • Practice: Find high earners per department

➕ Lab 6: Set Operations

  • UNION, INTERSECT, MINUS
  • Practice: Combine and compare queries

🔄 Lab 7: Pivoting Data

  • PIVOT, UNPIVOT
  • Practice: Crosstab salary reports

🎚 Lab 8: Limiting Rows

  • FETCH FIRST, OFFSET
  • Practice: Top earners, latest hires

🏗 Lab 9: Creating and Modifying Tables

  • CREATE, ALTER TABLE
  • Virtual Columns
  • Practice: Create custom project table

📁 Lab 10: Data Types

  • NUMBER, CHAR, VARCHAR2, DATE, TIMESTAMP
  • NCHAR, NVARCHAR2, INTERVAL
  • Practice: Define appropriate types

🔐 Lab 11: Constraints

  • PRIMARY KEY, FOREIGN KEY
  • NOT NULL, UNIQUE, CHECK, DEFAULT
  • Practice: Create relational schema

✏️ Lab 12: Modifying Data

  • INSERT, INSERT ALL, UPDATE, DELETE
  • MERGE for UPSERT
  • Practice: Populate employee/project data

⏳ Lab 13: Temporary Tables

  • Global and Private Temporary Tables
  • Practice: Use for session-specific data

👁 Lab 14: Views

  • CREATE, DROP, Updatable Views
  • WITH CHECK OPTION, Inline Views
  • Practice: Build report views

⚡ Lab 15: Indexes

  • CREATE, DROP, Unique, Function-based, Bitmap Index
  • Practice: Improve query performance

📛 Lab 16: Synonyms

  • CREATE, DROP SYNONYM
  • Practice: Use synonyms for object access

🔢 Lab 17: Sequences

  • CREATE, ALTER, DROP SEQUENCE
  • Practice: Use sequences for IDs

🧰 Tools Required

  • Oracle Database (XE or Standard)
  • SQL Developer or compatible tool
  • Sample schema: HR, SCOTT, or custom dataset

✅ Learning Outcomes

  • Master Oracle SQL fundamentals
  • Write optimized SQL queries
  • Design and manage Oracle database objects
oracle sql tutorial, oracle database lab, sql practice exercises, oracle lab manual, sql join practice, oracle sql queries, group by sql oracle, subquery oracle, pivot sql, create table sql oracle, oracle views, temporary tables oracle, sql developer lab, dml oracle, ddl commands, oracle index types, sql sequences oracle, sql training beginner, oracle sql beginner, advanced sql oracle, online sql tutorial oracle, sql lab syllabus, sql lab exercises, sql lab topics

📘 C Programming Language

🖥️ Learn C Programming From Scratch

Master C with practical examples, easy tutorials, and hands-on projects

📘 C Programming Syllabus

This is a detailed C programming syllabus designed for a 6-month semester. It is suitable for undergraduate students or beginners learning C programming.

📘 Module 1: Introduction to Programming (Weeks 1–2)

💡 Practice Problems for C Programming

🎥 Reference Videos: Playlist 1 Playlist 2

Keywords: c programming, practice problems, coding exercises, programming tutorial, beginner programming, c language, programming challenges, learning c, code practice, programming homework

🔁 Module 3: Control Structures (Weeks 4–5)

Decision making:
Loops:
Jump statements: 

🧩 Module 5: Functions (Weeks 8–9)

📍 Module 6: Pointers (Weeks 10–11)

📦 Module 7: Structures and Unions (Weeks 12–13)

📁 Module 8: File Handling (Weeks 14–15)

💾 Module 9: Dynamic Memory Allocation (Week 16)

  • Memory allocation functions: malloc(), calloc(), realloc(), free()
  • Memory leaks and handling

⚙️ Module 10: Preprocessor Directives (Week 17)

  • #define, #include, #ifdef, #ifndef
  • Macros and conditional compilation

🔀 Module 11: Miscellaneous Topics (Week 18)

  • Command-line arguments
  • Enumerations and typedefs

🛠️ Weeks 19–24: Project & Final Assessment

  • Mini project development
  • Internal assessments and lab tests
  • Final practical and written exams

🧪 Lab Work / Assignments

  • 100-125 practical programs based on the above modules
  • Sample mini projects: Student Record System, Bank Management System, File Encryption Tool
c programming tutorial, learn c programming, c programming for beginners, c language tutorial, c programming course, c programming tutorial for beginners with examples, how to learn c programming step by step, c programming full course free, c language basics for beginners, c programming projects for students, best way to learn c programming, c programming tutorial with practice problems, c programming online compiler tutorial, simple c programs for practice, what is c programming used for?, how hard is c programming to learn?, why learn c programming in 2025?, how to write your first c program?, is c programming still relevant today?, best c programming course online, c programming certification course, c programming books for beginners, best IDE for c programming, c programming tutorial with certificate
#CProgramming #LearnC #CProgrammingTutorial #CLanguage #CodeInC #BeginnerCoding #CProgrammingForBeginners #CLanguageTutorial #CProjects #CProgrammingCourse #CProgrammingExamples #CProgrammingPractice #CProgramming2025 #LearnToCode #ProgrammingBasics #CodingInC #ProgrammingForBeginners #CodeNewbie #FreeProgrammingCourse #CSBasics #ProgrammingHelp #CProgrammingFullCourse #SimpleCPrograms #FirstCProgram #CProgrammingStepByStep #OnlineCCompiler #CProgrammingWithExamples #CProgrammingMadeEasy

SQL Insert command in details

Understanding the SQL INSERT Command

sql insert command

Let’s take a closer look at the SQL INSERT command below:
INSERT INTO customers
(customer_id, first_name, last_name, email, created_at)
VALUES (101, 'Ahsan', 'Arif', 'aa@x.com', '11-jan-4');

At first glance, this might appear to be a basic statement, but it plays a vital role in managing data within relational databases. Let’s break it down.

INSERT INTO customers

This tells the database to add a new record to the customers table—a central location where client information is stored. Keeping this data accurate and up to date is key for managing customer relationships effectively.

Column List

Within the parentheses, we list the fields where data will be inserted:

  • customer_id: A unique identifier for each customer, ensuring proper tracking and referencing.
  • first_name and last_name: These fields store the customer's name for personalization and service.
  • email: Critical for communication—used for updates, offers, and notifications.
  • created_at: A timestamp marking when the record was created, useful for historical tracking and analysis.

VALUES Clause

Here we provide the actual data:

  • 101 as the customer ID
  • 'Ahsan' as the first name
  • 'Arif' as the last name
  • 'aa@x.com' as the email
  • '11-jan-4' as the creation date

Why It Matters

Each insert like this keeps the customer database current. Accurate data entry is essential—it drives better insights, personalized services, targeted marketing, and streamlined operations.

Real-World Impact

Whether it's a retail brand tailoring promotions or a service team addressing customer needs, having precise and structured customer data enables more effective engagement and decision-making.

Final Thoughts

This simple command highlights the power of structured data. Every row added brings value—not just as stored information, but as an opportunity to understand and serve customers better. As you continue exploring SQL, remember that even the most basic operations are foundational to effective data management.

Thanks for reading—I hope this breakdown clarified how meaningful even a single SQL statement can be.

Introduction to the `INSERT` Command

Certainly! Below is  a training module that focuses on the Oracle SQL `INSERT` command, specifically tailored for entering values into a `Customers` table. 

sql insert statement

Thank you for joining this training session today. We're going to dive into one of the fundamental concepts of SQL—specifically, the `INSERT` command. This command is essential for adding new records to our database tables, and today we will focus on how to use it effectively with a `Customers` table.

The `INSERT` command in Oracle SQL allows you to add new rows of data to a specified table. In our case, we’ll be inserting customer records into the `Customers` table. This table typically contains essential information about our customers, such as `Customer_ID`, `First_Name`, `Last_Name`, `Email`, and `Created_at`.

Basic Syntax

The basic syntax for the `INSERT` command is as follows:

```sql

INSERT INTO table_name (column1, column2, column3, ...)

VALUES (value1, value2, value3, ...);

```
Inserting Data into the Customer Table


Let’s consider our `Customer` table has the following structure:

- **Customer_ID**: Integer (Primary Key)

- **First_Name**: Varchar (Not Null)

- **Last_Name**: Varchar (Not Null)

- **Email**: Varchar (Unique)

- **Created_at**: Date (Default)

Now, to insert a new customer record, we would write an SQL command as follows:

```sql

INSERT INTO Customers (Customer_ID, First_Name, Last_Name, Email, created_at)

VALUES (1, 'Mr', 'Rahim', 'mr@tc.com', '01-jan-24');

```
Inserting Multiple Records

You may often need to input multiple records at once. Oracle SQL allows this by extending the `INSERT` statement like so:

```sql

INSERT INTO Customers(Customer_ID, First_Name, Last_Name, Email, created_at)

VALUES

(2, 'Md', 'Karim', 'mk@tc.com', '01-feb-24'),

(3, 'Mis', 'Lucky', 'ml@tc.com', '01-mar-23');

```
Important Considerations

1. **Primary Key Constraint**: Remember that if `Customer_ID` is a primary key, each value must be unique. Attempting to insert a duplicate value will result in an error.

2. **Data Types**: Ensure the values you provide match the data types defined in the table schema. For example, an integer is expected for numeric fields.

3. **NULL Values**: If your table allows NULL values for certain columns, you can choose to omit them from your `INSERT` statement, like so:

```sql

INSERT INTO Customers (Customer_ID, First_Name, Last_Name)

VALUES (4, 'Mis', 'Berly');

```
4. **Using Default Values**: If any column has a default value defined, it will automatically be used if you do not specify a value for that column during the insert.


Conclusion

The `INSERT` command is a powerful tool for populating your database. By understanding how to use it effectively, you'll be able to maintain and manage your customer records efficiently.

Remember, practice is key! I encourage you to try inserting records into your `Customers` table and explore different scenarios like bulk inserts or handling errors.

If you have any questions or need further clarification on any point, please feel free to ask. Happy querying!

Understanding the Oracle `CREATE TABLE` Command

Understanding the Oracle `CREATE TABLE` Command

For details : TrustCoding

Today, I’d like to talk to you about a fundamental aspect of database management in Oracle: the `CREATE TABLE` command. This command is essential for defining and establishing the structure of our data within a relational database.

Introduction to the `CREATE TABLE` Command

The `CREATE TABLE` command allows us to create a new table in our Oracle database. A table acts as a structured collection of data, organized in rows and columns, much like a spreadsheet. Each table reflects a particular entity, such as customers, products, or orders, and serves as a fundamental building block for data storage.

Basic Syntax

The basic syntax of the `CREATE TABLE` command looks like this:

CREATE TABLE table_name (

    column1_name datatype [constraint],

    column2_name datatype [constraint],

    ...

);

**table_name**: This is the name you choose for your new table.

**column1_name, column2_name**: These are the names of the columns you want to include in your table.

**datatype**: Each column requires a data type, such as `VARCHAR2` for variable-length strings, `NUMBER` for numeric values, or `DATE` for date values.

**constraint**: Constraints are optional rules applied to the columns, such as `PRIMARY KEY`, `FOREIGN KEY`, `UNIQUE`, or `NOT NULL`, which help maintain data integrity.

 Example of Using `CREATE TABLE`

Let's look at an example to clarify this further. Suppose we want to create a table for storing customer information. Here’s how the command might look:





CREATE TABLE customers (

    customer_id NUMBER PRIMARY KEY,

    first_name VARCHAR2(50) NOT NULL,

    last_name VARCHAR2(50) NOT NULL,

    email VARCHAR2(100) UNIQUE,

    created_at DATE DEFAULT SYSDATE

);

In this example, we’ve created a table named `customers` with five columns. The `customer_id` is defined as the primary key, ensuring that each customer has a unique identifier. The `email` column has a unique constraint, preventing duplicate email addresses. Additionally, the `created_at` column automatically records the date and time the record was created.

Key Considerations

When using the `CREATE TABLE` command, there are a few important considerations:

1. **Naming Conventions**: Choose clear and descriptive names for your tables and columns, which helps in understanding the data structure.

2. **Data Types**: Selecting the appropriate data types for your columns is crucial. This affects storage efficiency and performance.

3. **Constraints and Relationships**: Properly defining constraints ensures the integrity of your data. Consider how tables relate to each other and use foreign keys for relational integrity.

4. **Indexes**: After creating a table, you might want to create indexes to improve query performance for specific columns, particularly those frequently used in searches.

Conclusion

In conclusion, the Oracle `CREATE TABLE` command is a powerful tool that lays the foundation for our databases. It allows us to define the structure of our data clearly, ensuring that we can efficiently store, retrieve, and manage that data. Whether you're a beginner or looking to refine your database skills, mastering the `CREATE TABLE` command is essential.

Thank you for your attention, and I hope this overview has given you a better understanding of how to construct tables in Oracle databases. If you have any questions, feel free to ask!

For details : TrustCoding

Java : Object and Class

Objects and Classes in Java

In object-oriented programming, objects and classes are fundamental components. They represent the two main pillars of OOP, and it's impossible to create a program in Java without them. In this section, we'll explore the concepts of objects and classes in Java.


What is an object in Java?

object in Java

An object is a real-world entity characterized by its state and behavior. In simpler terms, it's something tangible that you can touch and feel, such as a car or a chair. For example, the banking system represents an intangible object. Each object possesses a unique identity, typically represented by a unique ID that the JVM uses internally for identification purposes.


Characteristics of an Object


State: This refers to the data or values held by an object.

Behavior: This defines the functionality of an object, such as actions like depositing or withdrawing.

Identity: An object's identity is generally represented by a unique ID. While this ID is not visible to users, it is crucial for the JVM to distinguish each object uniquely.

Example of an Object in Java

Consider a pen as an object. Its state includes attributes like its name (Reynolds) and color (white). Its behavior is its functional capability, such as writing.

An object is an instance of a class, which acts as a template or blueprint for creating objects. In simpler terms, an object is the result of instantiating a class.

An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.

Object Definitions
  1. An object is a real-world entity.
  2. An object is a runtime entity.
  3. An object is an entity that has state and behavior.
  4. An object is an instance of a class.

What is a Class in Java?

A class is a collection of objects that share common properties. It serves as a template or blueprint from which objects are created. Unlike objects, a class is a logical entity and does not have a physical presence.


A class in Java can contain

:Class in Java

1. Fields

Fields are variables declared within a class that represent the state of the objects created from that class. Also known as instance variables, they define the data stored in each object. Access modifiers like public, private, and protected can be applied to fields to control their visibility and accessibility.

2. Methods

Methods are functions defined within a class that describe the actions or behaviors that objects of that class can perform. They enable interaction with and modification of an object's state (its fields). Methods can either be void (returning nothing) or return values, and they can also have different access modifiers.


3. Constructors

Constructors are special methods used to initialize class objects. When an object is created using the new keyword, the constructor is invoked and shares the same name as the class. Constructors can initialize an object's fields and perform any necessary setup during object creation.

4. Blocks

Java supports two types of blocks within a class: instance blocks (also known as initialization blocks) and static blocks. Static blocks are executed only once when the class is loaded into memory, typically for static initialization. Instance blocks, on the other hand, are executed each time a new object of the class is created and can be used to initialize instance variables.

5. Nested Class and Interface

Java allows classes and interfaces to be nested within other classes and interfaces. Nested classes can be either static or non-static and have access to the members (fields and methods) of the enclosing class. Nested interfaces, which are implicitly static, can be used to group related constants and methods logically.

Syntax of a Class

  1. class <class_name>{  
  2.     field;  
  3.     method;  
  4. }  

Instance Variable in Java


An instance variable is a variable defined within a class but outside any method. Unlike local variables, instance variables do not receive memory allocation at compile time; instead, they are allocated memory at runtime when an object (or instance) is created.

Each instance of a class has its own copy of the instance variables, meaning that changes to the instance variables of one object do not affect those of other objects of the same class. Instance variables can be initialized using constructors or setter methods. They are essential in object-oriented programming, as they encapsulate data within objects and often represent the state or properties of those objects.

Method in Java

In Java, a method is a block of code defined within a class that performs a specific function. Methods provide a way to interact with an object's state and encapsulate behavior within objects.

Advantages of Methods

Code Reusability: Methods promote code reusability by allowing the same block of code to be executed multiple times throughout a program. Once defined, a method can be called from anywhere within its scope.

Code Optimization: Methods help optimize code by encapsulating complex or repetitive tasks into reusable components. This modularization enhances readability and simplifies maintenance.

The new Keyword in Java

The new keyword is used to allocate memory at runtime. All objects are allocated memory in the heap memory area.

In Java, an instance of a class—commonly referred to as an object—is created using the new keyword. This keyword dynamically allocates memory for the object and returns a reference to it when followed by the class name and parentheses, which may include optional arguments.

MyClass.java

  1. public class MyClass {  
  2.     int myField;  
  3.     public MyClass(int value) {  
  4.         myField = value;  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         // Using the new keyword to create an instance of MyClass  
  8.         MyClass myObject = new MyClass(10);  
  9.         // Accessing the instance variable of the object  
  10.         System.out.println("Value of myField: " + myObject.myField);  
  11.     }  
  12. }  

Output:

Value of myField: 10 

Explanation

In this example, the constructor MyClass(int value) is called with the parameter 10, the reference to the newly constructed object is assigned to the variable myObject, and new MyClass(10) dynamically allocates memory for an object of type MyClass. Lastly, a printout of the instance variable myField's value is obtained.

Object and Class Example: main within the class

In Java, the main() method can be declared in a class, which is typically done in demonstration or basic programs. Having the main() method defined inside of a class allows a program to run immediately without creating a separate class containing it.

In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

  1. //Java Program to illustrate how to define a class and fields  
  2. //Defining a Student class.  
  3. class Student{  
  4.  //defining fields  
  5.  int id;//field or data member or instance variable  
  6.  String name;  
  7.  //creating main method inside the Student class  
  8.  public static void main(String args[]){  
  9.   //Creating an object or instance  
  10.   Student s1=new Student();//creating an object of Student  
  11.   //Printing values of the object  
  12.   System.out.println(s1.id);//accessing member through reference variable  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:

0
null

Explanation

In this example, the constructor MyClass(int value) is invoked with the parameter 10, resulting in a new MyClass object being created and its reference assigned to the variable myObject. The new MyClass(10) statement dynamically allocates memory for this object. Finally, the value of the instance variable myField is printed.

Object and Class Example: main Method Within a Class

In Java, the main() method can be defined within a class, which is common for demonstrations or simple programs. This allows the program to run immediately without needing a separate class for execution.

In the following example, a Student class is created with two data members: id and name. We instantiate the Student class using the new keyword and print the object's values. The main() method is included within the class to facilitate running the program.

File: TestStudent1.java

  1. //Java Program to demonstrate having the main method in   
  2. //another class  
  3. //Creating Student class.  
  4. class Student{  
  5.  int id;  
  6.  String name;  
  7. }  
  8. //Creating another class TestStudent1 which contains the main method  
  9. class TestStudent1{  
  10.  public static void main(String args[]){  
  11.   Student s1=new Student();  
  12.   System.out.println(s1.id);  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:

0
null 

Explanation

In this Java program, the main method is located in a different class than the Student class. The Student class does not define any methods for its fields, name and id. The main method exists in another class called TestStudent1, where it uses the default constructor to create an object s1 of type Student. Because the fields name and id are not explicitly initialized, they have default values: null for the String and 0 for the int.

Object Initialization in Java

There are three main ways to initialize an object in Java:

  1. By Reference Variable
  2. By Method
  3. By Constructor

1) Initialization through Reference Variable

Initializing an object means assigning data to its fields. Below is a simple example demonstrating how to initialize an object through a reference variable.

File: TestStudent2.java

  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent2{  
  6.  public static void main(String args[]){  
  7.   Student s1=new Student();  
  8.   s1.id=101;  
  9.   s1.name="Sonoo";  
  10.   System.out.println(s1.id+" "+s1.name);//printing members with a white space  
  11.  }  
  12. }  

Output:

101 Sonoo 


This Java code includes two classes: Student and TestStudent2. The Student class defines two fields, id and name, which represent the student's ID and name, respectively. The TestStudent2 class contains the main method, which serves as the entry point of the program. Inside this main method, an object s1 of type Student is created using the new keyword. The fields id and name of s1 are then initialized with the values 101 and "Sonoo".

Additionally, you can create multiple Student objects and store information in them using different reference variables.

File: TestStudent3.java

  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent3{  
  6.  public static void main(String args[]){  
  7.   //Creating objects  
  8.   Student s1=new Student();  
  9.   Student s2=new Student();  
  10.   //Initializing objects  
  11.   s1.id=101;  
  12.   s1.name="Sonoo";  
  13.   s2.id=102;  
  14.   s2.name="Amit";  
  15.   //Printing data  
  16.   System.out.println(s1.id+" "+s1.name);  
  17.   System.out.println(s2.id+" "+s2.name);  
  18.  }  
  19. }  

Output:

101 Sonoo
102 Amit

Explanation

This Java code illustrates how to create and initialize multiple Student class objects within the TestStudent3 class. Using the new keyword, two Student objects, s1 and s2, are created. Each object's id and name fields are then initialized separately: s1 has an id of 101 and a name of "Sonoo," while s2 is assigned an id of 102 and a name of "Amit."

2) Initialization via Method

In this example, we create two Student objects and initialize their values by calling the insertRecord method.

We display the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java

  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  void insertRecord(int r, String n){  
  5.   rollno=r;  
  6.   name=n;  
  7.  }  
  8.  void displayInformation(){System.out.println(rollno+" "+name);}  
  9. }  
  10. class TestStudent4{  
  11.  public static void main(String args[]){  
  12.   Student s1=new Student();  
  13.   Student s2=new Student();  
  14.   s1.insertRecord(111,"Karan");  
  15.   s2.insertRecord(222,"Aryan");  
  16.   s1.displayInformation();  
  17.   s2.displayInformation();  
  18.  }  
  19. }  

Output:


11 Karan
222 Aryan
Explanation


The Java code provided defines two classes: Student and TestStudent4. The Student class contains fields for rollno and name, along with methods insertRecord and displayInformation to initialize and display the respective data. In the main method of the TestStudent4 class, two Student objects are created, and their insertRecord methods are called to set the values for rollno and name.

Object in Java with values



As illustrated in the figure above, objects are stored in the heap memory area, and reference variables point to these objects in memory. In this context, s1 and s2 are reference variables that reference the objects allocated in the heap.

3) Initialization Using a Constructor

Object initialization through a constructor is a fundamental concept in object-oriented programming in Java. Constructors are special methods within a class that are invoked when an object of that class is created using the new keyword. They set up the object's state by providing initial values for its fields or performing necessary setup tasks. The constructor is automatically called upon instantiating an object, ensuring that the object is properly initialized before it is used.

Here’s an example that demonstrates object initialization via a constructor:

File: ObjectConstructor.java

  1. class Student {  
  2.     int id;  
  3.     String name;  
  4.     // Constructor with parameters  
  5.     public Student(int id, String name) {  
  6.         this.id = id;  
  7.         this.name = name;  
  8.     }  
  9.     // Method to display student information  
  10.     public void displayInformation() {  
  11.         System.out.println("Student ID: " + id);  
  12.         System.out.println("Student Name: " + name);  
  13.     }  
  14. }  
  15. public class ObjectConstructor {  
  16.     public static void main(String[] args) {  
  17.         // Creating objects of Student class with constructor  
  18.         Student student1 = new Student(1"John Doe");  
  19.         Student student2 = new Student(2"Jane Smith");  
  20.         // Displaying information of the objects  
  21.         student1.displayInformation();  
  22.         student2.displayInformation();  
  23.     }  
  24. }  

Output:

Student ID: 1
Student Name: John Doe
Student ID: 2
Student Name: Jane Smith

Explanation

In this example, the id and name fields of a Student object are initialized through a constructor defined in the Student class, which takes two parameters: id and name. When creating the student1 and student2 objects using this constructor, their fields are set with the provided values. This approach ensures that objects are created with the correct initial values, making it simpler to instantiate and use them later in the program.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

  1. class Employee{    
  2.     int id;    
  3.     String name;    
  4.     float salary;    
  5.     void insert(int i, String n, float s) {    
  6.         id=i;    
  7.         name=n;    
  8.         salary=s;    
  9.     }    
  10.     void display(){System.out.println(id+" "+name+" "+salary);}    
  11. }    
  12. public class TestEmployee {    
  13. public static void main(String[] args) {    
  14.     Employee e1=new Employee();    
  15.     Employee e2=new Employee();    
  16.     Employee e3=new Employee();    
  17.     e1.insert(101,"ajeet",45000);    
  18.     e2.insert(102,"irfan",25000);    
  19.     e3.insert(103,"nakul",55000);    
  20.     e1.display();    
  21.     e2.display();    
  22.     e3.display();    
  23. }    
  24. }    

Output:

101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

Explanation


The Employee class in this Java code defines three fields: id, name, and salary. It includes two methods: insert, which sets the values of the fields, and display, which prints those values. In the main function of the TestEmployee class, three Employee objects (e1, e2, and e3) are created. The insert method is called for each object to initialize the id, name, and salary fields with specific values. Subsequently, the display method is invoked for each object to show the initialized data.

Object and Class Example: Rectangle


Another example is provided that handles the records for a Rectangle class.

File: TestRectangle1.java

  1. class Rectangle{  
  2.  int length;  
  3.  int width;  
  4.  void insert(int l, int w){  
  5.   length=l;  
  6.   width=w;  
  7.  }  
  8.  void calculateArea(){System.out.println(length*width);}  
  9. }  
  10. class TestRectangle1{  
  11.  public static void main(String args[]){  
  12.   Rectangle r1=new Rectangle();  
  13.   Rectangle r2=new Rectangle();  
  14.   r1.insert(11,5);  
  15.   r2.insert(3,15);  
  16.   r1.calculateArea();  
  17.   r2.calculateArea();  
  18. }  
  19. }  

Output:

55
45

Explanation

This Java code defines a Rectangle class with fields for length and width, along with methods to set the dimensions and calculate the area. In the main method of the TestRectangle1 class, two Rectangle objects are created, and their dimensions are set using the insert method.
Different Ways to Create an Object in Java

Using the new Keyword

The most common way to create an object in Java is with the new keyword followed by a constructor.
Example:java

ClassName obj = new ClassName();

This allocates memory for the object and calls its constructor to initialize it.

Using the newInstance() Method

This method, part of the java.lang.Class class, creates a new instance of a class dynamically at runtime, invoking the no-argument constructor.

Example:java


ClassName obj = (ClassName) Class.forName("ClassName").newInstance();

Using the clone() Method

The clone() method creates a copy of an existing object through a shallow copy, returning a new object that duplicates the original.

Example:java


ClassName obj2 = (ClassName) obj1.clone();

Using Deserialization

Objects can be created by deserializing them from a stream of bytes using the ObjectInputStream class. The object is read from a file or network, and the readObject() method is called to recreate it.

Using Factory Methods

Factory methods are static methods within a class that return instances of that class. They allow for encapsulating the object creation logic without directly invoking a constructor.

Example:java

ClassName obj = ClassName.createInstance();

These methods provide flexibility in how objects are instantiated in Java, catering to different needs and scenarios.

We will learn these ways to create object later.

Different Ways to create an Object in Java

    Anonymous Object

    An anonymous object is one that does not have a name or reference. It can only be used at the time of its creation.

Calling method through a reference:

  1. Calculation c=new Calculation();  
  2. c.fact(5);  

Calling method through an anonymous object

  1. new Calculation().fact(5);  

Let's see the full example of an anonymous object in Java.

  1. class Calculation{  
  2.  void fact(int  n){  
  3.   int fact=1;  
  4.   for(int i=1;i<=n;i++){  
  5.    fact=fact*i;  
  6.   }  
  7.  System.out.println("factorial is "+fact);  
  8. }  
  9. public static void main(String args[]){  
  10.  new Calculation().fact(5);//calling method with anonymous object  
  11. }  
  12. }  

Output:

Factorial is 120

Explanation

The factorial of an integer \( n \) can be calculated using Java code that defines a `Calculation` class with a `factorial` method. This method employs a for loop to compute the factorial by iterating from 1 to \( n \), and the result is then printed to the console. The main method demonstrates the use of an anonymous `Calculation` class object, which calls the `factorial` method with the parameter 5, showcasing how to use anonymous objects in Java for one-time method invocations.

Creating Multiple Objects of One Type

In Java, it's possible to create multiple objects of the same type, similar to how we handle primitive data types.

Initialization of Primitive Variables

  1. int a=10, b=20;  

Initialization of Reference Variables

  1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects  

Let's see the example:

  1. //Java Program to illustrate the use of Rectangle class which  
  2. //has length and width data members  
  3. class Rectangle{  
  4.  int length;  
  5.  int width;  
  6.  void insert(int l,int w){  
  7.   length=l;  
  8.   width=w;  
  9.  }  
  10.  void calculateArea(){System.out.println(length*width);}  
  11. }  
  12. class TestRectangle2{  
  13.  public static void main(String args[]){  
  14.   Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
  15.   r1.insert(11,5);  
  16.   r2.insert(3,15);  
  17.   r1.calculateArea();  
  18.   r2.calculateArea();  
  19. }  
  20. }  

Output:

55
45

Explanation

This Java program demonstrates the use of a Rectangle class, which has length and width as its data members. The class includes methods to insert dimensions and compute the area of a rectangle. In the main method of the TestRectangle2 class, two Rectangle objects (r1 and r2) are created in a single line using a comma-separated list, showcasing the ability to instantiate multiple objects of the same type at once. Each object's dimensions are set by calling the insert method, and the area of each rectangle is calculated and printed using the calculateArea method.

Real World Example: Account

File: TestAccount.java

  1. //Java Program to demonstrate the working of a banking-system  
  2. //where we deposit and withdraw amount from our account.  
  3. //Creating an Account class which has deposit() and withdraw() methods  
  4. class Account{  
  5. int acc_no;  
  6. String name;  
  7. float amount;  
  8. //Method to initialize object  
  9. void insert(int a,String n,float amt){  
  10. acc_no=a;  
  11. name=n;  
  12. amount=amt;  
  13. }  
  14. //deposit method  
  15. void deposit(float amt){  
  16. amount=amount+amt;  
  17. System.out.println(amt+" deposited");  
  18. }  
  19. //withdraw method  
  20. void withdraw(float amt){  
  21. if(amount<amt){  
  22. System.out.println("Insufficient Balance");  
  23. }else{  
  24. amount=amount-amt;  
  25. System.out.println(amt+" withdrawn");  
  26. }  
  27. }  
  28. //method to check the balance of the account  
  29. void checkBalance(){System.out.println("Balance is: "+amount);}  
  30. //method to display the values of an object  
  31. void display(){System.out.println(acc_no+" "+name+" "+amount);}  
  32. }  
  33. //Creating a test class to deposit and withdraw amount  
  34. class TestAccount{  
  35. public static void main(String[] args){  
  36. Account a1=new Account();  
  37. a1.insert(832345,"Ankit",1000);  
  38. a1.display();  
  39. a1.checkBalance();  
  40. a1.deposit(40000);  
  41. a1.checkBalance();  
  42. a1.withdraw(15000);  
  43. a1.checkBalance();  
  44. }}   

Output:

832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

Explanation

The Account class in this Java program simulates a basic banking system with features for depositing, withdrawing, checking the balance, and viewing account details. It includes attributes such as account number, account holder's name, and balance amount. The main method of the TestAccount class is responsible for creating and initializing an Account object, a1, with the relevant information. Afterward, the account is utilized for deposits and withdrawals, and the balance is checked after each transaction.