Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.
Saturday, September 30, 2023
How to find length/size of ArrayList in Java? Example
How to remove all elements of ArrayList in Java - RemoveAll Example
How to loop over a TreeSet in Java with Example
How to Convert Vector to Array in Java? 2 Examples
How to sort a LinkedList in Java? Example Tutorial
Friday, September 29, 2023
10 Example of List in Java
Hello guys, Java, as a versatile and widely used programming language, offers a plethora of data structures to developers. One of them is List which is also fundamental component in Java's collection framework, play a pivotal role in managing and manipulating sequences of elements. In the past, I have shared 10 Examples of HashMap in Java and In this article, we'll delve into Java lists, exploring their features and providing ten illustrative examples to deepen your understanding. List are also a popular topic from Java interviews with questions like difference between ArrayList and LinkedList which have been asked to me almost 10 times in past 20 years.
How to Convert a List to a Set in Java with Example
Difference between ArrayList and HashMap in Java
One of the most critical differences between the HashMap and ArrayList class is that the former is the implementation of the hash table while the latter is a dynamic array that can resize itself. The HashMap and ArrayList are two of the most popular classes from the Java Collection framework. Though both are used to store objects they are completely different in their implementation, working, and usage. The main difference between ArrayList and HashMap is that ArrayList is an index-based data structure backed by an array while HashMap is a map data structure that works on hashing to retrieve stored values.
Thursday, September 28, 2023
How to sort HashSet in Java? Example
How to declare ArrayList with values in Java? Examples
int[] primes = {2, 3, 5, 7, 11, 13, 17};
or
String[] names = {"john", "Johnny", "Tom", "Harry"};
but unfortunately, ArrayList doesn't support such kind of declaration in Java. But don't worry, there is a workaround to declare an ArrayList with values e.g. String, integers, floats, or doubles by using the Arrays.asList() method, which is nothing but a shortcut to convert an Array to ArrayList.
How to add element at first and last position of linked list in Java? Example Tutorial
Difference between Class and Record in Java?
Hello guys, when it comes to defining data structures in Java, two primary options are at your disposal: records and classes. Each has its unique characteristics and use cases, and understanding the differences between them is crucial for making the right design choices in your Java applications. This has now also become a popular Java interview question and asked to one of my reader recently as well. Java classes have been the cornerstone of object-oriented programming for years, offering full customization and flexibility. They allow you to define complex objects with custom behavior, encapsulation, and fine-grained control over state changes.
Difference between HashMap and LinkedHashMap in Java
HashMap and LinkedHashMap are two of the most commonly used Map implementation in Java. The main difference between HashMap and LinkedHashMap is that LinkedHashMap maintains the insertion order of keys, the order in which keys are inserted into LinkedHashMap. On the other hand, HashMap doesn't maintain any order or keys, or values. In terms of performance, there is not much difference between HashMap and LinkedHashMap but yes LinkedHashMap has more memory footprint than HashMap to maintain doubly LinkedList which it uses to keep track of the insertion order of keys.
Difference between TreeMap and TreeSet in Java? Answer
The main difference between TreeMap and TreeSet is that TreeMap is an implementation of Map interface while TreeSet is an implementation of the Set interface. There are some similarities between both TreeMap and TreeSet and few differences as well. In this Java tutorial, we will first see similarities between TreeMap and TreeSet, and then you will learn some differences between TreeMap and TreeSet in Java.
Difference between FileReader vs FileInputStream in Java? Answer
How to Create Read Only and Unmodifiable ArrayList in Java? Example
Difference between HashSet and TreeSet in Java
Wednesday, September 27, 2023
How to handle click event in jQuery - Example
In the world of web development, interactivity is key to creating engaging user experiences. One fundamental aspect of interactivity is the ability to respond to user actions, such as clicks. jQuery, a fast and concise JavaScript library, has long been a favorite among developers for simplifying common tasks, including event handling. You can handle click event in jQuery by using event handlers. You can bind event handlers to any element by using on() method or click() method. The event handler is nothing but a function containing some code which will be executed when user will click on the element. For example, if user clicks on a button then color of button might changed to show on and off behavior. All this can be implemented by handling click event in jQuery.
Top 5 Java Main method Interview Questions with Answers
- Can we overload the main method in Java? Which main method JVM will call?
- Can we override the main method in Java?
- Can we make the main final in Java?
- Can we make the main synchronized in Java?
- How to call a non static method from main in Java?
Difference between NoClassDefFoundError vs ClassNotFoundExcepiton in Java
Difference between Public, Package, Private and Protected in Java?
Difference between HashSet vs TreeSet in Java? [Answer]
What is fail safe and fail fast Iterator in Java?
Tuesday, September 26, 2023
Difference between ROW_NUMBER(), RANK() and DENSE_RANK() in SQL
Difference between Method and Constructor in Java and OOP? Example
What is static in Java? Example Tutorial
Static in Java is related to class if a field is static means it belongs to the class, similarly static method belongs to classes and you can access both static method and field using the class name, for example, if count field is static in Counter class than you can access it as Counter.count, of course, subject to restriction applied by access modifier like private fields are only accessible in class on which they are declared, protected fields are accessible to all classes in the same package but only accessible in subclass outside the package, you can further see private vs protected vs public for complete details on access modifier.
Can you make an Abstract Class or Method Final in Java? Example
What is Variable and Method Hiding in Java - Example Tutorial
Difference between Abstract class and Interface in Java 8? Answer
Monday, September 25, 2023
How to Fix java.lang.OutOfMemoryError: Metaspace in Java? [Solution]
Hello guys, An OutOfMemoryError related to Metaspace indicates that your Java application has exhausted the memory allocated for the Metaspace area, which is used for class metadata and method information. This error typically occurs when an application dynamically generates and loads a large number of classes or when the Metaspace size is not properly configured to handle the application's requirements. Java class metadata (the virtual machine's internal presentation of Java class) is allocated in native memory (referred to here as metaspace). If metaspace for class metadata is exhausted, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown.
Java Interface Example Tutorial
How Constructor Chaining works in Java - Example
5 Rules of Method Overloading and Overriding in Java? Examples
Difference between Method Overloading and Overriding in Java? Answer
In the last couple of articles, we have seen What is method overloading and What is method overriding in Java and now we will see What is difference between overloading and overriding in Java. Overloading vs overriding is one of those frequently asked Java interview questions which can not be ignored. Overloading vs Overriding has appeared in almost every Java interview, mostly at beginner and intermediate level like 2 to 4 years experience. In fact, most of those tricky Java interview Questions came from Overloading and Overriding.
Can You Override Private Method in Java ? Example
Sunday, September 24, 2023
How to fix java module error "Caused by: java.lang.reflect.InaccessibleObjectException: module java.base does not "opens java.util" to unnamed module"
The error message you're seeing, (Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.util.Comparator java.util.TreeMap.comparator accessible: module java.base does not "opens java.util" to unnamed module @6d4a82") or java.lang.reflect.InaccessibleObjectException, is related to module system changes introduced in Java 9 and later versions. It occurs when you try to access a field, method, or class that is not accessible due to module restrictions. In this case, it appears that you're trying to access the private final java.util.Comparator field of a java.util.TreeMap, which is not accessible because the java.base module does not open java.util to unnamed modules.
Difference between Class and Interface in Java and OOP? (with Example)
10 Essential Object Oriented Concepts for Java Developers
Difference between Static binding vs Dynamic binding in Java? [Answer]
What is Inheritance in Java with example - Object Oriented Programming Tutorial
Inheritance in Java or OOPS (Object-oriented programming) is a feature that allows coding reusability. In other words, Inheritance self-implies inheriting or we can say acquiring something from others. Along with Abstraction, Encapsulation, and Polymorphism, Inheritance forms the backbone of Object-oriented programming and Java. In Java, we use the term inheritance when one object acquires some property from other objects. In Java, inheritance is defined in terms of superclass and subclass. it is normally used when some object wants to use an existing feature of some class and also wants to provide some special feature, so we can say inheritance has given the advantage of reusability.
19 Java and OOP Method Overloading and Overriding Interview Questions and Answers
Difference between Abstraction and Polymorphism in Java and OOP [Answer]
Difference between instance and Object in Java
Saturday, September 23, 2023
How to create a class with methods and attributes in Java? Example Tutorial
Hello guys, we are again with new article that is on Creating Class with methods and attributes in Java. The main aim of this article is to give you idea about how to declare a class or method in Java and about different ways of declaring. In the world of Java programming, class serve as the fundamental building blocks for creating objects and defining the structure of your applications. These classes encapsulate data and behavior, allowing you to model real-world entities and implement the logic that governs their interactions.
How to convert a List to Array in Java? Example Tutorial
How to search a LinkedList in Java? Example
How to get first and last elements form ArrayList in Java
Difference between synchronized ArrayList and CopyOnWriteArrayList in Java?
PriorityQueue in Java? Example Tutorial
Friday, September 22, 2023
10 Common Coding Mistakes Every Java Developers Should be aware of
Hello guys, Java is a versatile and powerful programming language, but it's not immune to common coding mistakes that developers may inadvertently make. These errors can lead to unexpected behavior, performance issues, and even security vulnerabilities. In this article, I am going to share 10 such common coding mistakes Java developers often encounter, provide examples of each mistake, explain why they are problematic, and offer solutions to correct them. I strongly recommend every Java developer whether he is beginner, intermediate or senior developer to go through the list once so that you are aware of these mistakes. If you have been coding in Java then most likely you would have also made the same mistake, if you do, let us know in comments so that we all can learn from each other.
Difference between class and ID selector in jQuery
In jQuery, class and ID selectors are used to select and manipulate elements in the Document Object Model (DOM) based on their attributes. However, they have distinct differences in terms of how they select elements and their application:
Class Selector ($(".class-name")):
Syntax: To select elements by their class, you use the .class-name syntax, where class-name is the name of the CSS class you want to target.
Selection: Class selectors select all elements that have a specific CSS class applied to them. This means that if multiple elements share the same class, all of them will be selected.
Usage: Class selectors are typically used when you want to apply the same behavior or style to multiple elements with a common class.
Example:
javascript
Copy code
// Select all elements with the class "button"
$(".button").click(function() {
// Perform some action
});
ID Selector ($("#element-id")):
Syntax: To select elements by their ID, you use the #element-id syntax, where element-id is the unique ID assigned to the element you want to target.
Selection: ID selectors select a single element with the specified ID. IDs must be unique within a web page, so there should be only one element with a given ID.
Usage: ID selectors are used when you want to target a specific element on the page for a unique operation or manipulation.
Example:
javascript
Copy code
// Select the element with the ID "header"
$("#header").addClass("highlight");
Key Differences:
Uniqueness: Class selectors can select multiple elements with the same class, while ID selectors target a single, unique element with a specific ID.
Performance: ID selectors are generally faster than class selectors because they exploit the uniqueness of IDs, making the search more efficient.
Applicability: Use class selectors when you want to apply a behavior or style to multiple elements with a shared class. Use ID selectors when you need to interact with or manipulate a specific, unique element.
CSS Specificity: In terms of CSS specificity, IDs have higher specificity than classes. This means that rules applied to IDs will override rules applied to classes, which can be important for styling.
In summary, understanding the differences between class and ID selectors in jQuery is essential for efficiently selecting and manipulating elements in your web applications. Select classes when you want to work with multiple elements sharing the same class, and use IDs when you need to interact with a unique element on the page.
main difference between class and Id selector in jQuery is that class selector starts with dot (.) while ID selector starts with pound (#) e.g.
$(".articles") will select all elements which has class articles applied on them
$(#article) will only select the element with id article, remember a webpage cannot have elements with duplicate id, which means on id can only be used by one element.
Though jQuery allows you to select elements using many differnt ways, finding elmeent using tag name is the most common one e.g. $("p") can be used to find all paragraph text or $("li") can be used to find all list tags in the page, but sometime you need to little bit of flexibility.
1) ID Selector is fastest selector in jQuery.
2) ID's should be unique on the page, when you have multiple elements with same ID's, jQuery selects only the first one. That's because it doesn't have to bother looking for others as there isn't supposed to be any more - that might explain the weird behaviour you're experiencing.
3) ID selector always return a single element but class selector can return more than one elements. This happens becasue ID is uninuqe in a page and cannot be shared between elements but class can be shared between multiple elements.
4) Query searches for elements from right to left then walks up the DOM tree to see if they match the next selector going left..
Top 10 Java Code Analysis Tools
Top 10 Java Code Analysis Tools
Efficient and error-free coding practices are vital for the success of any software project. However, even experienced Java developers can inadvertently introduce bugs, security vulnerabilities, or code smells into their applications. To address this, Java code analysis tools come to the rescue. These tools help identify potential issues, enforce coding standards, and improve overall code quality. In this article, we'll delve into the top 10 Java code analysis tools that can significantly enhance your development process.
1. Maven Dependency Analysis:
Maven Dependency Analysis is a part of Apache Maven, a widely used build automation and project management tool. It helps identify and manage dependencies in your project. By analyzing dependencies, you can ensure that your application uses the correct versions of libraries, eliminating potential conflicts.
2. Maven Enforcer Plugin:
The Maven Enforcer Plugin ensures that your project follows specific rules and constraints defined in your Maven build. It helps enforce best practices, such as specifying minimum Java versions, banning certain dependencies, or controlling version ranges, thereby maintaining consistency across your codebase.
3. JSLint Maven Plugin:
JSLint Maven Plugin is a valuable tool for frontend developers working with JavaScript within a Java project. It checks JavaScript code against coding standards and reports any deviations. This ensures that your JavaScript code aligns with best practices and maintains quality.
4. Maven Duplicate Finder Plugin:
The Maven Duplicate Finder Plugin identifies duplicate code in your project, helping to eliminate redundancy and maintain code clarity. It can detect code clones, reducing the chances of bugs propagating throughout your codebase.
5. Checkstyle:
Checkstyle is a popular code analysis tool that enforces coding standards and style guidelines. It supports various coding styles, including Google, Sun, and custom configurations. Checkstyle helps you maintain a consistent coding style throughout your project, making the code more readable and maintainable.
6. PMD:
PMD (Programming Mistake Detector) is a static code analysis tool that detects potential issues, such as code complexity, unused variables, and suboptimal code constructs. PMD provides valuable insights to help developers refactor and optimize their code for better performance and maintainability.
7. FindBugs:
FindBugs is another static code analysis tool that focuses on identifying common bugs and code defects in Java applications. It scans your code for issues like null pointer exceptions, resource leaks, and more, providing actionable recommendations for improvement.
8. Cobertura:
Cobertura is a code coverage analysis tool for Java. It helps you assess the quality of your test suite by identifying areas of code that are not adequately covered by tests. By using Cobertura, you can ensure that your tests exercise your code comprehensively.
9. CodeNarc:
CodeNarc is a static analysis tool specifically designed for Groovy, a dynamic language that runs on the Java Virtual Machine (JVM). It enforces coding standards and identifies potential issues in Groovy codebases, promoting clean and maintainable code.
10. SonarQube:
SonarQube is a comprehensive code analysis platform that supports multiple programming languages, including Java. It provides a centralized dashboard for analyzing code quality, identifying issues, and tracking code smells and vulnerabilities. SonarQube integrates with popular build tools and IDEs, making it a powerful tool for continuous code improvement.
List of Code Analysis Tools:
Maven Dependency Analysis
Maven Enforcer Plugin
JSLint Maven Plugin
Maven Duplicate Finder Plugin
Checkstyle
PMD
FindBugs
Cobertura
CodeNarc
SonarQube
In conclusion, Java code analysis tools are indispensable for maintaining high-quality code, improving codebase maintainability, and ensuring that your software projects are robust and reliable. By integrating these tools into your development process, you can catch issues early, enforce coding standards, and deliver software that meets the highest quality standards. Whether you're a solo developer or part of a large team, leveraging these tools can significantly enhance your Java development workflow.
What is the difference between a trait and an abstract class?
What is the difference between a trait and an abstract class?
--------------------------------------------------------------
The first difference is that a class can only extend one other class, but an unlimited number of traits.
While traits only support type parameters, abstract classes can have constructor parameters.
Also, abstract classes are interoperable with Java, while traits are only interoperable with Java if they do not contain any implementation.
A class can inherit from multiple traits but only one abstract class.
Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. For example, you cant say trait t(i: Int) {}; the i parameter is illegal.
Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code.
trait Car {
val brand: String
}
trait Shiny{
val shineRefraction: Int
}
trait Miles{
val miles: Int
}
class BMW extends Car with Shiny with Miles{
val brand = "BMW"
val shineRefraction = 12
val miles = 500
}
In the realm of object-oriented programming, both traits and abstract classes play essential roles in structuring code and promoting code reusability. However, they have distinct characteristics and use cases that set them apart. In this article, we will explore the key differences between a trait and an abstract class in the Scala programming language.
1. Inheritance Limitations:
One of the fundamental differences between traits and abstract classes lies in their inheritance model. In Scala, a class can extend only one other class, whether it's a concrete class or an abstract class. On the other hand, Scala allows a class to mix in (inherit from) an unlimited number of traits. This trait-based approach provides a flexible mechanism for combining various pieces of functionality in a single class.
2. Constructor Parameters:
Abstract classes and traits also differ in their support for constructor parameters. Abstract classes can have both constructor parameters and type parameters. This means you can pass values to an abstract class when creating an instance. In contrast, traits can only have type parameters; they cannot accept constructor parameters. Attempting to define a trait with constructor parameters is not allowed in Scala.
3. Interoperability with Java:
Scala is often used in conjunction with Java, and interoperability with Java is an essential consideration. Abstract classes have a clear advantage in this regard. They are fully interoperable with Java, meaning you can call them from Java code without any additional wrappers or modifications. Traits, on the other hand, are fully interoperable with Java only if they do not contain any implementation code. If a trait includes concrete method implementations, it becomes less straightforward to use from Java code.
Here's a quick example to illustrate these differences:
scala
Copy code
trait Car {
val brand: String
}
trait Shiny {
val shineRefraction: Int
}
trait Miles {
val miles: Int
}
class BMW extends Car with Shiny with Miles {
val brand = "BMW"
val shineRefraction = 12
val miles = 500
}
In this example, the BMW class inherits from multiple traits (Car, Shiny, and Miles) to combine their functionalities. Traits provide a workaround for Scala's lack of support for multiple inheritance, making it possible to mix in various traits to create a rich class hierarchy.
In summary, traits and abstract classes serve different purposes in Scala. Traits offer a flexible way to mix in multiple sets of behaviors into a class, making up for Scala's limitation on multiple inheritance. Abstract classes, on the other hand, provide constructor parameter support and seamless interoperability with Java. The choice between traits and abstract classes depends on the specific needs of your application and the desired characteristics of your class hierarchy.
In short, traits is Scala's work around for multiple inheritance feature which is not supported in Java.
Top 10 excuse for not doing Unit testing and Code reviews
Top 10 excuse for not doing Unit testing and Code reviews
------------------------------------------------------------
If you have been doing software development for couple of years, then you definitely know advantages of code review and unit test, but you do agree that, though it is widely regarded and accepted as best practice, it not always used as much.
Top 10 Excuses for Avoiding Unit Testing and Code Reviews
While unit testing and code reviews are widely recognized as best practices in software development, the reality is that they are not always embraced as fervently as they should be. Despite their numerous benefits, developers and teams often find themselves making excuses to avoid or delay these essential activities. Here are the top 10 excuses for not prioritizing unit testing and code reviews:
1. Tight Schedules and Timely Delivery:
"We acknowledge the benefits of unit testing and code reviews, but our project timelines are so tight that we can't afford the extra time required for these activities."
2. QA's Responsibility:
"We are paid to write code, and QA is responsible for testing it. Why should we do their job?"
3. Trust in QA's Expertise:
"Our QA team is exceptionally skilled at finding bugs. We have confidence in their ability to catch issues without the need for extensive testing on our part."
4. Post-Release Code Reviews:
"Let's focus on getting the release out the door first. We can always conduct code reviews after the software is deployed. The business has been waiting for this for a long time."
5. Fear of Conflict:
"Code reviews can sometimes lead to conflicts, especially when dealing with developers with strong egos. It's easier to skip them to maintain a harmonious atmosphere."
6. Time Constraints vs. Testing:
"I would love to write unit tests for all my classes, but it will take twice as long to complete this feature. Do you want me to prioritize writing tests over delivering features?"
7. Planned But Delayed Testing:
"Unit testing is on our roadmap, and we intend to revisit it once we have some breathing room in our schedule. Right now, we're swamped with other tasks."
8. Build Speed Concerns:
"Unit tests can slow down our build process significantly. Our agile team relies on a fast build environment, and we can't afford the delay."
9. Monthly Code Reviews:
"I enjoy code reviews, but I wish they were a regular occurrence, at least once a month. It's hard to keep up the momentum when they're infrequent."
10. Code Reviews for Inattentive Programmers:
"Code reviews are more for those developers who don't pay attention while coding. Since we take care to write quality code, we believe they're not necessary for us."
In conclusion, while these excuses may be tempting in the face of tight deadlines, conflicting priorities, and ego considerations, the benefits of unit testing and code reviews cannot be overstated. Embracing these practices leads to better code quality, fewer bugs, improved collaboration, and ultimately, more robust software. It's essential for development teams to recognize the value of these practices and prioritize them in their software development lifecycle. After all, the long-term benefits far outweigh the short-term challenges.
That's all folks, let me know what is your excuse of not doing of code review?
Top 5 Frequently Asked HR Interview Questions in Job Interviews
HR interviews are a standard part of the job application process, and you've likely encountered some seemingly straightforward yet surprisingly tricky questions during these interviews. While some may dismiss these questions as overly simplistic or cliché, they serve a vital purpose in the hiring process. In this article, we'll explore five of the most commonly asked HR interview questions, delve into their significance, and discuss why they continue to be an integral part of job interviews.
1. What Are Your Strengths and Weaknesses?
This classic question often elicits prepared responses from candidates, but its value lies beyond the rehearsed answers. HR professionals use this question to gauge a candidate's honesty, self-awareness, and preparation. While a response like "I work too hard" may come across as scripted, a more genuine answer, such as admitting to occasional emotional decision-making, reveals a candidate's courage and authenticity. Depending on the role, this information can provide insights into a candidate's suitability for the job.
2. Why Are You Looking to Leave Your Current Job?
The question about why you're leaving your current job serves as a window into your motivations and professionalism. It's not just about money; it's about understanding what drives you. Are you seeking new challenges, a better work environment, or improved work-life balance? The way you address this question demonstrates your diplomacy and honesty, without necessarily being negative about your current employer. HR professionals want to assess your seriousness and commitment to the job application.
3. Where Do You See Yourself in 5 Years?
While the classic humorous response is tempting, this question probes your ambition and long-term goals. It allows employers to identify candidates who align with the company's growth trajectory. Some candidates are more ambitious and forward-thinking, while others may seek stability and a balanced work-life scenario. A diverse team requires individuals with varying perspectives on their career trajectories.
4. Why Do You Want to Join Our Company?
This question delves into your knowledge of the company and your reasons for wanting to be a part of it. A generic response focused solely on salary and benefits may not leave a favorable impression. A thoughtful answer, highlighting your interest in the company's products, values, or unique opportunities, demonstrates your genuine enthusiasm for the role. HR professionals are looking for candidates who are genuinely excited about the company and its mission.
5. If You Described Yourself as a Biscuit, What Sort of Biscuit Would You Be?
While seemingly whimsical, this question assesses your ability to think creatively and respond under unexpected circumstances. There isn't a right or wrong answer here; rather, it's an opportunity to showcase your creativity and adaptability. Responding with a playful but tasteful answer can leave a positive impression, demonstrating your ability to handle unconventional questions with a touch of humor. For example, you can say that "Ummm, tasty and expensive"
In conclusion, these commonly asked HR interview questions, often dismissed as cliché, play a vital role in evaluating candidates beyond their technical skills. They provide insights into qualities like honesty, diplomacy, ambition, enthusiasm, and adaptability, which are essential in today's dynamic workplace. So, while you may encounter these questions frequently, remember that your responses reveal more about you than meets the eye, and they can significantly influence the outcome of your job interview.
10 Websites to Learn Programming Online for FREE
10 Websites to Learn Programming Online for FREE
--------------------------------------------------
If you are interested in the Internet and computer and You want to learn programming but do not know where to start?Or feel that time is over and you will not be able to learn programming,The following educational sites list will help you Start learning programming in an easy interactive way.
1-FreeCodeCamp
Is a free site that teaches you programming,Created by Quincy Larson in 2014,Includes a set of tutorials at :HTML-CSS-Js-React.js-Databases-mongoDB.There is also a chat forum with students to solve technical problems.
Advantages :
*Get experience by coding for FREE
*Build projects
*Earn FREE certifications
2-CodeAcademy
Is an educational company aiming to give different tint to teach,It also provides thousands of courses : JavaScript->HTML-CSS-PHP-Python-Ruby-jQuery .It has a team of more than 60 members Contains designers, technicians and experts.Who work to provide the finest lessons,To millions of individuals around the world.
Advantages :
*An interactive platform for more than 24 million people sharing experience
*The user is rewarded with badges when the exercises are finished
3-Coursera
Is an institution that offers a range of free lessons offered by a group of accredited teachers in the finest American universities.Foundations by Andrew Ng & Daphne Koller, a team of computing experts.
Advantages :
*Obtain certified certificates
*Learn in the least possible time
*Source open to all
4-SoloLearn
Is a site that allows you to learn a host of famous programming languages ¹¹such as Python 3, Java, C++, and SQL.In an interactive way that relies on combining lessons with exercises .
Advantages :
*Learning by doing
*You decide when to learn
*Competition from all over the world
5-Edx
Is an educational platform that contains hundreds of free and open source tutorials .A large and qualified team is available to provide the necessary knowledge in programming languages.
Advantages :
*Courses in various magazines
*Supported by Harvard University
*Introducing new techniques to better education
6-KhanAcademy
Is a reliable teaching source that works to spread knowledge in various fields of mathematics, physics, and computers Gives you the ability to learn js-> java->Html-Databases From a team of different peoples of the world.This site was launched in 2006 by SALMAN KHAN Which worked to enlarge the site to become a global site.
Advantages :
*Content is also available in other languages
*There are lessons supported by videos
*The lessons are free and accessible
7-Udacity
Is an institution that offers free courses in various technical journals such as artificial intelligence and machine teaching As well as programming in various languages ¹¹and aims to develop the skills of students by integrating lessons with exercises .
Advantages :
*The best place to start learning to code
*The information is checked before submission
*Free courses from big companies like Google
Udemy
Pluralsight
Educative
That's all about some of the best websites to learn Programming online for FREE.
How to read a line from File in Java?
How to read a line from File in Java?
--------------------------------------
You can read a file line by line using both BufferedReader and Scanner in Java, but if you want to read a specific line in file then its not directly supported in Java. In Java 8, you can also use readAllLines() from File method for reading a file line by line in Java 8.
Solution
Advantages :
Disadvantages :
That's all about how to read a line in Java. You can either read whole file line by line using BufferedReader.readLine() method, or you can use Scanner.nextLine() method for same job. IF you want to read a specific line from file in Java then your only choice is using RandomAccessFile, which provides a file pointer to move around.
Difference between Maven and Gradle in Java
Difference between Maven and Gradle in Java
---------------------------------------------
Maven is a build automation tool mostly for Java projects. It's a great tool, but it has one important drawback that has motivated the creation of similar tools, like Gradle and SBT. That weakness is its verbosity of configuration. Maven gets all project build parameters from pom.xml, an XML file that can get very long.
I think Gradle solves this problem more elegantly, where you can inject common dependencies rather than inherit them.
This tends to give better control and flexibility.
It seems analogous to composition (Gradle) vs. inheritance (Maven) ;-)
Is there a way to specify only select elements to include from a parent POM?
It's not possible, in Maven. But why would you need that? All elements defined in jcabi-parent POM are "optional". When you inherit our pom.xml and don't use them, they won't get into your project.
Further Learning
Thanks for reading this article so far. If you find this article useful then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.
10 Skills You can Learn to become a Senior Developer in 2020
10 Skills You can Learn to become a Senior Developer in 2020
-------------------------------------------------------------
Nobody likes to be in the same place for year and that's also true for junior develoeprs and software engineers. They also want to grow and become Senior pro but many of them don't know what it takes to become a senior developer which companies sought after. In this article, I am going to share some of the essential skills required to beocme a senior software engineer. There is a good chance that you already have many of these skills but not upto the level required to be considered as senior pro, in that case just work on those and level up those skills.
1. Containers
2. Cloud
3. Algorithms
4. Data Structures
5. Concurrency
6. Database
7. Problem Solving
8. Scripting
9. Agile Methodology
10. Automation
That's all about some of the essential skills for programmers who wants to become a senior developer in 2020.
Further Learning
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.
Top 10 Tools for REST API Development and Testing
Top 10 Tools for REST API Development and Testing
--------------------------------------------------
Hello guys, it's been long time since I have shared useful tools. So, today, I am going to write about 10 essential tools for REST API development and Testing. These are the tools which will help you in every stage of your REST based project like design, development, testing, and documentation.
Without wasting anymore of your time, here is my list of 10 useful tools every REST developer should learn
1. Postman
Postman is the most essential tool for API development and testing. It allows you to interact with any REST API by sending differnet kinds of HTTP request like GET, POST, DELETE etc. You can then see the response and also view response headers and codes. It also allows you to send query paramter, customize request headers and much more. You can also use different Authentication method like BASIC authentication to interact with secure REST API. Postman is avaialble both as a desktop application (Postman App) as well as Chrome extension. If your work involves interacting with REST API, it make sense to learn Postman. Its very useful testing REST API as well.
2. cURL
This is a Linux utility or command which can also be used as a great tool to interact with REST APIs from command line. The cURL command allows you to send both GET and POST request and also populate differnet request headers. You can also send authentication credential to interact with secure API. If you love to work in Linux command line then this a great tool to learn.
3. RESTAssured
4. Swagger
5. Burp
Debugging with HTTP Debuggers using Burp as a proxy
6. WireShark
Debugging with packet sniffers using Wireshark
7. RAML
8. JMeter
Using Loader to do load, soak and stress testing
9. SoapUI
This is another intersting tool which you can use
10. Apiary
Using Apiary for designing, documenting and stubbing out your API
That's all about some of the useful tools for REST API developers. A good knowledge of these tools are essential for buiilding real-world REST API. These tools will help you in designing, testing, and even on documentation of your REST API and RESTful Web Services.Thanks for reading this article so far. If you like these REST API tools then plese share with your friends and colleagues. If you have any questions or feedback then please drop a note.
Perl Interview Questions and Answers
Perl Interview Questions and Answers
-------------------------------------
What do variable sigils indicate in Perl 5?
What's the difference between accessing an array element with $items[$index] and @items[$index]?
What's the difference between == and eq?
What do you get if you evaluate a hash in list context?
How do you look up keywords in the Perl documentation?
What is the difference between a function and a method in Perl 5?
When does Perl 5 reclaim the memory used by a variable?
How do you ensure that the default scope of a variable is lexical?
How do you load and import symbols from a Perl 5 module?
What governs how Perl 5 loads modules How can you influence the list of directories from which perl attempts to load modules?
How do you look up error messages in the Perl 5 documentation? (Award bonus points for knowing how to enable explanations of all error messages encountered.)
What happens when you pass an array into a function?
How do you pass one or more distinct arrays into a function?
What is the difference, on the caller side, between return; and return undef;?
Where do tests go in a standard CPAN distribution?
How do you run tests in a standard CPAN distribution?
What command do you use to install new distributions from the CPAN?
Why would you use the three-argument form of the open builtin?
How do you detect (and report) errors from system calls such as open? (Award bonus points for knowing how to enable automatic detection and reporting of errors.)
How do you throw an exception in Perl 5?
How do you catch an exception in Perl 5?
What is the difference between reading a file with for and with while?
How do you handle parameters within a method or function in Perl 5?
What do parentheses around the variable name in my ($value) = @_; mean, and what would happen if you removed them?
Is new a builtin function/keyword?
How do you read the documentation of a core library? A CPAN module?
How do you access only the values of a Perl 5 hash?
That's all about some good Perl Interview Questions and Answers. If you are starting to learn Perl, this list is a good way to measure your skills. A good Perl developer should be able to answer all of these questions without much difficulty and with little bit of study and practice. You can also read a good text on Perl to learn more about these questions e.g. Modern Perl.
Graphs Interview Questions
----------------------------
Breadth first search in a graph
Number of clusters of 1s OR Number of Islands
Topological Sorting of a Directed Acyclic Graph.
Minimum number of trials to reach from source word to destination word
Friend Circles Problem-> Graph Theory
Dijkstra's Shortest Path algorithm
Bellman-Ford Algorithm
14 Multithreading best practices in Java for Experienced Developers
1) Given meaningful name to your threads and thread pool
I can't emphasize this. When dumping threads of a running JVM or during debugging, default thread pool naming scheme is pool-N-thread-M, where N stands for pool sequence number (every time you create a new thread pool, global N counter is incremented) and M is a thread sequence number within a pool. For example pool-2-thread-3 means third thread in second pool created in the JVM lifecycle. See: Executors.defaultThreadFactory(). Not very descriptive. JDK makes it slightly complex to properly name threads because naming strategy is hidden inside ThreadFactory. Luckily Guava has a helper class for that:
import com.google.common.util.concurrent.ThreadFactoryBuilder;
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("Orders-%d")
.setDaemon(true)
.build();
final ExecutorService executorService = Executors.newFixedThreadPool(10, threadFactory);
By default thread pools create non-daemon threads, decide whether this suits you or not.
Let's go through each of these multithreading best practices with examples to illustrate their importance:
2) Minimize inter thread communication and data sharing
Inter-thread communication and data sharing can lead to complex synchronization issues. Minimizing such communication reduces the risk of deadlocks and race conditions. Consider using thread-local variables when possible to avoid sharing data between threads.
Example:
public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
threadLocal.set(42);
int result = threadLocal.get(); // Each thread has its own value
}
}
3) Minimize locking by reducing the scope of synchronized
To avoid contention and improve performance, synchronize only the critical sections of your code, reducing the scope of synchronization.
Example:
public class SynchronizationExample {
private int count = 0;
private Object lock = new Object();
public void increment() {
synchronized (lock) {
count++;
}
}
}
4) Use Immutable objects
Immutable objects are thread-safe by design because they cannot be modified once created. Use them to avoid the need for synchronization when dealing with shared data.
Example:
public final class ImmutableExample {
private final int value;
public ImmutableExample(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
5) Avoid Static variables
Static variables can be shared among all threads, leading to concurrency issues. Minimize their use and prefer instance variables when necessary.
Example:
public class StaticVariableExample {
private static int sharedCount = 0;
public synchronized static void increment() {
sharedCount++;
}
}
6) Use MDC Context for Logging
Logging frameworks like Log4j and Logback provide tools like Mapped Diagnostic Context (MDC) to associate context information with log entries for each thread.
Example (Logback MDC):
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class LoggingExample {
private static final Logger logger = LoggerFactory.getLogger(LoggingExample.class);
public static void main(String[] args) {
MDC.put("user", "john_doe");
logger.info("User logged in.");
MDC.clear();
}
}
7) Always remove ThreadLocal once done
When using ThreadLocal, it's essential to remove the value associated with the current thread once you're done with it to prevent memory leaks.
Example:
public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
threadLocal.set(42);
int result = threadLocal.get();
threadLocal.remove(); // Remove the value when done
}
}
8) Use Lock Stripping (e.g., ReadWriteLock)
Lock stripping techniques, like ReadWriteLock, allow multiple threads to read concurrently while ensuring exclusive access for writes.
Example:
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockExample {
private ReadWriteLock lock = new ReentrantReadWriteLock();
private int data;
public int readData() {
lock.readLock().lock();
try {
return data;
} finally {
lock.readLock().unlock();
}
}
public void writeData(int newData) {
lock.writeLock().lock();
try {
data = newData;
} finally {
lock.writeLock().unlock();
}
}
}
9) Use volatile
The volatile keyword ensures that reads and writes to a variable are directly performed on the main memory, preventing thread-local caching of the variable.
Example:
public class VolatileExample {
private volatile boolean flag = false;
public void toggleFlag() {
flag = !flag;
}
}
10) Use atomic integers for counters:
Atomic integer classes, such as AtomicInteger, provide thread-safe operations for common tasks like incrementing counters.
Example:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
private AtomicInteger counter = new AtomicInteger(0);
public void increment() {
counter.incrementAndGet();
}
public int getCount() {
return counter.get();
}
}
11) Use BlockingQueue for Producer-Consumer design:
BlockingQueue provides a thread-safe way to implement the Producer-Consumer pattern, ensuring proper synchronization between producers and consumers.
Example:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumerExample {
private BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
public void produce(int item) throws InterruptedException {
queue.put(item);
}
public int consume() throws InterruptedException {
return queue.take();
}
}
12) Use Disruptor for fast inter-thread communication:
The Disruptor pattern is designed for high-performance, low-latency inter-thread communication. It offers a ring buffer-based approach for handling data flow between threads efficiently.
13) Minimize context switching of threads:
Reducing context switching, where a CPU switches between threads, improves performance. Minimize unnecessary thread creation and ensure efficient use of existing threads.
14) Use Busy Spin to keep cached data in CPU L1:
Busy spinning is a technique where a thread repeatedly checks for a condition to become true instead of yielding its execution. It can be used when waiting times are short to keep data in CPU caches and reduce latency.
15) Use thread-safety:
Always design your classes and components with thread-safety in mind. Understand the thread-safety guarantees of libraries and frameworks you use and follow best practices to ensure your code is robust in a multi-threaded environment.
In conclusion, these best practices help you write efficient and robust multi-threaded Java applications. By minimizing inter-thread communication, using thread-safe constructs, and following these guidelines, you can avoid common pitfalls and create reliable concurrent systems.