Comparable and comparator in java with example – Comparable vs Comparator in Java with Example | When to Use Comparable and Comparator in Java?

Comparable vs Comparator in Java with Example

Comparable and comparator in java with example: Comparable in Java is an interface that is present in java.lang package. A comparable object is used to comparing itself with other objects. The objects of classes that implement the Comparable interface can be ordered. In other words, classes that implement the Comparable interface contain an object that can be compared in some meaningful manner. It contains only one method named compareTo(Object obj).

Method Used in Comparable

Comparable vs comparator java: public int compareTo(Object obj): The compareTo(Object obj) method is used to compare the current object with the specified object.

  1. It returns a positive integer value if the current object is less than the specified object.
  2. It returns a negative integer value if the current object is greater than the specified object.
  3. It returns zero if the current object is equal to the specified object.

Example to Demonstrate compareTo(Object obj) Method

class compareToExample{
public static void main(String args[]){
System.out.println("A".compareTo("B"));
System.out.println("B".compareTo("A"));
System.out.println("A".compareTo("A"));
}
}

Output:

-1
1
0

When to Use Comparable in Java with Example?

How to use comparable in java: If we want to sort the elements according to the default natural sorting order then we should go for Comparable interface. If we go for default natural sorting order then the object should be homogeneous and comparable. An object is said to be comparable if its corresponding class implement the Comparable interface. All the String and Wrapper classes by default implement the Comparable interface. Therefore if you want to sort the String element then you don’t need to implement a Comparable interface.

Read More Articles:

Comparable Example in Java

Comparator and comparable java example: Suppose you have a class Employee and you want to sort employee id on the basis of natural sorting order which is ascending order for numbers and alphabetical order for String then you can implement Comparable interface with the Employee class and override the CompareTo(Object obj) method of Comparable interface. We can sort the element of the String object, wrapper class object, and user-defined class object. Here we have discussed the user-defined class object.

import java.util.*;
class Employee implements Comparable{
int eid;
String name;
int age;

//constructor for initialize the value
Employee(int eid,String name,int age){
this.eid=eid;
this.name=name;
this.age=age;
}

//compareTo() method.
public int compareTo(Employee emp){
if(eid==emp.eid)
return 0;
else if(eid>emp.eid)
return +1;
else
return -1;
}
}

public class ComparableDemo{
public static void main(String args[]){

ArrayList al=new ArrayList();
al.add(new Employee(101,"Amit",23));
al.add(new Employee(106,"Ajay",27));
al.add(new Employee(102,"Vijay",29));
al.add(new Employee(120,"Sumit",32));
al.add(new Employee(105,"Rahul",28));

//call sort() method of collection interface
Collections.sort(al);

//for each loop to print the employee details
for(Employee emp:al){
System.out.println(emp.eid+" "+emp.name+" "+emp.age);
}
}
}

Output:

Comparable vs Comparator in Java with Example 1

Comparators in Java

Java comparator comparable: Comparators in Java is an interface that is present in java.util package. Sometimes we do not satisfy with the default natural sorting order then we should go for Customized sorting order. For customized sorting order we need to specify a Comparator when you construct a tree set. The comparator interface contains two methods:

Method Used in Comparator

1. public int compare(Object obj1, Object obj2): This method is used to compare the first object with the second object. It is similar to the compareTo(Object obj) method of Comparable interface. This method returns a positive integer value if obj1 is greater than obj2, and returns a negative integer value if obj1 is less than obj2. If the obj1 and obj2 are equals then it returns 0. A ClassCastException has occurred if the types of the objects are not compatible for comparison.

2. public boolean equals(Object obj): This method is used to compare the current object with the specified object. Overriding equals() method is optional because it is already available in every Java class from Object class through inheritance.

Comparator Example in Java

Java comparable vs comparator: In this example, we are going to show you how we use a comparator for customized sorting order. Here we are trying to insert integer value in the tree set according to descending order(own customized order). Let’s understand this with a simple example

import java.util.*;
class ComparatorDemo{
public static void main(String args[]){
TreeSet tset = new TreeSet(new MyComparator());
tset.add(10);
tset.add(40);
tset.add(20);
tset.add(30);
tset.add(60);
tset.add(50);

//displaying custom sorted order
System.out.println("Custom sorted order is: " +tset);
}
}

//our own class implements comparator interface
class MyComparator implements Comparator{
public int compare(Object obj1, Object obj2){

//typecast to an integer.
Integer I1 = (Integer)obj1;
Integer I2 = (Integer)obj2;
if(I1<I2) return +1; else if(I1>I2)
return -1;
else
return 0;
}
}

Output:

Comparable vs Comparator in Java with Example 2

What is the Difference Between Comparable and Comparator in Java?

Comparable vs Comparator in Java with Example 3

Python Programming – Constants

Python e constant: In this Page, We are Providing Python Programming – Constants. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Constants

Constants

math.pi
The mathematical constant π.

math. e
The mathematical constant e.

>> math.e
2.718281828459045

Number-theoretic and representation functions

math . ceil ( x )
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.

>>> import math 
>>> math . ceil ( -3 . 2 )
-3 . 0
>>> math . ceil ( 3 . 2 )
4 . 0

math . copysign ( x , y )
Return x with the sign of y.

>>> math . copysign ( 5 . 1 , -2 . 8 )
-5 . 1
>>> math . copysign ( -5 . 1 , 2 . 8 )
5 . 1

math . tabs ( x )
Return the absolute value of x.

>>> math . fabs ( - 4 . 2 )
4 . 2

math . factorial ( x )
Return x factorial. Raises ValueError, if x is not integral or is negative.

>>> math . factorial ( 5 ) 
120 
>>> math . factorial ( -5 ) 
Traceback ( most recent call last ) :
File "<stdin>", line 1, in <module>
ValueError: factorial ( ) not defined for negative values

math . floor ( x )
Return the largest integer value less than or equal to x as a float.

>>> math . floor ( -3 . 2 )
-4 . 0
>>> math . floor ( 3 . 2 )
3 . 0

math . fmod ( x , y )
Return remainder of a division expression. Note that the Python expression x%y may not return the same result. The result of fmod (x, y) has same sign as x, while x%y returns a result with the sign of y instead.

>>> math . fmod ( 5 . 0 , -2 . 0 )
1 . 0
>>> 5 . 0% -2 . 0 
-1 . 0
>>> math . fmod ( -5 . 0 , 2 . 0 )
-1 . 0
>>> -5 . 0 % 2 . 0
1 . 0

Consider the following interesting scenario.

>>> math . fmod ( -1e-100 , 1e100)
-1e-100 
>>> -1e-100 % 1e100
1e +100

It can be observed that fmod (-1e-100 , 1e100) returns -1e-100, but the result of Python’s – 1e-100%1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod ( ) is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math . frexp ( x )
Return the mantissa and exponent of x as the pair (m, e). The m is a float and e is an integer such that x = m x 2e exactly. If x is zero, returns ( 0 . 0 , 0 ) , otherwise 0 . 5<=abs ( m ) <1.

>>> math . frexp ( 4 . 0 )
( 0 . 5 , 3 )
>>> 0 . 5*2**3
4 . 0
>>> math . frexp ( 0 . 1 )
( 0 . 8 , -3 )
>>> 0 . 8* 2**-3
0 . 1
>>> math . frexp ( -4 . 0 )
( -0 . 5 , 3 )
>>> -0 . 5*2**3
- 4 . 0

math.fsum(iterable)
Return an accurate floating point sum of values in the iterable.

>>> math . fsum ( [ . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 , . 1 ] )
1 . 0

math . isinf ( x )
Check if the float x is positive or negative infinity.

>>> a=1e+300
>>> a
1e+300
>>> math . isinf ( 1e+300 )
False
>>> a=1e+310
>>> a
inf
>>> math . isinf ( 1e+310 )
True

Calculating an exponent with floating point values, in particular, raises Overf lowError instead of preserving the inf result.

>>> a=10 . 0**310

Traceback ( most recent call last ) :
File "<pyshell#l>", line 1, in <module>
    a=10 . 0**310
OverflowError: (34 , ' Result too large ' )

math . isnan ( x )
Check if the float x is a nan (not a number), nan does not compare as equal to any value, even itself, so nan should be checked using isnan () function.

>>> a=1e+310
>>> a
inf
>>> b=a/a
>>> b
nan
>>> math . isnan ( a )
False
>>> math . isnan ( b )
True

math . ldexp ( x , i )
Return x* (2**i). This function is reverse of function frexp ( ).

>>> math . 1dexp ( -0 . 5 , 3 )
-4 . 0
>>> -0 . 5*2**3
-4 . 0
>>> math . ldexp ( 0 . 8 , -3 )
0 . 1
>>> 0 . 8*2**-3
0 . 1

math . modf ( x )
Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

>>> math . modf ( 1 . 5 )
( 0 . 5 , 1 . 0 )

>>> math . modf ( -1 . 5 )
( -0 . 5 , -1 . 0 )

math . trunc ( x )
Return the real value x truncated to an integer.

>>> math . trunc ( 93 . 2508 )
93
>>> math . trunc ( -93 . 2508 )
-93

Power and logarithmic functions

math . exp ( x )
Return ex.

>>> math . e**-3 . 2
0 . 04076220397836622
>>> math . pow ( math . e , -3 . 2 )
0 . 04076220397836622
>>> math . exp ( -3 . 2 )
0 . 04076220397836621

math . expm1 ( x )
Return ex-1. For small floats x, the subtraction in exp(x)-1 can result in a significant loss of precision; the expml ( ) function provides a way to compute this quantity to full precision:

>>> x=0 . 0000000000000000000000001
>>> math . exp ( x ) , -1
0 . 0
>>> math . expm1 ( x )
1e - 25

math . log ( x [ , base ] )
With one argument, return the natural logarithm of x (to base e). With two arguments, return the logarithm of x to the given base, calculated as log (x) / log (base).

>>> math . log ( 9 )
2 . 1972245773362196
>>> math . log ( 9 , 2 )
3 . 1699250014423126

math . loglp ( x )
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

>>>x=0.0000000000000000000000001
>>> X
1e-25
>>> 1+x
1 . 0
>>> math . 1og ( 1 +x )
0 . 0
>>> math . 1og1p ( x )
1e-25

math . 1og10 ( x )
Return the base-10 logarithm of x. This is usually more accurate than log (x, 10).

>>> math . 1og10 ( 100 )
2 . 0
>>> math . 1og10 ( 10000 )
4 . 0

math . pow ( x , y )
Return x raised to the power y. In particular, pow ( 1 . 0 , x ) and pow ( x , 0 . 0 ) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow (x, y) is undefined, and raises ValueError.

>>> math.pow ( 9 . 0 , 0 . 5 )
3 . 0
>>> math . pow ( -9 . 0 , 0 . 5 )
Traceback ( most recent call last ) :
File "<stdin>" , line 1 , in <module>
ValueError: math domain error

Unlike the built-in * * operator, math. pow ( ) converts both its arguments to type float.

math . sqrt( x )
Return the square root of x. Computing the square roots of negative numbers requires complex numbers, which are not handled by math module. Any attempt to calculate a square root of a negative value results in ValueError.

>>> math . sqrt ( 9 . 0 )
3 . 0
>>> math . sqrt ( -9 , 0 )

Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
math . sqrt ( -9 . 0 )
ValueError: math domain error

Trigonometric functions

math . acos ( x )
Return the arc cosine of x, in radians.

>>> math . acos ( 0 . 5 )
1 . 0471975511965979

math . asin ( x )
Return the arc sine of x, in radians.

>>> math . asin ( 0 . 5 )
0 . 5235987755982989

math . atan ( x )
Return the arc tangent of x, in radians.

>>> math . atan ( 0 . 5 )
0 . 4636476090008061

math . atan2 ( y , x )
Return atan(y/x), in radians. The resuit is between -TI and TI. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2 () is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan (1) and atan2 (1,1) are both n /4, but atan2 (-1,-1) is -3#/4.

>>> math . atan ( 1 . 0 )
0 . 7853981633974483
>>> math . pi / 4
0 . 7853981633974483

math . cos ( x )
Return the cosine of x radians.

>>> math . cos ( 0 . 7853981633974483 )
0 . 7071067811865476

math . hypot ( x , y )
Return the Euclidean distance, \(\sqrt{x^{2}+y^{2}}\) . This is the length of the vector from the origin to point (x,y).

>>> math . hypot ( 3 . 0 , 4 . 0 )
5 . 0

math . sin ( x )
Return the sine of x radians.

>>> math . sin ( 0 . 7853981633974483 )
0 . 7071067811865475

math . tan ( x )
Return the tangent of x radians.

>>> math.tan ( 0 . 7853981633974483 )
0.9999999999999999

Angular conversion

math . degrees ( x )
Converts angle x from radians to degrees.

>>> math . degrees ( 1 . 5707963267948966 )
90 . 0
>>> 1 . 5707963267948966*180 / math . pi
90 . 0

math . radians ( x )
Converts angle x from degrees to radians.

>>> math . radians ( 90 )
1 . 5707963267948966
>>> ( 90*math . pi ) / 180
1 . 5707963267948966

Hyperbolic functions

math . acosh ( x )
Return the inverse hyperbolic cosine of x.

>>> math . cosh ( 1 . 0 )
1 . 5430806348152437

math . asinh ( x )
Return the inverse hyperbolic sine of x.

>>> math . asinh ( 1 . 0 )
0 . 8813735870195429

math . atanh ( x )
Return the inverse hyperbolic tangent of x.

>>> math . atanh ( 0 . 8 )
1 . 0986122886681098

math . cosh ( x )
Return the hyperbolic cosine of x.

>>> math . cosh ( 0 . 7853981633974483 )
1 . 3246090892520057

math . sinh ( x )
Return the hyperbolic sine of x.

>>> math . sinh ( 0 . 7853981633974483)
0 . 8686709614860095

math . tanh ( x )
Return the hyperbolic tangent of x.

>>> math . tanh ( 0 . 7853981633974483 )
0 . 6557942026326724

Special functions

math . erf ( x )
Return the error function at x.

>>> math . erf ( 0 . 25 )
0 . 2763263901682369

math . erfc ( x )
Return the complementary error function at x i.e. 1-erf (x).

>>> math . erf c ( 0 . 25 )
0 . 7236736098317631

math . gamma ( x )
Return the gamma function at x.

>>> math . gamma ( 5 . 5 )
52 . 34277778455352

math . lgamma ( x )
Return the natural logarithm of the absolute value of the gamma function at x.

>>> math . 1 gamma ( 5 . 5 )
3 . 9578139676187165

C++ projects ideas – Simple Project Ideas in C++ for Beginners | Some of the Best C++ Project Topics that you can Try

Project Ideas in C++ for Beginners

Project Ideas in C++ For Beginners: Google Chrome, Youtube, Adobe Photoshop, Doom 3. Grand names, various industries yet used by clients around the world with great enthusiasm. Apart from the widespread consumer base, there is another common thread, C++, which ties all these brands together. If you’re a beginner, working with some C++ project ideas in real-time is the most pleasing thing you can do.

In this article, you can study some fascinating concepts from C++ projects that can be tested for Python by beginners. In this article, you will find the best projects for Python beginners.

About C++ Programming Language

C++ project ideas for beginners: A C-prototype programming language has developed into one of the most sought-after and adaptable languages. It is handily integrated into a wide range of online applications with more graphical and object-driven programming. Designed as a free form language, C++ has many libraries, additional functions, and data structures and includes updated C language capabilities.

Coding C++ projects can be used to implement advanced software methods like polymorphism, abstractions, encapsulation, and legacy. That’s why C++ has evolved to become one of the most popular languages of software writing since its birth in 1979. In the present world, where our lives are closely intertwined with the digital landscape, virtually everywhere you stumble upon C++.

Our opening sentence suggests that when you are involved in eCommerce activities, online entertainment, knowledge center, design maneuvers, gaming, workflow, or even financing management, you are likely to use web applications that carry on one or two activities to take advantage of C++ projects.

Why do Developers Develop Project Ideas using C++?

C++ projects ideas: For several highly apparent purposes, C++ seems to prefer to learn for some undeniable reasons those who work with embedded systems and systems programming, including the operating systems and hardware interfaces. First of all, comparable to C, C++ is a programming language that may be perfectly adapted and innovated afterward.

It is a straightforward language to capture, in terms of abilities, since it consists of pure notions and syntax understandable. In addition, C++ is a very flexible and dynamic language that has provided several technological features in sectors like electronics, automotive, robotics, and many more. It was achievable because developers found it convenient to include C++ into these industries’ established operating frameworks. C++ is also very compatible with a broad range of platforms and systems, and it is not just easy to scribe.

It enables the use of C++ to design new technical inputs. Thus, C++ is the coding language of all future technology, loaded with the deliciousness of C and improved features.

See More:

Which Industries Predominantly Use C++ Projects?

  • Graphic design-In every nook and corner of the earth, digital art has made its imprint. Although some may view it as a substitute for canvas-based skills, it is better to view it as a different industry. For their advertising, most artists rely on digital art. Furthermore, graphic design plays a central role in the corporate and marketing sector, from logo design to presentation templates. C++ is the natural choice for all web developers, given its reliance on graphical user interfaces. C++ was used to construct Web apps and software such as Adobe Photoshop and Illustrator.
  • Animation- Two-dimensional animation shows gone days that would fascinate us as children. The animation scope has extended and evolved every day in the last few days. Essentially sophistication has led to such rapid improvements in the programming language. Contemporary animation in the form of high-resolution 3-D animation, rendering, modeling, and simulation on both large displays and web portals is also available. Indeed, CGIs have gotten wild, even in regular films, where they are often used. The process behind these developments involves image processing, sensor applications, and real-time visual effects. Each of these codes is usually written into C++.
  • Operating Systems and Web Browsers- We saw how the C language was essential to the creation of sophisticated OSes. C++ can be ascribed as an updated version to the development of most Microsoft-based operating systems and Symbian and iOs systems. In the same breath, C++ was chosen as the media for constructing browsers such as Google Chrome and Mozilla Firefox, thanks to its ability to cluster data files effortlessly.
  • Media Management- We no longer need to rely on cumbersome audio cassettes and CD ROMs to listen if we want to. We can settle in our favorite music from our selected gadgets anytime through web programs such as Spotify, Wynk, or even iTunes. Audio and video sharing files encoded in C++ have made this possible. It must be assigned to the same media access files that were created in C++ that Netflix has become many of our favorite leisure.
  • Database Access- Knowledge is power, and there’s absolutely no lack of information in these days of information technology. Whether it’s a sophisticated topic or a triviality about your local celebrities, whether it’s a scarce cuisine from another side of the world or the latest NASA findings, everything is just a search away via Google. Once again, the treasuries of tech-speaking data or databases, such as the open-source database such as MySQL or software applications such as Wikipedia and Youtube, are developed with C++.

To know more about the C++ Programming Language check out our CPP Programming Tutorial and grasp the fundamentals behind them.

What Novel Concepts can be Developed with C++ in the C Project?

C++ project ideas: This list of C++ student project ideas is suitable for beginners and programmers generally. These C++ ideas for projects will provide you with all you need to carry on your software developer profession successfully.

In addition, this list should get you began if you are seeking C++ project ideas for the last year. So let’s go directly to a few C++ project ideas without further ado, which will reinforce your base and let you ascend the ladder.

After we have taken on the history and widespread use of C++ and found that C++ provides developers with an abundance of innovation as a coding language, let’s look at specific prototypes and projects in C++ that can aid C++ developers.

Security Systems

C++ project ideas for beginners: Regardless of the increasing terrorist rate, supervision or safety have been increased everywhere, irrespective of whether airports or offices, Malls, or even entrances to condominiums, all over the world. A key role is webcams and CCTVs. However, biometric and facial recognition techniques are being applied in other verticals for more advanced safety measures.

The present facial recognition systems can be improved with C++. C++ libraries for OpenCV probably can help identify face characteristics on either video cameras or live webcam broadcasts. These may serve to regulate admission and reduce further intervention and inspections by humans.

Car Rental System

C++ project idea: The introduction of Uber and Ola cabs has made the lives of smartphone users endlessly easier. However, there are also restrictions on these apps. It can be a terrific C project concept to change the same principle and take it much higher using C++ codes. Developers can consider using C++ in JSON Format text files to save user and cab services GPS coordinates within a given space.

C++ libraries enable the user to cover a broad perimeter compared to other existing rental services so that this application can genuinely link the user to more expansive geography. Then developers can connect the user to the most appropriate services using login credentials. This program can continue to revise its price, safety, preferences, etc., characteristics.

Dating Applications

C++ ideas: It was days when love was in the air. However, love now appears on our smartphones, and web apps have readily accepted the roles of cupids. C++ and flexible, object-oriented program support allow a wide range of information to be saved and analyzed.

This program can import and recover a high volume of data entries by integrating two elements while maintaining the safety characteristics sacrosanct. First, the program can simulate users’ tastes and personalities using string capabilities, and the most compatible match based on the two criteria is achieved.

Employee Management System

Advanced c++ projects: Imagine an e-journal which not just handles your business every day but helps you keep track of all the records of your employees. Furthermore, it is possible to add, delete or alter entries with C++ source code for your convenience.

The C++ library blocks are an excellent way to construct a management system of this type. However, to improve the system functionality and features, developers can add other open source libraries. For example, both a web portal and a mobile app can be developed with C++.

Trading Software

Ideas for c++ projects: The most volatile industries worldwide are trade and stock markets. It could take a turn in seconds for better or worse. News channel trailer traditionally reflects stock market update, but C++ coders can design an application synchronized in real-time with stock market statistics and filter the data according to user preferences.

Experts’ notifications, advisories, and commentary are additional elements that can enhance the app and make it a lovely financial management tool.

Billing System

C++ program ideas: Many of our services, for example, water charges, power bills, maintenance fees, are subject to a particular cycle of invoices. Often in transportation, actual bills are misplaced or are delayed. To avoid all this, we can again rely on C++ to produce an e-billing system with the source code that synchronizes our e-wallets or bank accounts to the receiver’s accounts.

It can generate the bill automatically and inform us of the due dates of our systems. Users can choose to make auto-debit or, via this application, choose to make manual payments.

Intuitive Gadgets

Cool c++ projects: C++ is an embedded systems language that is beneficial in the development of application software and in combining software and hardware pieces from the internet to improve compatibility, for example, with smart clockwork, smart TV, and home assistants. In addition, C++ can program and make consumers appeal to new features and more interactive traits in these devices.

Traffic Management System

Traffic checks are pretty strict in a developed country like ours, where cities continually bustle with automobiles and feet. However, our roads can fundamentally improve safety and travel hassle-free by automating our signals with sensors, speed restrictions, and various safety elements.

It also shelves the discomfort of standing under the sun all day long to control a raw din in these deficient traffic control systems. Signals and signs are necessary, and road traffic can be controlled remotely. The coding and hardware required embedding will also be simplified by the C++ database.

Conclusion

We discussed seven projects C++ in this article. We started with some starting projects that you may quickly solve. Going back, studying a few additional ideas is recommended, and then test intermediate applications once you have completed the simple C++ projects. You can then deal with advanced tasks when you are confident. You need to take advantage of these C++ project ideas to develop your skills.

GitHub vs. GitLab: Difference Between GitHub and GitLab | Which is Right For You?

GitHub vs. GitLab Difference Between GitHub and GitLab

GitHub vs. GitLab: Difference Between GitHub and GitLab: Both GitLab and GitHub refer to the topmost web-based repositories aiding in the management of codes and file sharing with any other remote repository. Because the files on the internet change often, all of the data gets stored in a repository and may be accessed at any time. Both GitHub and GitLab are required for Git development to track changes in a source code.

Making changes to existing source code and, in some cases, developing new source code is all part of the software development life cycle (SDLC). However, because most developers were working on separate portions of the code at the same time, the changes in the code may sometimes conflict. This will very certainly create unwelcome flaws in the software. While these may not have an immediate impact on software development, they may cause severe faults in the future, making it difficult to pinpoint the error zone.

Refer to this article on GitHub vs. GitLab: Difference Between GitHub and GitLab to become familiar with the Pros and Cons of each one of them and choose based on your requirement.

Key Differences and Similarities between GitHub and GitLab

What is the difference between github and gitlab: Repository management like GitHub and GitLab comes in handy here. They safeguard the source code against defects and inconsistencies. Running the code files via either of the two systems makes it simple to track changes. It can be tough to pick between GitHub and GitLab because they are both version control systems (VCS).

The most significant distinction between the two is that, while GitHub is a remote code review and management platform, GitLab is primarily focused on DevOps and CI/CD. GitLab has currently gained immense popularity as the company continuously adds the latest features to make it user-friendly and also more competitive. On the other hand, GitHub is more popular among developers because it holds millions of repositories.

GitHub vs. GitLab: What’s the Difference?

Git hub vs git lab: Let’s compare and contrast GitHub with GitLab. Both GitHub and GitLab allow developers to manage source code and keep track of local file changes. These updates can also be shared with a remote repository by developers. However, there are substantial distinctions between the two systems.

Feature GitHub GitLab
Fees With publicly published codes, GitHub projects are free and open to everybody. GitLab is a code repository where only its team of web engineers may collaborate.
Location In the free plan, GitHub does not allow you to locate a repository within an organization. While making use of the free plan, GitLab lets the users locate a repository within an organization.
Issue Tracker The issue tracker supports pulling requests, which means that when issues are merged to another repository, they are automatically closed. The issue tracker allows users to link issues to PRs so that they can be closed automatically.
Documentation GitHub documents are structured into a series of guidelines, each of which focuses on a different platform. GitLab docs are like the language documentation where they include a search bar and a list of all the required documents by the installer.
Integration In GitHub, there is no built-in continuous integration. Instead, third-party providers are in charge of providing it. GitLab has a built-in integration that works well. However, they prefer to use their integration tools, which are constantly updated.
Authentication Authenticating who has access to and who does not have access to the repository can be done based on their function. A developer can decide whether or not someone should be able to access a repository in this situation.
Community GitHub is home to a sizable developer community. It has millions of active users for debating the issues. GitLab offers community events bringing the open-source contributors together.
Platform It has a development platform where projects can be stored. In addition, it has features like task management, bug tracking, and so on. GitLab refers to a web-based DevOps tool to better manage the internal repositories.
Inner-sourcing Internal repositories can be sourced from within by developers. Inner sourcing is not allowed in GitLab.
Confidential Issues This module produces the private issues only visible to project participants. The confidential issue feature is also absent in GitLab.

Github Pros and Cons

Here are the pros of Github:

  • For the open-source codebase, this is an incredible system.
  • Allows for simple sharing
  • It offers pull requests and comments and has a sophisticated and user-friendly UI.
  • It has a sizable population
  • Remote collaboration is possible because of the simple setup.
  • It has features that make it simple to control.

Here are the cons of Github:

  • It doesn’t have a great API development team
  • For the ones looking for a private repository, it’s a bit pricier.
  • It does not have many features.

Do Refer:

GitLab Pros and Cons

Here are the pros of GitLab:

  • It has a steady stream of fresh features
  • Availability of code reviews as well as the Pull requests.
  • Has a fantastic CLI experience
  • Provides package management services.
  • The CI/CD lifecycle is supported.
  • Codes are simple to maintain.

Here are the cons of GitLab:

  • Problematic upgrade procedure
  • Some enterprise-level functionalities are missing.
  • The program has many bugs
  • a small group of people constitutes the community

Conclusion

GitLab may be better if you have more flexible requirements and you wish to save some money. However, if you’re going to put your faith in a community of over 40 million developers, GitHub is the way to go. Because of its big community and user-configurable structure, GitHub availability is higher and more prevalent among developers. In contrast, GitLab is powerful and offers more entrepreneur-friendly features and plans. GitLab has several noticeable advantages over GitHub, including creating an unlimited number of private repositories and a built-in continuous integration system.

The platform each ideology presents is the main distinction between GitHub and GitLab. GitLab is more focused on giving a features-based system with a centralized, integrated platform for web developers, whereas GitHub offers superior availability and focuses more on infrastructure performance. If you’re working on a larger project with a group of developers, GitHub may be the best option. GitLab, on the other side, can be used if the project requires continuous integration.

xml interview questions – SQL Server Interview Questions on XML Integration

xml interview questions: We have compiled most frequently asked SQL Server Interview Questions which will help you with different expertise levels.

SQL Server Interview Questions on XML Integration

Note  In this chapter we willfirst just skim through basic XML interview questions so that you 
         do not get stuck up with simple questions.

Question 1.
What is XML?
Answer:
XML (Extensible markup language) is all about describing data. Below is a XML which describes invoice data.

<?xml version="1.0 " encodings"ISO-8859-1"?>
<invoice>
<productname>Shoes</productname>
<qty>12</qty>
<totalcost>100</totalcost>
<discount>10</discount>
</invoice>

An XML tag is not something predefined but it is something you have to define according to your needs. For instance in the above example of invoice all tags are defined according to business needs. The XML document is self explanatory, any one can easily understand looking at the XML data what exactly it means.

Question 2.
What is the version information in XML?
Answer:
“version” tag shows which version of XML is used.

Question 3.
What is ROOT element in XML?
Answer:
In our XML sample given previously <invoicex/invoice> tag is the root element. Root element is the top most element for a XML. .

Question 4.
If XML does not have closing tag will it work?
Answer:
No, every tag in XML which is opened should have a closing tag. For instance in the top if I remove </discount> tag that XML will not be understood by lot of application.

Question 5.
Is XML case sensitive?
Answer:
Yes, they are case sensitive.

Question 6.
What’s the difference between XML and HTML?
Answer:
XML describes data while HTML describes how the data should be displayed. So HTML is about displaying information while XML is about describing information.

Question 7.
Is XML meant to replace HTML?
Answer:
No they both go together one is for describing data while other is for displaying data.

Question 8.
Can you explain why your project needed XML?
Answer:

Note  This is an interview question where the interviewer wants to know why you have chosen XML.

Remember XML was meant to exchange data between two entities as you can define your user friendly tags with ease. In real world scenarios XML is meant to exchange data. For instance you have two applications who want to exchange information. But because they work in two complete opposite technologies it’s difficult to do it technically. For instance one application is made in JAVA and the other in .NET. But both languages understand XML so one of the applications will spit XML file which will be consumed and parsed by other application.s
You can give a scenario of two applications which are working separately and how you chose XML as the data transport medium.

Question 9.
What is DTt> (Document Type definition)?
Answer:
It defines how your XML should structure. For instance in the above XML we want to make it compulsory to provide “qty” and “totalcost”, also that these two elements can only contain numeric. So you can define the DTD document and use that DTD document with in that XML.

Question 10.
What is well formed XML?
Answer:
If a XML document is confirming to XML rules (all tags started are closed, there is a root element etc) then it’s a well formed XML.

Question 11.
What is a valid XML?
Answer:
If XML is confirming to DTD rules then it’s a valid XML.

Question 12.
What is CDATA section in XML?
Answer:
All data is normally parsed in XML but if you want to exclude some elements you will need to put those elements in CDATA,

Question 13.
What is CSS?
Answer:
With CSS you can format a XML document.

Question 14.
What is XSL?
Answer:
XSL (the extensible Stylesheet Language) is used to transform XML document to some other document. So its transformation document which can convert XML to some other document. For instance you can apply XSL to XML and convert it to HTML document or probably CSV files.

Question 15.
What is Element and attributes in XML?
Answer:
In the below example invoice is the element and the invnumber the attribute.
<invoice invnumber=1002></invoice>

Question 16.
Can we define a column as XML?
Answer:
Yes, this is a new feature provided by SQL Server. You can define a column data type as XML for a table.

SQL Server Interview Questions on XML Integration chapter 7 img 1

Question 17.
How do we specify the XML data type as typed or untyped?
Answer:
If there is a XSD schema specified to the data type then it’s typed or else it’s untyped. If you specify XSD then with every insert SQL Server will try to validate and see that is the data adhering to XSD specification of the data type.

Question 18.
How can we create the XSD schema?
Answer:
Below is the DDL statement for creating XML schema.

CREATE XML SCHEMA COLLECTION MyXSD AS
N'<?xml version="1. 0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
 elementFormDefault="qualified" targetNamespace="http://MyXSD">
  <xs:element name="MyXSD">
    <xs:complexType>
     <xs:sequence>
      <xs:element name="Orderid" type="xs:string" />
      <xs:element name="CustomerName" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
 </xs:element>
</xs:schema>

After you have created the schema you see the MYXSD schema in the schema collections folder.

SQL Server Interview Questions on XML Integration chapter 7 img 2

When you create the XML data type you can assign the MyXsd to the column.

SQL Server Interview Questions on XML Integration chapter 7 img 3

Question 19.
How do I insert in to a table which has XSD schema attached to it?
Answer:
I know many developers will just say what the problem with simple insert statement. Well guys its not easy with attaching the XSD its now a well formed datatype.The above table I have named as xmltable. So we had specified in the schema two nodes one is ordered and the other customername. So here’s the insert.
Insert into xmltable values ( ‘ <MyXSD xmlns=’’http: //MyXSD” ><Orderid>l</ Orderid><CustomerName>Shiv</CustomerNamex/MyXSD> ’)

Question 20.
What is maximum size for XML datatype?
Answer:
2 GB and is stored like varbinary.

Question 21.
What is Xquery?
Answer:
In a typical XML table below is the type of data which is seen. Now I want to retrieve orderid “4”. I know many will jump up with saying use the “LIKE” keyword. Ok you say that an interviewer is very sure that you do not know the real power of XML provided by SQL Server.

SQL Server Interview Questions on XML Integration chapter 7 img 4

Well first thing XQUERY is not that something Microsoft invented, it’s a language defined by W3C to query and manipulate data in a XML. For instance in the above scenario we can use XQUERY and drill down to specific element in XML.
So to drill down here’s the XQUERY

SELECT * FROM xmltable .
WHERE TestXml.exist('declare namespace
xd=http://MyXSD/xd:MyXSD[xd:Orderid eg "4"]’) = 1
Note  It's out of the scope of this book to discuss XQUER Y. I hope and only hope guys many interviewers 
         will not bang in this section. In case you have doubt visit wwzv. w3c.org or SQL Server books online they 
         have a lot of material in to this.

Question 22.
What are XML indexes?
Answer:
XML data types have huge size 2 GB. But first thing is that you should have a primary key on the XML data type column. Then you can use the below SQL statement to create index on the XML column:-

CREATE PRIMARY XML INDEX xmlindex ON xmltable(TestXML)

Question 23.
What are secondary XML indexes?
Answer:
Secondary indexes are built on document attributes.

Question 24.
What is FOR XML in SQL Server?
Answer:
FOR XML clause returns data in XML rather than simple rows and columns. For instance if you fire the below query on any table you will get XML output:-
SELECT * FROM MyTable FOR XML AUTO

Question 25.
Can I use FOR XML to generate SCHEMA of a table and how?
Answer:
The below SQL syntax will return the SCHEMA of the table.

SELECT * FROM MyTable FOR XML AUTO, XMLSCHEMA

Question 26.
What is the OPENXML statement in SQL Server?
Answer:
We had seen that FOR XML returns a XML format of a table data. And open XML does the vice versa of it. If you pass XML document to it will convert it to rows and columns.

Question 27.
I have a huge XML file which we want to load in database?
Answer:
Twist: – Can I do a BULK load of XML in database?
Below is the SQL statement which will insert from “MyXml.xml” in to “MyTable”.

INSERT into MyTable(MyXMlColumn) SELECT * FROM OPENROWSET (Bulk 'c:\MyXml.xml', SINGLE_CLOB) as abc

Question 28.
How to call stored procedure using HTTP SOAP?
Answer:
Twist: – Can I create web services for SQL Server objects?

Note  Ok every one reading this answer out of dedication I have switched off my mobile and lam writing this answer.

You can call a stored procedure using HTTP SOAP. This can be done by creating END POINTS using the “CREATE ENDPOINT” DDL statement. I have created a TotalSalesHttpEndPoint which can be called later through “webservices”.

CREATE ENDPOINT TotalSalesHttpEndPoint
STATE = STARTED
AS HTTP(
   PATH = '/sql ',
   AUTHENTICATION = (INTEGRATED ),
   PORTS = ( CLEAR ),
   SITE = 'server'
   )
FOR SOAP (
    WEBMETHOD 'http://tempUri.org/'. 'GetTotalSalesOfProduct’
              (name='AdventureWorks.dbo.GetTotalSalesOfProduct ’, schema=STANDARD ),
    BATCHES = ENABLED,
    WSDL = DEFAULT,
    DATABASE = 'AdventureWorks ',
    NAMESPACE = 'http://AdventureWorks/TotalSales'
    )

Question 29.
What is XMLA?
Answer:
XMLA stand for XML for Analysis Services. Analysis service is covered in depth in data mining and data ware housing chapters. Using XMLA we can expose the Analysis service data to the external world in XML. So that any data source can consume it as XML is universally known.

Hashtable example in java – Java Hashtable with Example | HashTable Class Declaration, Parameters, Methods, Constructors with Examples

Java Hashtable with Example

hashtable example in java: Want to learn about the Java Hashtable? Then, this is the best & ultimate tutorial for you all. Hashtable stores the key/values pair in a hash table. Both HashMap and HashTable are similar but there are few differences between them which can be known clearly from here.

Also, we will see how to create a Hashtable, how it works internally, methods of java hashtable, some example codes, etc. So, stay tuned to this page and gather enough information on Hashtable Class in Java.

Hashtable in Java

Java Hashtable Class inherits Dictionary class and implements the Map interface. Also, This class implements a hash table. Moreover, it was a part of java.util package. Java Hashtable is the same as HashMap besides it is synchronized.

Java Hashtable class declaration

Here is the declaration for java.util.Hashtable class:

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable

Parameters of HashTable Class

  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

The Hierarchy of Hashtable Class in Java

hierarchy of hashtable class in java

Do Read:

How Hashtable works internally in java?

A Hashtable internally holds buckets in which it stores the key/value pairs. The Hashtable uses the key’s hashcode to specify which bucket the key/value pair should map. When you give a key/value to the Hashtable, it asks the key’s hashcode. The Hashtable uses that code to determine the bucket in which to place the key/value.

Thus, for instance, if the hashcode equals zero, the Hashtable stores the value into Bucket 0. Furthermore, if the hashcode is two, the Hashtable stores the value into Bucket 2. (This is a simple example; the Hashtable will massage the hashcode first so the Hashtable doesn’t try to insert the value outside the bucket.)

With the help of this hashcode approach, the Hashtable can also instantly determine in which bucket it has stored the value when you decide to retrieve it. The hashcode only says the Hashtable into which bucket to drop the key/value. Sometimes, still, multiple objects may map to the same bucket, an event called a collision. In Java, the Hashtable reacts to a collision by storing multiple values into the same bucket (other implementations may work collisions differently).

Features about Java Hashtable

  1. Java Hashtable is the best option in case of frequent operation is to store and retrieves objects from a hash table.
  2. Java Hashtable uses a hash table data structure.
  3. It implements a Serializable, Cloneable interface but not RandomAccessInterface.
  4. Hashtable is thread-safe because every method determines in the Java Hashtable class is synchronized.
  5. Insertion order is not stored and it depends on the hash code of keys.
  6. Duplicates keys are not accepted but values may be duplicated.
  7. Heterogeneous objects are allowed.
  8. Java Hashtable class includes unique elements.
  9. Java Hashtable doesn’t support null keys or null values.

Constructors of Java Hashtable Class

Java Hashtable represents the following constructors.

  1. Hashtable(): The first constructor is used to create a default hash table.
  2. Hashtable(int size): This constructor is used to creates a hash table that has an initial size specified by size.
  3. Hashtable(int size, float load factor): This constructor is used to creates a hash table that has an initial size specified by size and a load factor is specified by the load factor.
  4. Hashtable(Map m): This constructor is used to creates a hash table that is initialized with the elements in m.

Methods of Hashtable Class in Java

  1. void clear(): This method is used to removes all key/values pair from a hash table and make it empty.
  2. Object clone(): It creates a shallow copy of this hash table.
  3. boolean contains(Object value): This method returns true if some value equal to value exists within the hash table and returns false if the key is not found.
  4. boolean containsKey(Object key): This method returns true if some key equal to key exists within the hash table else it returns false.
  5. boolean containsValue(Object value): It returns true if some value equal to value exists within the hash table else it returns false.
  6. Enumeration elements(): It returns an enumeration of the values contained in the hash table.
  7. Object get(Object key): This method is used to remove the object that contains the value associated with a key and returned a null object if the key is not in the hash table.
  8. boolean isEmpty(): It returns true if the hash table is empty else returns false.
  9. Enumeration keys(): It returns an enumeration of the keys contained in the hash table.
  10. Object put(Object key, Object value): This method is used to insert a key-value pair in the hash table.
  11. void rehash(): This method is used to increases the size of the hash table and rehashes all of its keys.
  12. Object remove(Object key): It removes a key and its value and returned a null object if the key is not in the hash table.
  13. int size(): It returns the number of entries in the hash table.
  14. String toString(): This method is used to returns the string equivalent of a hash table.

Java Hashtable Example

import java.util.*;
class HashtableExample{
public static void main(String args[]){

//creating a hash table
Hashtable<String, String> ht = new Hashtable<String, String>();

Enumeration names;
String key;

//adding values in this hash table
ht.put("Key 1", "Rahul");
ht.put("Key 2", "Amit");
ht.put("Key 3", "Vijay");
ht.put("Key 4", "Suresh");
ht.put("Key 5", "Prashant");

//returns size of the hash table
System.out.println("Hash table size is: "+ht.size());

//checks hash table is empty or not
System.out.println("Hash table is empty or not: "+ht.isEmpty());

//returns true if hash table contains specified value
System.out.println("Hash table contains specified value or not: "+ht.containsValue("Prashant"));

names = ht.keys();
while(names.hasMoreElements()){
key = (String)names.nextElement();
System.out.println("Key is: " +key + " & its Value is: " +ht.get(key));
}

ht.clear();
System.out.println("Removes all the key-value pair: "+ht);
}
}

Output:

Java Hashtable with Example 1

Hashtable vs HashMap

Hashtable and HashMap both are part of the java.util and are utilized to save data in the form of key-value pairs. Hashing techniques are used by both to store unique keys. However, there are few differences between Hashtable and HashMap which is very essential to know for achieving the Java related interviews. Let’s focus on the differences between Hashtable and HashMap by viewing the following points:

  1. Hashtable is synchronized while the HashMap is not synchronized.
  2. Hashtable doesn’t allow you to store null key and null value on the other hand HashMap allows you to store one null key and multiple null values.
  3. HashMap was introduced in Java 1.2 while Hashtable is a legacy class.
  4. HashMap is fast while Hashtable is slow due to synchronization.
  5. HashMap is traversed by Iterator while Hashtable is traversed by both Enumeration and Iterator.
  6. HashMap inherits the AbstractMap class on the other hand Hashtable inherits the dictionary class.

Comparison Table of HashMap & HashTable

Java Hashtable with Example 2

Navigableset – NavigableSet in Java with Example | How to Create a Java NavigableSet Interface? | Methods & Example Programs

NavigableSet in Java with Example

Navigableset: The NavigableSet Interface in java is a subinterface of SortedSet which gives additional methods for navigating the elements in the set. From this tutorial of Java NavigableSet, you can easily & quickly learn all Navigable Set Methods with Sample Program. Also, understand how to create and use a NavigableSet in Java using a class that implements it.

This Tutorial of Navigable Set in Java Includes the following:

Java NavigableSet

NavigableSet in Java is an interface present in java.util package. It is part of the collection framework in java. NavigableSet is the child interface of the SortedSet interface. NavigableSet came in Java 1.6 version. It behaves like a SortedSet exception that defines several methods for navigation purposes. It can navigate the set in reverse order compared to the order defined in the SortedSet.

NavigableSet in Java with Example 1

Also See:

Interface NavigableSet<E>

Type Parameters:

E – the type of elements maintained by this set

All Superinterfaces:

Collection<E>, Iterable<E>, Set<E>, SortedSet<E>

All Known Implementing Classes:

ConcurrentSkipListSet, TreeSet

Java NavigableSet Implementations

In Java, the implementation of the NavigableSet interface can be done by the java.util package ie., java.util.TreeSet class. Also, there is an implementation in the java.util.concurrent package called ConcurrentSkipListSet but that is the outer scope of this path.

Create a NavigableSet

In order to create a Java Navigable Set, you have to make an instance of one of the classes implementing the NavigableSet interface. Following is an instance of creating an instance of the class TreeSet which implements the NavigableSet interface:

NavigableSet navigableSet = new TreeSet();

How to use NavigableSet?

For using the NavigableSet, we need to import the java.util.NavigableSet package in java. After importing the package, here’s how we can create navigable sets.

// SortedSet implementation by TreeSet class
NavigableSet<String> numerals = new TreeSet<>();

In the above example, we have created a navigable set named numerals of the TreeSet class.

Methods of NavigableSet in Java

1. floor(E e): This method returns the highest element in this set which is less than or equal to the given element, it returns null if there is no such element.

2. lower(E e): This method returns the highest element in this set which is less than to the given element, it returns null if there is no such element.

3. ceiling(E e): This method returns the least element in this set which is greater than or equal to the given element, it returns null if there is no such element.

4. higher(E e): This method returns the least element in this set which is greater than the given element, it returns null if there is no such element.

5. pollFirst(E e): This method is used to retrieve and remove the first least element, it returns null if there is no such element.

6. pollLast(E e): This method is used to retrieve and remove the last highest element, it returns null if there is no such element.

7. desecendingSet(): This method is used to returns the navigable set in reverse order.

8. descendingIterator() – This method returns an iterator that can be used to iterate over a set in reverse order.

Java NavigableSet Example

import java.util.NavigableSet;
import java.util.TreeSet;
class Person
{
public static void main(String args[])
{
NavigableSet nset = new TreeSet();

nset.add(100);
nset.add(200);
nset.add(300);
nset.add(400);
nset.add(500);
nset.add(600);
nset.add(700);

//displaying normal order
System.out.println("Normal order of navigable set is: " +nset);

//displaying reverse order
System.out.println("Reverse order of navigable set is: " +nset.descendingSet());

System.out.println("Lower(300) is: " +nset.lower(300));
System.out.println("floor(400) is: " +nset.floor(400));
System.out.println("Ceiling(300) is: " +nset.ceiling(300));
System.out.println("Higher(200) is: " +nset.higher(200));
System.out.println("pool first is: " +nset.pollFirst());
System.out.println("pool last is: " +nset.pollLast());
}
}

Output:
The normal order of navigable set is: [100, 200, 300, 400, 500, 600, 700]
The reverse order of navigable set is: [700, 600, 500, 400, 300, 200, 100]
Lower(300) is: 200
floor(400) is: 400
Ceiling(300) is: 300
Higher(200) is: 300
poll first is: 100
poll last is: 700

Shortcuts in intellij – IntelliJ IDEA Keyboard Shortcuts | List of All Shortcut Keys for IntelliJ IDEA

IntelliJ IDEA Keyboard Shortcuts

IntelliJ IDEA Keyboard Shortcuts: IntelliJ IDEA is a unique Java platform that is often used for the purpose of developing various computer software. Developed by the renowned JetBrains, you can use this program across various operating systems, like Windows or Linux. If you are a new programmer, feel free to use this program because the ease of its use is unbeatable.

Do you know that you can also use this program for languages other than Java as well? Yes, you can use IntelliJ IDEA for JPQL, SQL and even HTML. So you must be intrigued to know that there are various keyboard shortcuts that you can use so that your program experience is even smoother. There are lots of keyboard shortcuts for IntelliJ IDEA that are related to its navigation, debugging, editing or refactoring features. If you memorize these hotkeys, it will no doubt save you lots of time and make you more productive!

Wondering How to explore & learn Shortcut Keys for various Operating Systems, Computer Software Programs, Social media applications Keyboards? Here is the one-stop destination for all Keyboard Shortcuts, just take a look & memorize regularly for better performance in competitive exams & real-time situations.

IntelliJ IDEA Keyboard Shortcuts

Choosing The Right Keymap

Shortcuts in intellij: Choosing a proper keymap is quite crucial, and automatically IntelliJ IDEA suggests a keymap that I based on your computer environment. You must make sure before finalizing the keymap that the suggestion from IntelliJ IDEA matches your operating system. If it doesn’t match, then you have to use some other editor or IDE that actually suits your operating system.

You will always be able to modify any previous copy of the predefined keymap. This allows you to assign your own set of shortcuts for all the frequently used commands. The predefined keymaps are given below:

  1. Visual Studio or Visual Studio for macOS: The Visual Studio keymap is a perfect recommendation for you if you are a fresh starter and have no previous experience with any other IDEs. You can also use this keymap if you are accustomed to using the plain version of Visual Studio.
  2. IntelliJ (macOS): IntelliJ macOS is highly recommended for you if you have any earlier experience with the IntelliJ IDEA platform or any other platform of a similar type from JetBrains.
  3. ReSharper (macOS) or Resharper: The ReSharper keymap is a recommendation for you if you are familiar with Visual Studio.

Learning The Shortcuts

Intellij idea shortcuts: Given below are the most commonly used shortcuts in the IntelliJ IDEA platform:

IntelliJ IDEA Keyboard Shortcuts 2

Shortcut Action Explanation
Double Shift Search Everywhere Quickly find a file, or any action, tool window, symbol. It is also applicable to find any setting in
IntelliJ IDEA platform, or in your current project, and also in the current Git repository.
Alt+Enter Show Context Actions It is a quick fix for any highlighted errors or warnings.
It is also a useful fix for any intention action
for the purpose of improving and optimizing any code.
Ctrl+Shift+Enter Complete Current Statement Used for inserting any necessary trailing symbols.
The symbol, after being inserted is put in the caret where you can start typing the next statement.
Ctrl+Shift+A Find Action To find any command and successfully execute it
or to open a tool window
or to search for any particular setting.
F2 Navigate between code issues
Shift+F2 Jump to the next or previously highlighted error.
Ctrl+Alt+L Reformat Code Reformat the entire file or any selected fragment of the file
following the current style settings of the code.
Alt+1 Focus the Project tool window
Escape Focus the editor
Ctrl+W Extend or shrink selection
Ctrl+Shift+W Increase or decrease the scope of selection according to specific code constructs.
Alt+F7 Find Usages It shows all the places where you have used any code element in your project.
Ctrl+/ Add/remove line or block comment It is used to select or reopen a recently opened file, from the folders in the list.
Ctrl+Shift+/ Comment out a line or block of code. It is used to refactor any given element under the caret.
For an example,copy, safe delete, rename, move, and many others.
Ctrl+B Go To Declaration Used to navigate to the initial or first declaration
of the instantiated class, which is called method (also field).
Ctrl+E View recent files
Ctrl+Alt+Shift+T Invoke refactoring

IntelliJ IDEA Keyboard Shortcuts 1

Using The Advanced Features

Apart from the keyboard shortcuts given above, there are certainly other useful features which are for advanced programmers. These are as follows:

  • Refactor: Crl+Alt+Shift+T
  • VCS Operation: Alt+
  • Vertical tool resize: Ctrl+Shift+Left or Ctrl+Shift+Right
  • Horizontal tool resize: Ctrl+Shift+Up or Ctrl+Shift+Down

Comparison Of Keyboard Shortcuts Between Various Keymaps

Shortcuts for general operations:

Command Visual Studio ReSharper IntelliJ
Searching Everywhere Double Shift Double Shift Double Shift
Find Ctrl+Shift+A Ctrl+Shift+A Ctrl+Shift+A
Refactor Ctrl+Shift+R Ctrl+Shift+R Ctrl+Alt+Shift+T
Open File or Folder Ctrl+O Ctrl+O N/A
Show Intention Actions Alt+Enter Alt+Enter Alt+Enter
Settings Ctrl+Alt+S Ctrl+Alt+S Ctrl+Alt+S
Recent Files Ctrl+Comma Ctrl+E Ctrl+E
Code Cleanup Ctrl+E, C Ctrl+Alt+F N/A
Select Alt+F1 Alt+F1 Alt+F1
View Breakpoints Ctrl+Alt+B Ctrl+Shift+F8 Ctrl+Shift+F8
Generate Alt+Insert Alt+Insert Alt+Insert
Build A Solution Ctrl+Shift+B Ctrl+Shift+B Ctrl+F9
Debug Alt+Shift+F9 Alt+Shift+F9 Alt+Shift+F9
Open a Solution or previous Project Ctrl+Shift+O Ctrl+Shift+O Ctrl+Shift+O
Attach Process Ctrl+Alt+P Ctrl+Alt+F5 Ctrl+Alt+F5
Reformat Code Ctrl+Alt+Enter Ctrl+Alt+L Ctrl+Alt+L
Inspect Ctrl+Alt+Shift+A Ctrl+Alt+Shift+A Ctrl+Alt+Shift+A
Find Usages Shift+F12 Alt+F7 Alt+F7
Navigate Alt+` Ctrl+Shift+G Ctrl+Shift+G
VCS Operations Popup Ctrl+Alt+Q Alt+` Alt+`

Comparison Of Keyboard Shortcuts Between Various Keymaps

Shortcuts for Basic Editing

Command Visual Studio ReSharper IntelliJ
Cut Ctrl+X Ctrl+X Ctrl+X
Copy Ctrl+C Ctrl+C Ctrl+C
Paste Ctrl+V Ctrl+V Ctrl+V
Paste as Plain Text Ctrl+Alt+Shift+V Ctrl+Alt+Shift+V Ctrl+Alt+Shift+V
Paste from History… Ctrl+Shift+V Ctrl+Shift+V Ctrl+Shift+V
Duplicate Line or Selection Ctrl+D Ctrl+D Ctrl+D
Open source in new window Shift+F4 Shift+F4 Shift+F4
Copy Paths Ctrl+Shift+C Ctrl+Shift+C Ctrl+Shift+C
Copy Reference Ctrl+Alt+Shift+C Ctrl+Alt+Shift+C Ctrl+Alt+Shift+C
Save All Ctrl+Shift+S Ctrl+Shift+S Ctrl+S
Delete Line Ctrl+Shift+L Ctrl+Shift+L Ctrl+Y
Scratch File Ctrl+Alt+Shift+Insert Ctrl+Alt+Shift+Insert Ctrl+Alt+Shift+Insert
Indent Selection Tab Tab Tab
Unindent Line or Selection Shift+Tab Shift+Tab Shift+Tab
Start New Line Shift+Enter Shift+Enter Shift+Enter
Start New Line Before Current Ctrl+Enter Ctrl+Enter Ctrl+Alt+Enter
Toggle Case Ctrl+Shift+U Ctrl+Shift+U Ctrl+Shift+U
Undo Ctrl+Z Ctrl+Z Ctrl+Z
Redo Ctrl+Y Ctrl+Y Ctrl+Shift+Z

Shortcuts for Navigating the Content

Command Visual Studio ReSharper IntelliJ
Previous Method Alt+Up Alt+Up Alt+Up
Next Method Alt+Down Alt+Down Alt+Down
Go to Line/Column… Ctrl+G Ctrl+G Ctrl+G
Switcher Ctrl+Tab Ctrl+Tab Ctrl+Tab
Select In… Alt+F1 Alt+F1 Alt+F1
Locate/Select in Solution View Alt+Shift+L Alt+Shift+L N/A
Show Bookmarks Ctrl+` Ctrl+` Shift+F11
Forward Ctrl+Shift+Minus Ctrl+Shift+Minus Ctrl+Alt+Right
Last Edit Location Ctrl+Shift+Backspace Ctrl+Shift+Backspace Ctrl+Shift+Backspace
Back Ctrl+Minus Ctrl+Minus Ctrl+Alt+Left
Select Next Tab Alt+Right Alt+Right Alt+Right
Select Previous Tab Alt+Left Alt+Left Alt+Left
Add to Favorites Alt+Shift+F Alt+Shift+F Alt+Shift+F
Toggle Bookmark with Mnemonic Ctrl+F11 N/A Ctrl+F11
Toggle Bookmark Ctrl+K, K N/A F11
Recent Files Ctrl+Comma Ctrl+E Ctrl+E
Recently Changed Files Ctrl+Shift+Comma Ctrl+Alt+Shift+Backspace N/A
Show Favorites window Alt+2 Alt+2 Alt+2
Show Structure window Ctrl+Alt+F Ctrl+F11 Alt+7
Show Find window Alt+3 Alt+3 Alt+3

Shortcuts for Navigating the Content

Shortcuts for Caret Options

Command Visual Studio ReSharper IntelliJ
Move Caret to Previous Word Ctrl+Left Ctrl+Left Ctrl+Left
Move Caret to Next Word Ctrl+Right Ctrl+Right Ctrl+Right
Move Caret to Line Start Home Home Home
Move Caret to Line End End End End
Containing Declaration Ctrl+[ Ctrl+[ Alt+Shift+[
Next Method Alt+Down Alt+Down Alt+Down
Previous Method Alt+Up Alt+Up Alt+Up
Move Caret to Page Top Ctrl+Page Up Ctrl+Page Up Ctrl+Page Up
Move Caret to Page Bottom Ctrl+Page Down Ctrl+Page Down Ctrl+Page Down
Move Caret to Text Start Ctrl+Home Ctrl+Home Ctrl+Home
Move Caret to Text End Ctrl+End Ctrl+End Ctrl+End
Extend Selection Ctrl+Alt+Right Ctrl+W Ctrl+W
Clone Caret Above Double Ctrl + Up Double Ctrl + Up Double Ctrl + Up
Clone Caret Below Double Ctrl + Down Double Ctrl + Down Double Ctrl + Down
Clone Caret Above with Virtual Space Alt+Shift+Up Alt+Shift+Up N/A
Clone Caret Below with Virtual Space Alt+Shift+Down Alt+Shift+Down N/A
Move Caret to Matching Brace Ctrl+] Ctrl+] Ctrl+Shift+M
Move Caret to Code Block Start Alt+Shift+[ Alt+Shift+[ Ctrl+[
Move Caret to Code Block End Alt+Shift+] Alt+Shift+] Ctrl+]
Move Caret to Previous Word with Selection Ctrl+Shift+Left Ctrl+Shift+Left Ctrl+Shift+Left
Move Caret to Next Word with Selection Ctrl+Shift+Right Ctrl+Shift+Right Ctrl+Shift+Right
Move Caret to Line Start with Selection Shift+Home Shift+Home Shift+Home
Move Caret to Line End with Selection Shift+End Shift+End Shift+End
Up with Selection Shift+Up Shift+Up Shift+Up
Down with Selection Shift+Down Shift+Down Shift+Down
Select Containing Declaration Ctrl+Shift+[ Ctrl+Shift+[ Ctrl+Alt+Shift+[
Move Caret to Code Block Start with Selection Ctrl+Alt+Shift+[ Ctrl+Alt+Shift+[ Ctrl+Shift+[
Move Caret to Code Block End with Selection Ctrl+Alt+Shift+] Ctrl+Alt+Shift+] Ctrl+Shift+]
Move Caret to Page Top with Selection Ctrl+Shift+Page Up Ctrl+Shift+Page Up Ctrl+Shift+Page Up
Move Caret to Page Bottom with Selection Ctrl+Shift+Page Down Ctrl+Shift+Page Down Ctrl+Shift+Page Down
Page Up with Selection Shift+Page Up Shift+Page Up Shift+Page Up
Page Down with Selection Shift+Page Down Shift+Page Down Shift+Page Down
Move Caret to Text Start with Selection Ctrl+Shift+Home Ctrl+Shift+Home Ctrl+Shift+Home
Move Caret to Text End with Selection Ctrl+Shift+End Ctrl+Shift+End Ctrl+Shift+End
Shrink Selection Ctrl+Alt+Left Ctrl+Shift+W Ctrl+Shift+W
Page Up Page Up Page Up Page Up
Page Down Page Down Page Down Page Down
Select All Ctrl+A Ctrl+A Ctrl+A
Left with Selection Shift+Left Shift+Left Shift+Left
Right with Selection Shift+Right Shift+Right Shift+Right
Add/Remove Caret Alt+Shift+Click Alt+Shift+Click Alt+Shift+Click
Toggle Column Selection Mode Alt+Shift+Insert Alt+Shift+Insert Alt+Shift+Insert
Add Caret to Each Line in Selection Alt+Shift+G Alt+Shift+G Alt+Shift+G
Add Selection for Next Occurrence Alt+Shift+. Alt+Shift+. Alt+J

Conclusion on IntelliJ IDEA Keyboard Shortcuts

These shortcuts are highly beneficial to learn, as you can see. It hardly takes five to ten minutes to memorize them, yet stays for a lifetime. It will no doubt save you lengths of time and make you tech-savvy. We hope we have been of help to you!

Java string to char array – How to Convert a String to char array in Java? | Java String toCharArray() Method with Example

How to Convert a String to char array in Java

Java string to char array: In our previous java string tutorials, we have learned how to convert a string to lowercase & Uppercase in java. But today, in this tutorial, we will learn how to convert a string to a char array in Java. To make it possible, we will use the Java String toCharArray() method. So, check the process and signature of the toCharArray() method of the java string class with an example from the below links.

This Tutorial of How to Convert a String to char array in Java includes the following:

Convert a String to Character array in Java

Java string to chararray: We can convert a string to a char array by using the two ways. The following are the two approaches to convert a string to a character array in java:

  • using Java String toCharArray()
  • Naive Approach

Method 1: Java String toCharArray()

Java convert string to char: The java stringtoCharArray()method converts this string into a character array. It returns a newly allocated character array whose length is the length of this string.

Syntax

Tochararray in java: The syntax of the Java String toCharArray() method is given below:

public char[] toCharArray()

It converts this string to a new character array.

Also Check:

Java program to convert a string to char array – Example

class toCharArray{
public static void main(String args[]){
String str = "Java";

//converting string to char array.
char ch[] = str.toCharArray();

//printing the char array.
for(int i=0; i<ch.length; i++){
System.out.println(ch[i]);
}
}
}

Output:

How to Convert a String to char array in Java

Method 2: Naive Approach

Java char array: The following steps are the best way to do the process of converting a string to char array in java using a naive approach:

  1. Get the string.
  2. Create a character array of the same length as of string.
  3. Traverse over the string to copy character at the i’th index of string to i’th index in the array.
  4. Return or perform the operation on the character array.

Let’s see the below-illustrated example to convert a string to a character array in java,

Example on Using Naive Approach to convert string to char array in java

// Java program to Convert a String
// to a Character array using Naive Approach

import java.util.*;

public class BG {

public static void main(String args[])
{
String str = "BtechGeeks";

// Creating array of string length
char[] ch = new char[str.length()];

// Copy character by character into array
for (int i = 0; i < str.length(); i++) {
ch[i] = str.charAt(i);
}

// Printing content of array
for (char c : ch) {
System.out.println(c);
}
}
}

Output: 

B
t
e
c
h
G
e
e
k
s

Entity framework interview questions – LINQ and Entity Framework Interview Questions in .NET

Entity framework interview questions: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on LINQ and Entity Framework

Question 1.
Define LINQ.
Answer:
LINQ (Language Integrated Query Microsoft) is a uniform programming model for any kind of data access. It is also an OR-mapper that helps us to expedite our business object creation process.

LINQ enables you to query and manipulate data independently of data sources. Figure 13.1 shows how the .NET language stands over the LINQ programming model and works in a uniform manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 1

LINQ can serve as a good entity for the middle tier. So it will sit in between the Ul and data access layer.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 2

Figure 13.2 shows a simple sample of LINQ. We have a collection of data ‘ objcountries’ to which LINQ will is making a query with country name can be any data source dataset, datareader,
XML, etc. Figure 13.2 shows how the ‘ Ob j Countries’ can be any can .of data. We then query for the ‘CountryCode’ and loop through the same.

Question 2.
How does LINQ help us from the perspective of business objects?
Answer:
One of the tedious jobs in business objects is parsing and searching object collections. For instance, consider Figure 13.3 where we want to search a country by an ‘ID’ value. Each loop is used through the collection and gets the object. Many may argue how about keeping a key in List or Array. The below example is just a sample. For instance, if you want to search using country code and name, list / collection keys will not work with those multi-value searches.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 3

In other words, using LINQ, we can query business object collections and filter the collection in a single LINQ query.

Question 3.
Can you explain how a basic LINQ Query looks like?
Answer:
Below is a simple LINQ query that selects all customer data from the ‘ Obj Customer’ collection.

from clsCustomer obj in objCustomer select obj

Question 4.
How do we write a LINQ query to search with criteria?
Answer:
We need to put the where clause before the ‘ select’ keyword.

return from clsCustomer Obj in objCustomer where Obj.customerCode == “001 "select Obj;

Question 5.
How can do join using the LINQ query?
Answer:
Below is the LINQ code snippet for creating joins between object collections. In this case, we are creating a join on customers and orders. If you remember the order collection was contained in the customer class.

return from clsCustomer ObjCust in objCustomer
from clsOrder ObjOrder in ObjCust.Orders
select ObjCust;

Question 6.
How can we do a group by using LINQ query?
Answer:
Below is the code snippet which shows how group by query is written using LINQ. You can see we have created first a temp variable, i.e., ‘GroupTemp’ and then we have used the ‘Select’ clause to return the same.

var GroupCustomers = from ObjCust in objCustomer
                       group ObjCust by ObjCust.City into GroupTemp
select new (GroupTemp.Key, GroupTemp);

Question 7.
What are entity classes in LINQ?
Answer:
Entity Glasses are classes that map to the table structure of your data source. Entity classes represent your business model. The class name of entity class map to table name using the ‘Table’ attribute while table column name map to properties of the class.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 4

Question 8.
How can we load the LINQ entity class?
Answer:
The LINQ entity classes are loaded by using DataContext class as shown in Figure 13.5.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 19

Question 9.
How do we define 1-to-many and many-to-1 relationships in LINQ?
Answer:
1-to-many relationships are defined by using EntitySet and many-to-1 is defined by using entity ref. Below is a sample code snippet that shows ‘ clsCustomer’ having many ‘CLS addresses
object.

[Table(Name = "Customer")]
public class clsCustomer
{
       private EntitySet<clsAddresses> _CustomerAddresses;
       [Association(Storage = "_CustomerAddresses", ThisKey="CustomerId", 
       OtherKey = "Customerld")]
       public EntitySet<clsAddresses> Addresses
       {
             set
             {
                 _CustomerAddresses = value;
             }
             get
             {
                 return _CustomerAddresses;
            }
     }
}

If we need to define a one-to-one relationship we need to use the EntityRef attribute as shown in the below code snippet.

public class clsAddresses
{
       . . . .
       . . . .
       private EntityRef<clsPhone> _Phone;
       . . . .
       . . . .
}

Question 10.
How can we call a stored procedure using LINQ?
Answer:
We can use the function attribute as shown in the below code snippet with the stored procedure name.

[Function(Name = "usp_SelectCustomer", IsComposable = false)]
public ISingleResult<clsCustomerEntity> getCustomerAll()
{
IExecuteResult objResult = this.ExecuteMethodCall(this,
(Methodlnfo)(Methodlnfo.GetCurrentMethod()));

Question 11.
How can we insert, update and delete using LINQ?
Answer:
Insert, update and delete operations in LINQ are done by using ‘ insertOnSubm.it’ , ‘DeleteOnSubmit’ and ‘SubmitChanges’.
To add a new record using LINQ below is the code snippet.

DataContext objContext = new DataContext(strConnectionString);
clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.GetTable<clsCustomerEntity>( ).InsertOnSubmit(objCustomerData);
obj Context.SubmitChanges( ) ;

Below is the code for updating a record by LINQ.

clsCustomerEntity objCustomerData =
(clsCustomerEntity)MyQuery.First<clsCustomerEntity>( );
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerMame = txtCustomerName.Text;
objContext.SubmitChanges( );

Below is the code for deleting records using LINQ,

objContext.GetTable<clsCustomerEntity>( ).DeleteOnSubmit(objCustomerData);
objContext. SubmitChanges( );

Question 12.
What are DBML files in LINQ?
Answer:
DBML stands for Database Markup Language which is a XML file, in big projects we will have large number of tables, developing entity classes for those
tables will be very difficult. DBML files help to automate the creation of entity classes by simple drag-and-drop as shown in Figure 13.6.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 5

Question 13.
What is an Entity framework?
Answer:
ADO.NET entity is a QRM (Object Relational Mapping) that creates a higher abstract object model overADO.NET components.
So rather than getting in to dataset, datatabies, command and connection objects as shown in the below code, you work on higher-level domain objects like customers, suppliers, etc.

DataTable table = adoDs.Tables [0];
for (int j = 0; j < table.Rows.Count; j++)
{
      DataRow row = table.Rows[j];
      // Get the values of the fields
      string CustomerName =
     (string)row["Customername"];
      string CustomerCode =
      (string)row["CustomerCode"];
}

Below is the code of entity framework in which we are working on the higher-level domain objects like a customer rather than working with base-level ADO.NET components (like dataset, DataReader, command, connection objects, etc).

foreach (Customer objCust in obj. Customers)
{ }

Question 14.
So what are the benefits of using EF?
Answer:
The main and the only benefit of EF (Entity Framework) it auto-generates code for Model (Middle layer), Data access layer, and mapping code thus reducing a lot of development time.

Question 15.
So what are the different ways of creating these domain/entity objects?
Answer:
Entity objects can be created in two ways from a database structure or by starting from scratch by creating a model (See Figure 13.7).

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 6

Question 16.
What is pluralize and singularize in the Entity framework dialog box?
Answer:
“Pluralize” and “Singuiarize” give meaningful naming conventions to the objects. In simple words it says do you want to represent your objects with the below-naming convention:

  • What does one Customer record mean? “Customer”(singular).
  • A lot of customer records means “Customer’s” ( plural, watch the “S”)

If you select the below check box entity framework generates a naming convention that adheres to plural and singular coding convention.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 7

Question 17.
What is the importance of the EDMX file in entity framework?
Answer:

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 8

EDMX (Entity Data Model XML) is an XML file that contains ail mapping details of how your objects map with SQL table (See Figure 13.9). The EDMX file is further divided into three sections CSDL (Conceptual Schema Definition Language), SSDL (Software Schema Definition Language), and MSL (Mapping Schema Language).

Question 18.
Can you explain CSDL, SSDL and MSL sections in EDMX file?
Answer:
CSDL (Conceptual Schema Definition Language) is the conceptual abstraction which is exposed to the application.
SSDL (Storage Schema Definition Language) defines the mapping with your RDBMS (Relational Database Management System) data structure. MSL (Mapping Schema Language) connects the CSDL and SSDL.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 9

Question 19.
What are T4 templates?
Answer:
T4 (Text Template Transformation Toolkit) is a template-based code generation engine as shown in Figure 13,11. So you can go and write C# code in T4 templates (, tt is the extension) files, and those C# codes are executed to generate the file as written according to C# logic.
For instance the below T4 C# code:

<#@ template language=” C#” #>
Hello <# Write(“Worldl”) #>

Will generate the following C# output:

Hello
World !

Question 20.
So what is the importance of T4 in the Entity framework?
Answer:
T4 files are heart in EF code generation. So the T4 code templates read the EDMX XML file and generate C# behind code. This C# behind code is nothing but your entity and context classes.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 10

If you create a project using Visual Studio 2012, you will see the hierarchy as shown in Figure 13.12 At the top we have the EDMX (Entity Data Model XML) file, followed by the TT or T4 file and then the .cs code file.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 11

Question 21.
How can we read records using entity framework classes?
Answer:
In order to browse through records you can create the object of the context class and inside the context class, you will get the records.
For instance in the below code snippet we are looping through list of Customer object collection. This customer collection is an output given by the context class
“CustomermytextEntities”.

CustomermytestEntities obj = new
CustomermytestEntiti.es () ;
foreach (Customer objCust in obj.Customers)
{ }

Question 22.
How can we add, update and delete using EF?
Answer:
Create the object of your entity class, add it to the data context using add object method and then call save changes method.

CustomermytestEntities obj = new CustomermytestEntities( ) ;
Customer objCust = new Customer( );
objCust.CustomerCode = "1001";
obj.Customers.AddObject(objCust);
obj.SaveChanges( );

If you want to update, select the object, make change to the object and call accept changes.

CustomermytestEntities objContext = new CustomermytestEntities( );
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault( );
objCustomer.CountryCode = "NEP";
objContext.AcceptAllChanges( );

If you want to delete call the delete object method as shown in the below code snippet.

CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefau.lt( );
objContext.DeleteObj ect(objCustomer);

Question 23.
People say the entity framework runs slow.
Answer:
By default Entity framework has lazy loading behavior. Due to this default behavior, if you are loading a large number of records, and especially if they have foreign key relationships, you can have performance issues.
So you need to be cautious if you really need lazy loading behavior for all scenarios.
So for better performance disable lazy loading when you are loading a large number of records or use stored procedures.

Question 24.
Can you explain lazy loading in a detailed manner?
Answer:
Lazy Loading is a concept where we load objects on demand rather than loading everything in one go.Consider a situation where you have 1 to many relationships between “Customer” and “Address” object. Now let’s say you are browsing the customer data but you do not want address data to be loaded that moment. But the time you start accessing the address object you would like to load address data from the database.

The entity framework has the lazy loading behavior by default enabled. For instance, consider the below code. When we are doing “foreach” on the customer object address object is not loaded. But the time you start doing “for each” on the address collection address object is loaded from SQL (Structured Query Language) Server by firing SQL queries.

So in simple words, if will fire a separate queries for each address record of the customer which is definitely not good for a large number of records.

MyEntities context = new MyEntities();
var Customers = context.Customers.ToList();
foreach (Customercust in Customers) // In this line no address object loaded
{
     foreach(Address add in cust.Addresses){}// Address object is loaded here
}

Question 25.
How can we turn off lazy loading?
Answer:
The opposite of lazy loading is eager loading. In eager loading we load the objects beforehand. So the first thing is we need to disable lazy loading by setting “LazyLoadingEnabled” to false.

context. ContextOptions.LazyLoadingEnabled = false;

So now we have to explicitly tell EF what objects we want to load by using the “include” function. Below is a simple sample code where we tell EF to load customer as well as address objects by using the “include” function.
So now the customer object and the related address objects will be loaded in one query rather than multiple queries.

var employees = context. Customers.Include(“Addresses”). Take(5);

Question 26.
How can we use stored procedures in entity framework?
Answer:
You can use the stored procedure mapping details in EDMX as shown in the Figure 13.13.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 12

Question 27.
What are POCO classes in Entity framework?
Answer:
POCO means Plain Old C# Object. When EDMX creates classes they are cluttered with a lot of entity tags. For instance below is a simple customer class generated using an entity framework. Many times we would like to use simple .NET classes and integrate the same with entity framework.
The entity framework allows the same. In other words you can create a simple .NET class and use the entity context object to load your simple .NET classes.

Below is a simple class generated by EF which is cluttered with lot of EF attributes.

[EdmEntityTypeAttribute
(NamespaceN ame ="CustomermytestModel",
Name="Customer")]
[ Serializable( )]
[DataContractAttribute(IsReference=true)]
public partial class Customer:
EntityObject
{
      #region Factory Method
      /// <summary>
      /// Create a new Customer object.
     /// </suinmary>
    /// <param name="id">Initial value of the Id property.</param>
   /// <param name="customerCode">Initial value of the CustomerCode
  property.</param>
  /// <param name="customername">Initial value of the Customername
  property.</param>
  public static Customer CreateCustomer(global: : System.Int32 id,
  global: : System.String customerCode, global: : System.String
  customername)
  {
         Customer customer = new Customer( );
         customer.Id = id;
         customer.CustomerCode = customerCode;
         customer.Customername = customername;
         return customer;
}
#endregion
#region Primitive Properties

Question 28.
How to implement POCO in entity framework?
Answer:
To implement POCO is a three-step process:

  • Go to the designer and make the code generation strategy to None. This step means that you would be generating the classes with your own hands rather than relying on EF auto code generation.
  • So now that we have stopped the auto generation of code, we need to create the domain classes manually. So add a class file and create the domain classes like the one “Customer” class we have created.
public class Customer
{
      private string _customerName;
      public string CustomerName;
      {
            get { return _customerName; }
            set { _customerName = value; }
      }
      private int _Customerid;
      public int Customerid
      {
           get { return _Customerid; }
           set { _Customerid = value; }
      }
}

Write your Context layer code inheriting from the “ObjectContext”. I his code you can copy paste from the behind code of EF also before disabling auto-generation.

public partial class Testl23Entities: ObjectContext
{
       public Testl23Entities( )
       : base("name=Testl23Entities", "Testl23Entities")
       {
             this.ContextOptions.LazyLoadingEnabled = true;
             OnContextCreated();
       }
       partial void OnContextCreated( ) ;
       public ObjectSet<Customer> Customers
       {
             get
             {
                   if ( (_Customers == null) )
                   {
                         _Customers =
                         base.CreateObj ectSet<Customer>("Customers");
                   }
                   return Customers;
             }
      }
      private ObjectSet<Customer> _Customers;
      public void AddToCustomers(Customer customer)
      {
              base.AddObject("Customers", customer);
      }
}

And finally, you can use the above code in your client as you were using your EF normally.

Test123Entities oContext = new Test123Entities( );
List<Customer> oCustomers = oContext. Customers. ToList<Customer>( );

Question 29.
in POCO classes do we will need EDMX flies?
Answer:
Yes, you will still need EDMX files because the context object reads the EDMX files to do the mapping.

Question 30.
What is the code first approach in entity framework?
Answer:
In the code first approach, we avoid working with the visual designer of entity framework. In other words, the EDMX file is excluded from the solution. So you now have complete control over the context class as well as the entity classes.

Question 31.
What is the difference between POCO, code first, and simple EF approach?
Answer:
All these three approaches define how much control you want on your Entity framework code. The entity framework is an OR-Mapper it generates lot of code, it creates your middle-tier (Entity) and Data access layer (Context).
But a lot of times you want to enjoy the benefits of both the world you want the auto-generation part to minimize your development time and also you want to control the code so that you can maintain code quality.

Below Is the difference table which defines each of the approaches. In the Simple entity framework, everything is auto generated and so you need the EDMX XML file as well. POCO is semi-automatic so you have full control over the entity classes but then the context classes are still generated by the EDMX file.
In code first you have complete control on how you can create the entity and the context classes. Because you are going to manually create these classes you do not have a dependency on the EDMX XML file, below is a simple table which shows the cross comparison.

EDMX Entity Context
Simple entity framework Needed Auto Auto
POCO approach Needed Manual Auto
Code First Not Needed Manual Manual

Question 32.
How can we handle concurrency in Entity framework?
Answer:

Note: Before this question interviewer can ask you about What is concurrency and What is pessimistic 
and optimistic locking. Please do refer ADO.NET Chapter for the same.

In EF concurrency issue is resolved by using optimistic locking. PleasereferADO.NET Chapter for What is optimistic locking and pessimistic locking?. To implement optimistic locking right click on the EDMX designer and set the concurrency mode to “Fixed” as shown in the Figure 13.14.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 13

Now whenever we have concurrency issues you should get an “OptimisticConcurrency Exception” error as shown in Figure 13.15. You can then put a try / catch to handle this situation.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 14

Question 33.
How can we do pessimistic locking in the Entity framework?
Answer:
We cannot do pessimistic locking using the entity framework. You can invoke a stored procedure from entity framework and do pessimistic locking by setting isolation level in the stored procedure. But direct entity framework does not support pessimistic locking.

Question 34.
What are ciientwins and store wins mode in entity framework concurrency?
Answer:
Clientwins and store wins are actions which you would like to take when concurrency happens. In store wins / database wins the data from the server is loaded into your entity objects. Client wins is opposite to storedwins, data from the entity object is saved to the database.
We need to use the “Refresh” method of the entity framework context and provide the “RefreshMode” enum values. Below is a simple code snippet that executes “Clientwins”.

Context. Refresh (System. Data. Objects. RefreshMode. Clientwins, Obj);

Question 35.
What are scalar and navigation properties in the Entity framework?
Answer:

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 15

Scalar is properties whose actual values are contained in the entities. For example, in the above customer entity “Customer name” and “Customer id” are scalar properties. Normally a scalar property will map to a database field.

Navigation Properties heip to navigate from one entity to the other entity. For instance consider the below example in which we have two entities customer and address and one customer has multiple address objects.

Now we would like to have a facility where at any given moment we would like to browse from a given customer object to the addresses collection and from address object to the customer.

If you open the entity designer you would notice “Navigation” Properties as shown in Figure 13.16. The navigation properties are automatically created from the primary and foreign key references.
So now because of those navigation properties we can browse from Customer to Addresses object, look at the below code.

Customer Cust = oContext.Customers.ToList<Customer>()[0];
// From customer are browsing addresses
List<Address> Addresses = Cust.Addresses.ToList<Address>( );

You can also go vice-versa. In other words from the Address object you can reference the Customer object as shown in the below code.

Address myAddress = Addresses[0];
// From address we can browse customer
Customer cus = myAddress.Customer;

Question 36.
What are complex types In the Entity framework?
Answer:
There can be situations where you have common properties across entities. For example, consider Figure 13.17 where we have “Customer” and “Supplier” entities. They have three fields in common “Address 1”, “Address2” and “Phoneno”. These fields have been duplicated both in “Customer” as well as “Supplier” entities.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 16

So to remove these duplicate and redundant fields we can move them, to a common complex type called “Address”. So complex. types group common fields so that they can be reused across entities.

So to create a complex type, select the fields which you want to group in a complex type. Below is Figure 13.18 which shows the same. Once the complex type is created you can then reuse the complex type with other entities as well.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 17

Question 37.
What is the difference between “DbContext” and “ObjectContext”?
Answer:
“DbContext” is a wrapper around “ObjectContext”, it is a simplified version of “ObjectContext” (See Figure 13.19).

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 18

So as a developer you can start with “DbContext” as It is simple to use. When you feel that some of the operation cannot be achieved by “DbContext” you can then access “ObjectContext” from “DbContext” object as shown in the below code:

((|ObjectcontextAdapter)dbContext).ObjectContext

Note: If the interviewer is asking what kind of operations are not supported in “DbContext”, you can excuse by saying do not remember upfront. Wonder why sometimes the interviewer asks API (Application Programming Interface) level questions?

Question 38.
What’s the difference between LINQ to SQL and Entity framework?
Answer:

  • LINQ to SQL is good for rapid development with SQL Server. EF is for enterprise scenarios and works with SQL servers as well as other databases.
  • LINQ maps directly to tables. One LINQ entity class maps to one table. EF has a conceptual model and that conceptual model maps to the storage model via mappings. So one EF class can map to multiple tables or one table can map to multiple classes.
  • LINQ is more targeted towards rapid development while EF is for the enterprise level where the need is to develop the loosely coupled framework.