What is Entity Framework ?

Entity Framework is an ORM framework. ORM stands for Object Relational Mapping. Object Relational Mapping automatically creates classes based on database tables, and vice-versa is also true, it means it can generate necessary SQL to create database tables based on classes. .Net applications may connect with any kind of data sources like flat files, XML data, or relational databases. Irrespective


If you have two tables showing on the left side and you want to create a new table using that data then you have to follow the following steps in ADO.NET:

1. We need to create Department and Employee classes. 

2. Write ADO.NET code to retrieve data from the database. 

3. Once the database is created, we need to create department and employee objects and populate them with the data.

Note: Entity Framework can do all the above automatically if we provide it with the database schema. 

Entity Framework provides us a class called DbContext which is our gateway to our database. A DbConext can have one or more DbSet and this DbSet represent a table in our database. We use LINQ query to query this DbSet and Entity Framework translates these LINQ queries to SQL queries at runtime. 

Three Important Entity Framework Approaches are: 

1. Database First Approach.

  • We design our tables.
  • Entity Framework generates domain classes.

2. Code First Approach.

  • We create our domain classes.
  • Entity Framework generates database tables.

3. Model First Approach.

  • We create a UML diagram.
  • Entity Framework generates domain classes and databases. 

Java Program for Concatenation of Array.

Given an integer array nums of length n, create a new array ans of length 2n such that ans is the concatenation of two nums arrays. 

Example:
Input: nums = [1, 2, 4]
Output: ans = [1, 2, 4, 1, 2, 4]

Input: nums = [1, 3, 2, 1]
Output: ans = [1, 3, 2, 1, 1, 3, 2, 1]

Steps:

  • Create a new array ans[] = new int[2*n] of size 2n where n is the size of the given array. 
  • Copy the elements given into the new array where ans[i] = nums[i] and ans[i+n] = nums[i]
  • Return ans.
public class Main
{
    public static int[] getConcatenation(int[] nums) {
        
        int ans[] = new int[2*nums.length];
        
        for(int i = 0; i<nums.length; i++){
            ans[i] = nums[i];
            ans[i+nums.length] = nums[i];
        }
        return ans;
    }
public static void main(String[] args) {
    int nums[] = {1, 2, 1, 3};
    
    int[] ans = getConcatenation(nums);
    
    for(int i = 0; i<ans.length; i++) {
        System.out.print(ans[i]+" ");
    }
}
}
Output:
1 2 1 3 1 2 1 3

Java Programming Complete Tutorial

Java Programming

The Java Programming Language is a general-purpose, high-level, strongly-typed, class-based object-oriented programming language. All Java applications first complied with the bytecode that can run on any Java Virtual Machine (JVM) regardless of the underlying computer architecture. 
 
Introduction to Programming:

Basic of Java:

Access Specifiers in Java.

The process of hiding information is implemented using Access Specifiers known as visibility modifiers. They regulate access to classes, fields, and methods. Access Specifiers specify if fields or methods in a class can be invoked from another class or sub-class. In simple words, they are used to restrict access. 

There are four types of Access Specifiers in Java. 

  • Public
  • Private
  • Protected
  • Default (no specifier)
Public: Classes, methods, and fields declared as public can be accessed from any class in an application. 
Default: If Classes, variables, and methods have a default specifier we can access them only within the same package but not from outside this package. 
When no access specifiers are specified for an element, its accessibility level is the default. There is no keyword default. (alert-passed)
Private: Private methods and fields can only be accessed within the same class to which the methods and field belong. 
Protected: Protected methods and fields are accessible within the package and outside the package but with the help of inheritance. It cannot be applied to a class and it provides more accessibility than the default access specifier.    


Access Modifiers default private protected public
Accessible inside the class Yes Yes Yes Yes
Accessible within the subclass inside the same package Yes No Yes Yes
Accessible outside the package No No No Yes
Accessible within the subclass outside the package No No Yes Yes

Accessors and Mutators in Java.

Java accessor and mutaotrs

Accessors and Mutators are two very important concepts in Java. It is used to read and update the private data member of a class. 

To understand this concept more clearly we first have to understand encapsulation and access specifiers. Encapsulation is an important concept in Object-oriented programming and it is implemented by wrapping up the data and methods into a single unit. 

The data present inside the class need to be secure and for this, we declare the data in a class as private. We cannot access the private data-member of other classes outside that class. To read and update the private data member a class outside that class we have to use public methods of that class. These methods are called Accessors or Getters and Mutators or Setters

Accessor or Getters are methods used to return the value of a private field of a class. It does not change the state of the Object. 

example:

public String getName() {
    return name; 
}    

Mutators or Setters are methods used to set a value of a private field of a class. It changes the state of the object. 

example:

public void setName(String fullName) {
    name = fullName;
}    


Example Java Program to Understand Accessors and Mutators.

public class Student {
    
    //attribute
    private int studId;
    private String studName;
    
    //Accessors or Getters
    public int getStudId() {
        return studId;
    }
    public String getStudName() {
        return studName;
    }
    //Mutators or Setters
    public void setStudId(int studId) {
        this.studId = studId;
    }
    public void setStudName(String studName) {
        this.studName = studName;
    }
}

import java.util.*;

public class Main
{
	public static void main(String[] args) {
	    //Object Creation
	    Student Obj = new Student();
	    
	    //assign value using Setters
	    Obj.setStudId(112);
	    Obj.setStudName("Rahul");
	    
	    //retrive value using Getters
	    System.out.println("Student ID: "+Obj.getStudId());
	    System.out.println("Student Name: "+Obj.getStudName());
	}
}
Output:
Student ID: 112
Student Name: Rahul

In the above example, we can see that how we are reading and updating the private data member of the Student class from the Main class with the help of the Object of Student class. 

Hope you found this article useful if you have any question related to this topic feel free to ask me in the comment section below. 

Java Classes and Objects.

Java is an Object-Oriented Programming Language and writing a program in Java is totally different from any other Object-Oriented Programming Language like C++ or Python. In Java, it is necessary to create a class before writing any solution to any programming question. 

Why it is important to create a Class in Java?

The property of the class is to combine all the properties and behaviors of an object in a program into a single unit.  A class is a template or blueprint that describes the behavior/states that an object of its type supports. 

What is an Object?

Any real-world entity with well-defined properties is called an Object. An Object will have a state, behaviors, and unique identity. An object can be tangible (physical entity) or intangible (cannot be touch or feel). 

There are three main characteristics of Objects, 

  • State: Represents the data of an object. 
  • Behavior: Represents the behavior of an object such as deposit, withdrawal, etc. 
  • Identity: It is used internally by the JVM to identify each object uniquely. 

What is a Class?

A class defines its object properties and object behavior through methods. A class is a template for a collection of objects that share a common set of attributes and behavior. In the perspective of Object-Oriented programming, a class is a description of the object. It describes the data that each object possesses and it also describes the various behaviors of the object. 


In the above example, you can see a class name Car and with its three different objects Car1, Car2, and Car3 having their own behavior and identity. 
Example of class:
public class Car {
   String carColor;
   String carBrand;
   String fuelType;
}

Example of object:
Car objCar = new Car();

Attribute Declaration. 

Attributes / Fields are used to declare the properties of a class. These attributes are called instance variables. They can be intrinsic types like int, boolean, etc, or user-defined types. 

example: private double salary;

Method Declaration. 

Methods describe the responsibility of the class. These methods are common for all objects. Hence they are known as instance methods. A method always has a name and a return type and it can accept parameters. 

example:
public void calculateArea(int height) {
     int result = height*height;
  System.out.println(result);
}  

Read Input From User in Java.

Java User Input

In Java, Input can be read from the keyboard in many ways. One such way is to use the predefined/inbuilt class Scanner which is present in java.util package. Predefined/inbuilt classes in Java are organized in the form of packages. To use Scanner class, include package java.util using import statement as:

//import just a Scanner class
import java.util.Scanner;

//import the entire package java.util
import java.util.*;

Next, create a Scanner object to give input from the system from the given keyboard.

  • Scanner sc = new Scanner(System.in);
import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter Roll No: ");
		int rollNo = sc.nextInt(); //integer input
		
		System.out.println("Enter Student name: ");
		String name = sc.next();  //single word input
		
		System.out.println(rollNo+" : "+name);
	}
}
Output:
Enter Roll No:
112
Enter Student name:
John
112 : John

Like in the above example, the Scanner class has methods to get input of various data types. 

Methods Data Type
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLong() Short
nextBoolean() Boolean
next() Single word (String without space)
nextLine() String without space
* For next() :even if you try to input multiple words, the will takes the first word only as input


Important note: Reading String using nextLine().

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Student name: ");
String name = sc.next();

System.out.println("Enter the Address: ");
String address = sc.nextLine();

System.out.println("Name: "+name+" Address: "+address);

When you will execute the above code, the address will not be taken as input because Scanner skips the nextLine() when it is used after the next() or nextXxx() (ex: nextInt()) method. It is because the next() reads only the String, not the new line, and nextLine() consumes the next line (\n) as input, hence no input is received. 

To overcome this problem, when using nextLine() after next() or nextXxx(), consume the new line by including the statement sc.nextLine(). See the below example to understand more. 

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter Roll No: ");
		int rollNo = sc.nextInt();
		
		//captures the new line 
		sc.nextLine(); 
		System.out.println("Enter Student Full Name: ");
		String name = sc.nextLine();
		
		System.out.println(rollNo+" : "+name);
	}
}
Output:
Enter Roll No: 
112
Enter Student Full Name: 
John Gupta
112 : John Gupta

Binary Search Algorithm in Java.

Given a sorted integer array arr[] of size n and a target element X, the task is to write a Java program to find and return the index of the target from the given array. Return -1 if the target element is not present in the array.

Example:

Input: arr[] = {1, 2, 3, 4, 5, 6, 8} X = 4
Output: Element found at index 3

Input: arr[] = {3, 5, 10, 11, 12} x = 6
Output: Element not found in the array

Binary search and Linear search are the two most popular search algorithms and binary search is more efficient because its time complexity is less than linear search. But the important thing to note is that binary search is only applicable to a sorted array. 


Binary Search Algorithm.

The Binary Search Algorithm is based on the idea of comparing the target value with the middle element of the array. If the target value is equal to the middle value of the array then searching is complete. If they are not equal and the target value is smaller than the middle value, we will continue searching on the left side of the array. If the target value is larger than the middle value, we will continue searching on the right side of the array. 


Steps for Binary Search Algorithm:

  • Initialize the left and right pointer as low = 0, high = n-1. 
  • While low <= high, compare the middle element arr[mid] of the array with target value x. 
  • If the middle element matches with target arr[mid] = x, return the index of the middle element mid.
  • If the target is less than the middle element arr[mid] > x, continue searching the left half. (high = mid - 1)
  • If the target is larger than the middle element arr[mid] < x, continue searching the right half. (low = mid + 1)
  • If the target element is not found, return -1.

Java Program for Binary Search Using Iteration.

// Java code to search the target element using binary search
public class BinarySearch {

    public static int binarySearch(int[] arr, int target) {
        int left = 0, right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1; // Element not found
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int target = 5;

        int result = binarySearch(arr, target);

        if (result != -1) {
            System.out.println("Element found at index " + result);
        } else {
            System.out.println("Element not found in the array");
        }
    }
}
Output:
Element found at index 4

Time Complexity: Binary search has a time complexity of O(log n), where n is the number of elements in the array. This is because, with each comparison, the size of the remaining array is halved.

Space Complexity: Binary search has a space complexity of O(1). It doesn't require additional memory that scales with the size of the input.

Java Program for Binary Search Using Recursion.

// Java code for Binary Search to target element using Recursion
public class BinarySearch {

    public static int binarySearchRecursive(int[] arr, int target, int left, int right) {
        if (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                return binarySearchRecursive(arr, target, mid + 1, right);
            } else {
                return binarySearchRecursive(arr, target, left, mid - 1);
            }
        }

        return -1; // Element not found
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int target = 5;

        int result = binarySearchRecursive(arr, target, 0, arr.length - 1);

        if (result != -1) {
            System.out.println("Element found at index " + result);
        } else {
            System.out.println("Element not found in the array");
        }
    }
}
Output:
Element found at index 4

Time Complexity: O(log n) where n is the size of the given array. 

Space Complexity: O(log n) because extra stack space is required to perform Recursion.

Java Program for Binary Search Using Built-in Function.

In Java, you can use the Arrays.binarySearch() method to perform a binary search on an array. This method is part of the java.util package and is designed to work with arrays that are already sorted.

Java Code:
// Binary Search Built-in Function in Java to search 
// an element in sorted array
import java.util.Arrays;

public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int target = 6;

        // Sorting the array (required for binary search)
        Arrays.sort(arr);

        // Using binarySearch method
        int result = Arrays.binarySearch(arr, target);

        if (result >= 0) {
            System.out.println("Element found at index " + result);
        } else {
            System.out.println("Element not found in the array");
        }
    }
}
Output:
Element found at index 5

Time Complexity: The Arrays.binarySearch() method has a time complexity of O(log n), similar to a standard binary search algorithm.

Space Complexity: The Arrays.binarySearch() method has a space complexity of O(1). It doesn't require additional memory that scales with the size of the input.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo