#hashset examples
Explore tagged Tumblr posts
Text
hi
import java.util.HashMap; import java.util.Map;
public class FrequencyCounter { public static void main(String[] args) { int[] nums = {2, 3, 2, 5, 3, 2}; Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } // Print the result for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { System.out.println("Number " + entry.getKey() + " appears " + entry.getValue() + " times."); } }
} ////////////////////
rray = [2, 1, 5, 1, 3, 2] target = 8 We’ll find the longest subarray where the sum is ≤ 8.
We use left, right, and sum to control and track the window .int left = 0, sum = 0, max = 0;
left: starting point of our sliding window
sum: running total of the current window
count: total number of valid subarrays we find
for (int right = 0; right < array.length; right++) { Expands the window by moving the right pointer forward. sum += array[right]; while (sum > target) { sum -= array[left]; left++; } max = Math.max(max, right - left + 1); }
/// Inheritance Inheritance allows a class to inherit fields and methods from another class. It supports code reuse and method overriding.
🔹 10. Polymorphism Polymorphism lets you perform the same action in different ways. It includes compile-time (overloading) and runtime (overriding) polymorphism.
🔹 11. Encapsulation Encapsulation binds data and methods together, hiding internal details. It’s achieved using private fields and public getters/setters.
🔹 12. Abstraction Abstraction hides complex implementation details and shows only the essentials. It’s achieved using abstract classes or interfaces.
List allows duplicates, Set allows only unique elements, Map stores key-value pairs. They are part of the Java Collections Framework f
Lambdas enable functional-style code using concise syntax. They simplify the implementation of functional interfaces.
🔹 19. Functional Interfaces A functional interface has exactly one abstract method. Examples include Runnable, Callable, and Comparator.
Stream API processes collections in a functional and pipeline-based way. It supports operations like filter(), map(), and collect()
Heap stores objects and is shared, while Stack stores method calls and local variables. Stack is thread-safe; Heap is managed by the garbage collector.
Immutable objects, like String, cannot be changed once created. They are thread-safe and useful in concurrent applications.
int left = 0, right = array.length - 1; while (left < right) { if (array[left] + array[right] == target) { // Found pair } else if (array[left] + array[right] < target) { left++; } else { right--; } } //////////////////
kafka partitions
List inputList = // input data Map uniqueMap = new HashMap<>();
for (Person person : inputList) { String key = person.name + "_" + person.age;if (!uniqueMap.containsKey(key)) { uniqueMap.put(key, person); // first time seeing this name+age } else {
///
List people = Arrays.asList( new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35) ); // Sort by age using lambda people.sort((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));
////////////////
public Person(String name, int age) { this.name = name; this.age = age; }@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); }
}
/////////// hashCode() is used by hash-based collections like HashMap, HashSet, and Hashtable to find the bucket where the object should be placed.
bject.equals() method compares memory addresses
///
List people = Arrays.asList( new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35) ); // Sort by age using lambda people.sort((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())); // Print sorted list people.forEach(System.out::println); }
///
0 notes
Text
How are hashCode and equals methods related?
In Java, the hashCode() and equals() methods play a critical role in determining object equality and behavior in hash-based collections like HashMap, HashSet, and Hashtable.
The equals() method is used to compare two objects for logical equality. By default, the equals() method in the Object class compares memory references. However, in most custom classes, this method is overridden to provide meaningful comparison logic—such as comparing object content (fields) rather than memory addresses.
The hashCode() method returns an integer representation of an object’s memory address by default. However, when overriding equals(), it is essential to also override hashCode() to maintain the general contract:
If two objects are equal according to the equals() method, then they must have the same hashCode() value.
Failing to do this can lead to unexpected behavior in collections. For instance, adding two logically equal objects (via equals()) to a HashSet may result in duplicates if hashCode() returns different values for them. This is because hash-based collections first use the hashCode() to find the correct bucket, and then use equals() to compare objects within the same bucket.
Example:
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; MyClass other = (MyClass) obj; return this.id == other.id; } @Override public int hashCode() { return Objects.hash(id); }
In summary, always override both methods together to ensure correct object behavior in collections. A strong grasp of these concepts is crucial for building reliable applications and is a core topic in any full stack Java developer course.
0 notes
Text
Key Concepts to Review Before Your Java Interview
youtube
Java interviews can be both challenging and rewarding, often acting as a gateway to exciting roles in software development. Whether you're applying for an entry-level position or an advanced role, being well-prepared with core concepts is essential. In this guide, we’ll cover key topics to review before your Java interview, ensuring you're confident and ready to impress. Additionally, don't forget to check out this detailed video guide to strengthen your preparation with visual explanations and code demonstrations.
1. Object-Oriented Programming (OOP) Concepts
Java is known for its robust implementation of OOP principles. Before your interview, make sure to have a firm grasp on:
Classes and Objects: Understand how to create and use objects.
Inheritance: Review how subclasses inherit from superclasses, and when to use inheritance.
Polymorphism: Know the difference between compile-time (method overloading) and runtime polymorphism (method overriding).
Abstraction and Encapsulation: Be prepared to explain how and why they are used in Java.
Interview Tip: Be ready to provide examples of how you’ve used these concepts in your projects or coding exercises.
2. Core Java Concepts
In addition to OOP, there are foundational Java topics you need to master:
Data Types and Variables: Understand primitive types (int, double, char, etc.) and how they differ from non-primitive types.
Control Structures: Revise loops (for, while, do-while), conditional statements (if-else, switch-case), and how they control program flow.
Exception Handling: Know how try, catch, finally, and custom exceptions are used to manage errors in Java.
Collections Framework: Familiarize yourself with classes such as ArrayList, HashSet, HashMap, and their interfaces (List, Set, Map).
Interview Tip: Be prepared to discuss the time and space complexities of different collection types.
3. Java Memory Management
Understanding how Java manages memory can set you apart from other candidates:
Heap vs. Stack Memory: Explain the difference and how Java allocates memory.
Garbage Collection: Understand how it works and how to manage memory leaks.
Memory Leaks: Be prepared to discuss common scenarios where memory leaks may occur and how to avoid them.
Interview Tip: You may be asked how to optimize code for better memory management or to explain how Java’s finalize() method works.
4. Multithreading and Concurrency
With modern applications requiring multi-threading for efficient performance, expect questions on:
Threads and the Runnable Interface: Know how to create and run threads.
Thread Lifecycle: Be aware of thread states and what happens during transitions (e.g., from NEW to RUNNABLE).
Synchronization and Deadlocks: Understand how to use synchronized methods and blocks to manage concurrent access, and how deadlocks occur.
Concurrency Utilities: Review tools like ExecutorService, CountDownLatch, and Semaphore.
Interview Tip: Practice writing simple programs demonstrating thread synchronization and handling race conditions.
5. Java 8 Features and Beyond
Many companies expect candidates to be familiar with Java’s evolution, especially from Java 8 onward:
Lambda Expressions: Know how to write concise code with functional programming.
Streams API: Understand how to use streams for data manipulation and processing.
Optional Class: Learn to use Optional for handling null checks effectively.
Date and Time API: Review java.time package for managing date and time operations.
Interview Tip: Be prepared to solve coding problems using Java 8 features to show you’re up-to-date with recent enhancements.
6. Design Patterns
Java interviews often include questions on how to write clean, efficient, and scalable code:
Singleton Pattern: Know how to implement and when to use it.
Factory Pattern: Understand the basics of creating objects without specifying their exact class.
Observer Pattern: Be familiar with the publish-subscribe mechanism.
Decorator and Strategy Patterns: Understand their practical uses.
Interview Tip: Have examples ready that demonstrate how you’ve used these patterns in your projects.
7. Commonly Asked Coding Problems
Prepare by solving coding problems related to:
String Manipulations: Reverse a string, find duplicates, and check for anagrams.
Array Operations: Find the largest/smallest element, rotate arrays, or merge two sorted arrays.
Linked List Questions: Implement basic operations such as reversal, detecting cycles, and finding the middle element.
Sorting and Searching Algorithms: Review quicksort, mergesort, and binary search implementations.
Interview Tip: Practice on platforms like LeetCode or HackerRank to improve your problem-solving skills under time constraints.
Final Preparation Tips
Mock Interviews: Conduct practice interviews with peers or mentors.
Review Your Code: Ensure your past projects and code snippets are polished and ready to discuss.
Brush Up on Basics: Don’t forget to revise simple concepts, as interviews can include questions on any level of difficulty.
For more in-depth preparation, watch this helpful video that provides practical examples and coding tips to boost your confidence.
With these concepts in mind, you'll be well-equipped to handle any Java interview with poise. Good luck!
0 notes
Text
The Ultimate Guide to Java Collection
Java libraries are indispensable tools that streamline development by providing pre-written code for common tasks. "The Ultimate Guide to Java Libraries" explores a myriad of libraries that enhance Java programming, from handling data structures to implementing complex algorithms.
A key feature covered is collections in Java, which offer efficient ways to manage groups of objects, improving code efficiency and readability.
TpointTech is a valuable resource for developers seeking in-depth tutorials and examples on using these libraries effectively. Leveraging these libraries can significantly reduce development time and improve application performance.
Overview of Java Collections
The Java Collections Framework includes interfaces, implementations, and algorithms. The core interfaces include Collection, List, Set, Queue, and Map, each serving different purposes.
Collection Interface:
The root interface of the framework, representing a group of objects known as elements. It is extended by List, Set, and Queue interfaces.
List Interface:
An ordered collection that allows duplicate elements. Common implementations are ArrayList, LinkedList, and Vector. Lists are ideal when you need to access elements by their index.
ArrayList: Resizable array implementation, offering constant-time positional access but slower for insertion and deletion.
LinkedList: Doubly-linked list implementation, providing efficient insertion and deletion but slower access time.
Vector: Synchronized version of ArrayList, rarely used due to performance overhead.
Set Interface:
A collection that does not allow duplicate elements. It models mathematical sets and provides implementations like HashSet, LinkedHashSet, and TreeSet.
HashSet: Uses a hash table for storage, offering constant-time performance for basic operations.
LinkedHashSet: Maintains insertion order, slightly slower than HashSet.
TreeSet: Implements the SortedSet interface, ensuring elements are in ascending order, based on their natural ordering or a specified comparator.
Queue Interface:
Designed for holding elements prior to processing, typically ordered in a FIFO (first-in-first-out) manner. Common implementations include LinkedList, PriorityQueue, and ArrayDeque.
PriorityQueue: Elements are ordered according to their natural ordering or a provided comparator, useful for creating priority-based tasks.
ArrayDeque: Resizable-array implementation of the Deque interface, providing efficient insertion and deletion from both ends.
Map Interface:
Represents a collection of key-value pairs, where each key maps to one value. Popular implementations are HashMap, LinkedHashMap, and TreeMap.
HashMap: Provides constant-time performance for basic operations, assuming a good hash function.
LinkedHashMap: Maintains a doubly-linked list of its entries, preserving the order of insertion.
TreeMap: Implements the SortedMap interface, ensuring keys are in ascending order.
Advantages of Java Collections Framework
Reduces Programming Effort: With a set of ready-made data structures and algorithms, JCF eliminates the need for developers to implement complex data structures from scratch.
Increases Program Speed and Quality: Standardized interfaces and optimized implementations ensure high performance and reliability.
Interoperability: Collections can be easily passed across APIs, reducing the complexity of integration.
Ease of Maintenance: Well-documented and widely-used classes make it easier for developers to maintain and enhance code.
Common Algorithms in JCF
Java Collections Framework includes various algorithms to perform routine tasks, such as sorting, searching, and shuffling. These algorithms are static methods in the Collections utility class.
Sorting: Collections.sort(List list), sorts the specified list into ascending order.
Shuffling: Collections.shuffle(List list), randomly permutes the elements in the list.
Searching: Collections.binarySearch(List> list, T key), performs binary search on a sorted list.
Conclusion
The Java Collections Framework is indispensable for any Java developer. It offers a standardized and efficient way to manage groups of objects, making code more robust and maintainable.
By leveraging the various interfaces and implementations, such as lists, sets, queues, and maps, developers can handle data structures effectively.
Understanding collections in Java, as detailed on resources like TpointTech, is crucial for building high-performance applications. Whether you're a beginner or an experienced developer, mastering Java collections will significantly enhance your programming capabilities.
0 notes
Text
Java Collections Framework: A Comprehensive Guide
The Java Collection Framework (JCF) is one of the most important features of the Java programming language. It provides a unified framework for representing and managing collections, enabling developers to work more efficiently with data structures. Whether you are a beginner or an experienced Java developer, understanding the Java collection system is important. This comprehensive guide will delve into the basic design and implementation of the Java compilation system, highlighting its importance in modern Java programming. The basics of the Java collections framework At its core, the Java collections in Java with Examples consist of interfaces and classes that define collections. These collections can contain objects and provide functions such as insertion, deletion, and traversal. The main features of JCF include List, Set, and Map. Lists are ordered collections of objects, aggregates are unordered collections without duplicate objects, and maps are key-value pairs. Significant interactions with classes in the Java collection system List Interface: Lists in JCF are implemented by classes like ArrayList and LinkedList. ArrayList provides dynamic arrays, allowing quick access to elements, while LinkedList uses a doubly linked list internally, making insertion and deletion faster Set interfaces: Represent classes such as sets, HashSet and TreeSet, and do not allow duplicate elements. HashSet uses hashing techniques for fast access, while TreeSet maintains objects in sorted order, enabling efficient retrieval. Map Interface: Maps are represented by HashMap and TreeMap. HashMap uses hashing to store key-value pairs and provides a constant-time display for basic processing. TreeMap, on the other hand, maintains elements in a sorted tree structure, enabling operations in logarithmic time. Advantages of Java Collections Framework The concurrent Collections in Java Framework offers several benefits to developers: Re-usability: Pre-implemented classes and interfaces let developers focus on solving specific problems without worrying about downstream data structures Interactivity: Collections in JCF can store object by object, encouraging interactivity and allowing developers to work with multiple data types. Performance: The system is designed to be efficient. The algorithm is implemented in such a way that it is efficient in terms of time and memory consumption. Scalability: JCF supports scalability, allowing developers to handle large amounts of data without worrying about memory limitations. Frequent use of information in the Java collections system Data Storage and Retrieval: Lists, sets, and maps are widely used to store and retrieve data efficiently. Lists are suitable for sorted collections, aggregates for unique elements, and maps for key-value pairs. Algorithm Implementation: Java Collections Framework can be used to implement many algorithms such as search and sort. This simplifies the coding process and reduces the possibility of error. Concurrent control: Classes like ConcurrentHashMap and CopyOnWriteArrayList provide concurrent access to collections, ensuring thread safety in multi-threaded applications. Best practices for Java collections systems with examples 1. List Interface (ArrayList):import java.util.ArrayList;import java.util.List; public class ListExample {public static void main(String args) {List list = new ArrayList(); // Adding elements to the list list.add("Java"); list.add("Python"); list.add("C++"); // Accessing elements using index System.out.println("Element at index 1: " + list.get(1)); // Iterating through the list System.out.println("List elements:"); for (String language : list) { System.out.println(language); } // Removing an element list.remove("Python"); System.out.println("List after removing 'Python': " + list); } } 2. Set Interface (HashSet) import java.util.HashSet;import java.util.Set; public class SetExample {public static void main(String args) {Set set = new HashSet(); // Adding elements to the set set.add("Apple"); set.add("Banana"); set.add("Orange"); // Iterating through the set System.out.println("Set elements:"); for (String fruit : set) { System.out.println(fruit); } // Checking if an element exists System.out.println("Contains 'Apple': " + set.contains("Apple")); // Removing an element set.remove("Banana"); System.out.println("Set after removing 'Banana': " + set); } 3. Map Interface (HashMap):import java.util.HashMap;import java.util.Map; public class MapExample {public static void main(String args) {Map map = new HashMap(); // Adding key-value pairs to the map map.put("Java", 1); map.put("Python", 2); map.put("C++", 3); // Iterating through the map System.out.println("Map elements:"); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } // Checking if a key exists System.out.println("Contains key 'Java': " + map.containsKey("Java")); // Removing a key-value pair map.remove("Python"); System.out.println("Map after removing 'Python': " + map); } Conclusion: In Java programming, the Java collections tutorial framework stands as the cornerstone of efficient data manipulation. Its versatile interfaces and classes empower developers to create complex applications, handling data structures with ease. Understanding the nuances of different types of collections, their functionality, and best practices is important for enabling Java developers aiming to build high-performance, scalable, and error-free applications Java collection concepts has been optimized to enable developers to unlock the full programming capabilities of Java Read the full article
0 notes
Text
"Coding in Java with Confidence: A Step-by-Step Mastery Guide"
Java is one of the most popular and widely used programming languages and platforms, offering a versatile environment for developing and executing programs across various domains. It is renowned for its speed, reliability, and robust security features. Its ease of learning, uncomplicated syntax, and roots in C++ make it accessible to programmers of different backgrounds. Java simplifies memory management through its automatic garbage collector, which efficiently cleans up unused objects.
For Beginners commencing on the Path to Java Mastery, This In-Depth Step-by-Step Guide Serves as Your Companion:
Understanding Java: Before venturing forth, it's imperative to answer fundamental questions about Java, such as its nature, reasons for popularity, and distinctive features. Gain clarity on Java by exploring informative articles that not only provide insights but also guide you on the path to effective learning.
Java Environment: A solid understanding of the environment in which Java operates is essential. Familiarize yourself with the intricacies of this environment, including the Java Virtual Machine (JVM). Discover more about the JVM, its architecture, and operational mechanisms by reading this informative article.
Java Programming Basics: Proficiency in any programming language begins with a strong grasp of its fundamentals. Explore into the basics of Java programming through articles that provide in-depth knowledge in a clear and concise format.
Object-Oriented Programming (OOPs) in Java: Java is a prime example of an object-oriented programming (OOP) language. To master Java, it's essential to understand OOP concepts, which simplify program structure by breaking it down into manageable objects.
Classes and Objects in Java: Classes and objects form the foundational concepts of object-oriented programming in Java. They represent real-world entities and serve as the building blocks for Java programming.
Constructors in Java: To efficiently harness the power of Classes and Objects, a comprehensive understanding of Constructors in Java is indispensable. Constructors play a vital role in initializing an object's state. Much like methods, constructors consist of a set of instructions executed at the time of object creation.
Methods in Java: Methods in Java encompass collections of statements designed to execute specific tasks and return results to the caller. Methods can perform specific tasks without necessarily returning values.
Strings in Java: Strings, defined as arrays of characters in Java, exhibit a unique ease of implementation compared to other programming languages. Even beginners can navigate the intricacies of Java's string handling.
Arrays in Java: Arrays in Java differ significantly in their functionality from those in C/C++.
Collections in Java: Collections in Java encapsulate individual objects into cohesive units. Java's Collection Framework furnishes a comprehensive set of classes and interfaces to facilitate the effective management of object collections.
Generics in Java: Generics in Java bear similarities to templates in C++. They empower the parameterization of methods, classes, and interfaces with types, including user-defined types. Classes such as HashSet, ArrayList, and HashMap effectively leverage generics, accommodating various data types.
Stream API in Java: The Stream API, introduced in Java 8, emerges as a potent tool for processing collections of objects. A stream represents a sequence of objects supporting a range of methods that can be pipelined to achieve specific outcomes.
Exceptions and Exception Handling in Java: Exception handling emerges as a recurring theme throughout the learning journey of Java. Unwanted or unexpected events, termed "EXCEPTIONs," may disrupt the orderly progression of program instructions during runtime.
Regular Expressions (Regex) in Java: While the term "Regular Expression" may appear unfamiliar, its significance in development cannot be overstated.
Multithreading in Java: Multithreading constitutes a distinctive Java feature facilitating concurrent execution of multiple program segments to maximize CPU utilization.
File Handling in Java: Java extends its support for file handling, enabling users to manage files by reading, writing, and engaging in various other file-related operations.
Packages in Java: In Java, packages serve as a mechanism for encapsulating a cluster of classes, sub-packages, and interfaces.
If you're interested in expanding your knowledge of Java, consider exploring ACTE Technologies. Their instructors are highly skilled and adept at teaching. You have the flexibility to learn Java online or in a traditional classroom setting. Java learning program at ACTE Technologies provides certifications and job placement assistance. In summary, mastering Java demands patience, dedication, and consistent practice. Staying committed to enhancing your skills is crucial. With sustained effort, you can become proficient in the language and leverage it to develop diverse applications and projects.
0 notes
Text
How to optimize memory in Java?

Optimizing memory usage in Java training near me is essential to ensure efficient and responsive applications while minimizing the risk of memory-related issues like Out Of Memory Errors. Here are several strategies to optimize memory in Java
Use Data Structures Wisely
Choose the appropriate data structures for your application's needs. Efficient data structures can significantly reduce memory consumption.
For example, use ArrayList when the size is dynamic but known in advance and HashSet or HashMap when you need fast lookup operations.
Minimize Object Creation
Excessive object creation can lead to high memory usage and increased garbage collection overhead. Reuse objects whenever possible.
Consider using object pooling or object reclamation techniques to reduce object churn.
String Handling
Be mindful of string concatenation operations, as they can create many temporary string objects. Use StringBuilder or StringBuffer for efficient string concatenation.
If you have many identical strings, consider using string interning to reuse string instances.
Avoid Memory Leaks
Be cautious about holding references to objects longer than necessary. Ensure that objects are eligible for garbage collection when they are no longer needed.
Use weak references or soft references when appropriate to allow objects to be collected more easily.
Use Primitive Data Types
Whenever possible, use primitive data types (int, float, char, etc.) instead of their object counterparts (Integer, Float, Character, etc.) to save memory.
Array Optimization
Use arrays instead of collections (e.g., ArrayList) when the size is known and fixed, as arrays have a smaller memory overhead.
Be cautious with multi-dimensional arrays, as they can consume more memory than expected due to padding.
Memory Profiling
Use memory profiling tools to identify memory leaks and memory-hungry parts of your application. Tools like VisualVM or YourKit can help pinpoint memory issues.
Garbage Collection Tuning
Tune the garbage collection settings using JVM flags (e.g., -Xmx, -Xms, -XX:MaxHeapFreeRatio, -XX:MinHeapFreeRatio, etc.) to optimize heap memory management.
0 notes
Text
What is the basic fundamental of Java?

Java is a powerful, object-oriented programming language that is widely used in the software industry for building scalable, secure, and platform-independent applications. Whether you are a beginner exploring the world of coding or an experienced developer brushing up on core concepts, understanding the basic fundamentals of Java is crucial.
In this article, we’ll explore the key principles that make up the foundation of Java programming and why mastering them is essential for any developer.
Why Learn Java Fundamentals First?
Java is not just a language—it’s a comprehensive ecosystem. Grasping the basics helps you write efficient code, debug effectively, and transition smoothly to more advanced topics like frameworks, APIs, and libraries.
Foundational knowledge is often what sets apart a beginner from a confident coder.
1. Java Syntax and Structure
Every Java program must follow a specific structure and syntax. The code is organized into classes and methods, and Java is case-sensitive. Here’s a quick overview of the structure:
java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Key Elements:
class: Everything in Java revolves around classes.
main(): Entry point of any Java application.
System.out.println(): Used to print output.
2. Data Types and Variables
Understanding data types is one of the most fundamental parts of programming in Java. Java is a statically typed language, meaning variables must be declared before use.
Primary Data Types:
int – integers
double – floating-point numbers
char – single characters
boolean – true or false
Variable Example:
java
int age = 25;
boolean isStudent = true;
3. Control Flow Statements
Control flow dictates how a program runs and under what conditions certain blocks of code are executed.
Main Control Statements:
if, else if, else
switch
for, while, do-while loops
break, continue
Example:
java
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
4. Object-Oriented Programming (OOP)
Java is fundamentally an object-oriented language. This means that the design of the program revolves around creating objects from classes.
Core OOP Principles:
Encapsulation – Binding data and methods together
Inheritance – Reusing code from one class in another
Polymorphism – One interface, many implementations
Abstraction – Hiding internal implementation details
Example:
java
class Animal {
void sound() {
�� System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Understanding OOP is vital if you want to build scalable and maintainable applications in Java. These principles are taught step-by-step in the Best Java course in Chandigarh, which focuses on both theory and real-time project application.
5. Java Methods and Functions
In Java, methods are blocks of code that perform a specific task and can be reused.
Method Syntax:
java
public static int add(int a, int b) {
return a + b;
}
Methods help you:
Break down complex problems
Avoid code repetition
Improve readability
6. Arrays and Collections
Java provides tools to store multiple values:
Arrays: Fixed-size, same data type
ArrayList, HashMap, HashSet (Collections): Flexible and dynamic
Example:
java
int[] numbers = {1, 2, 3, 4};
System.out.println(numbers[0]); // Output: 1
Collections are particularly useful in real-world Java development where data needs to be stored, searched, or manipulated efficiently.
7. Exception Handling
Errors are inevitable. Java provides a robust exception handling system that ensures your application doesn't crash unexpectedly.
Syntax:
java
try {
int divide = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Handling exceptions makes your code more resilient and user-friendly.
8. Java Development Tools
Java developers rely on a variety of tools for writing, testing, and deploying code, such as:
IDEs like IntelliJ IDEA or Eclipse
Build tools like Maven or Gradle
Version control systems like Git
Debuggers and profilers for performance monitoring
Learning how to use these tools early on will help you become an efficient developer.
Conclusion
The basic fundamentals of Java—from syntax and variables to object-oriented principles and exception handling—are essential stepping stones for every programmer. Whether you aim to build Android apps, enterprise solutions, or web applications, these core concepts are non-negotiable.
If you’re looking to get a solid foundation with hands-on practice and expert guidance, enrolling in the Best Java course in Chandigarh can significantly accelerate your learning journey. These courses typically include project-based learning, resume-building exercises, and mentorship to help you succeed in real-world scenarios.
0 notes
Text
Java Full Course
Introduction to Java
Java is one of the most popular and widely used programming languages in the world. Known for its platform independence, robust performance, and vast ecosystem, Java powers everything from enterprise applications and mobile apps to web servers and embedded systems. Developed by Sun Microsystems in 1995 and now maintained by Oracle Corporation, Java continues to be a top choice for developers and organizations alike.
In this full course overview, we will cover the core concepts of Java, from the basics to object-oriented programming, key libraries, and essential tools. Whether you're a beginner or someone brushing up their skills, this guide provides a structured learning path to mastering Java.
Chapter 1: Java Basics
What is Java?
Java is a high-level, object-oriented, class-based programming language. It follows the principle of "Write Once, Run Anywhere" (WORA), meaning compiled Java code can run on any platform that supports Java without recompilation.
Key Features:
Platform Independent: Thanks to the Java Virtual Machine (JVM)
Object-Oriented: Everything in Java is treated as an object
Robust and Secure: Strong memory management and exception handling
Multithreaded: Supports concurrent execution of two or more threads
Portable: Java programs can be moved easily from one computer system to another
Chapter 2: Setting Up Java
Prerequisites:
A computer with Windows, macOS, or Linux
Basic understanding of computers and programming logic
Installation Steps:
Download and install the Java Development Kit (JDK) from the Oracle website.
Install an IDE (Integrated Development Environment) like IntelliJ IDEA, Eclipse, or NetBeans.
Set the JAVA_HOME environment variable and configure the system path.
Verify the setup using the command: pgsql java -version
javac -version
Chapter 3: First Java Program
Let’s write a simple program to print "Hello, World!" on the screen.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Breakdown:
public class HelloWorld: Class definition
public static void main(String[] args): Main method - entry point of the program
System.out.println(): Outputs text to the console
Chapter 4: Variables and Data Types
Java has strong type-checking. You must declare the type of every variable.
Data Types:
int: Integer numbers
float, double: Decimal numbers
char: Single characters
boolean: true or false
String: Sequence of characters (not a primitive type)
Example:
int age = 25;
double salary = 45000.50;
char grade = 'A';
boolean isEmployed = true;
String name = "John";
Chapter 5: Operators and Control Statements
Java includes arithmetic, relational, logical, and assignment operators.
Control Structures:
if, else if, else
switch
for, while, do-while loops
Example:
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
Chapter 6: Object-Oriented Programming (OOP)
Java is based on OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
1. Classes and Objects
class Car {
String color = "Red";
void drive() {
System.out.println("Car is driving");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.drive();
}
}
2. Inheritance
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
3. Polymorphism and Overloading
class MathUtil {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Chapter 7: Arrays and Collections
Arrays:
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]); // Outputs 3
Collections:
ArrayList
HashMap
HashSet
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
Chapter 8: Exception Handling
Java provides built-in mechanisms to handle runtime errors.
Try-Catch Block:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Finally Block:
Always executed whether an exception is caught or not.
finally {
System.out.println("Cleanup code here");
}
Chapter 9: File Handling
Reading and Writing Files:
import java.io.*;
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello File");
writer.close();
BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
String line = reader.readLine();
System.out.println(line);
reader.close();
Chapter 10: Java Multithreading
Java supports multithreaded programming via the Thread class and the Runnable interface.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
MyThread t1 = new MyThread();
t1.start();
Chapter 11: Java GUI with Swing
Java Swing allows the creation of window-based applications.
import javax.swing.*;
public class GUIExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My App");
JButton button = new JButton("Click Me");
frame.add(button);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Chapter 12: Introduction to Java Frameworks
Once you are comfortable with core Java, consider exploring frameworks that help build robust applications:
Spring Boot: For building web applications and APIs
Hibernate: For database interaction
JavaFX: For rich desktop applications
These frameworks are heavily used in real-world enterprise environments.
Conclusion
Java remains a critical language in software development, suitable for everything from backend systems and web apps to Android development and cloud computing. By mastering the concepts in this course—from basics to object-oriented programming, file handling, and multithreading—you’ll have a solid foundation to move on to advanced topics and frameworks.
What to Learn Next:
JDBC and Database integration
REST APIs using Spring Boot
Unit Testing with JUnit
Maven/Gradle for project management
Java 8+ Features like Streams and Lambda Expressions
Whether you aim to become a backend developer, Android engineer, or full-stack Java specialist, continuous practice and hands-on projects are key. Happy coding!
0 notes
Text
hi
fizzbuzz reverse string implement stack
convert integer to roman numeral longest palindrome substring
design hashset
Java group by sort – multiple comparators example https://leetcode.com/discuss/interview-question/848202/employee-implementation-online-assessment-hackerrank-how-to-solve
SELECT SUBQUERY1.name FROM (SELECT ID,name, RIGHT(name, 3) AS ExtractString FROM students where marks > 75 ) SUBQUERY1 order by SUBQUERY1.ExtractString ,SUBQUERY1.ID asc ;
SELECT *
FROM CITY
WHERECOUNTRYCODE = 'USA' AND POPULATION > 100000;
Regards
Write a simple lambda in Java to transpose a list of strings long value to a list of long reversed. Input: [“1”,”2”,”3”,”4”,”5”] output: [5,4,3,2,1] 2. Write a Java Program to count the number of words in a string using HashMap.
Sample String str = "Am I A Doing the the coding exercise Am" Data model for the next 3 questions:
Write a simple lambda in Java to transpose a list of strings long value to a list of long reversed. Input: [“1”,”2”,”3”,”4”,”5”] output: [5,4,3,2,1] 2. Write a Java Program to count the number of words in a string using HashMap.
Sample String str = "Am I A Doing the the coding exercise Am" Data model for the next 3 questions:
Customer :
CustomerId : int Name : varchar(255)
Account :
AccountId : int CustomerId : int AccountNumber : varchar(255) Balance : int
Transactions : Transactionid : int AccountId: int TransTimestamp : numeric(19,0) Description : varchar(255) Amount(numeric(19,4)) 3. Write a select query to find the most recent 10 transactions. 4. Write a select query, which, given an customer id, returns all the transactions of that customer. 5. What indexes should be created for the above to run efficiently? CustomerId, AccountId 6. Write a program to sort and ArrayList.
Regards
0 notes
Text
Mastering C# Collections: Enhance Your Coding Skills and Streamline Data Management
As a developer, it is essential to have a solid understanding of data management in programming languages. In C#, collections play a crucial role in efficiently organizing and manipulating data. Collections are containers that allow you to store and retrieve multiple values of the same or different types. They provide powerful ways to manage data, improve code readability, and enhance overall coding skills.
Benefits of using collections in C
Using collections in C# offers several benefits that contribute to better coding practices and streamlined data management. Firstly, collections provide a structured approach to store and organize data, making it easier to access and manipulate specific elements. Unlike traditional arrays, collections offer dynamic resizing, allowing you to add or remove elements as needed, without worrying about size limitations.
Secondly, collections provide a wide range of built-in methods and properties that simplify common data operations. For example, you can easily sort, filter, or search elements within a collection using predefined methods. This saves time and effort in writing custom algorithms for such operations.
Thirdly, collections support type safety, ensuring that you can only store elements of specific types within a collection. This helps prevent runtime errors and enhances code reliability. Additionally, collections allow you to iterate over elements using loops, making it easier to perform batch operations or apply transformations to each element.
Understanding different collection types in C
C# offers a variety of collection types, each designed for specific use cases. Let's explore some of the most commonly used collection types in C# and understand their characteristics:
Arrays: Arrays are the most basic collection type in C#. They provide a fixed-size structure to store elements of the same type. Arrays offer efficient memory allocation and fast access to elements, but they lack dynamic resizing capabilities.
Lists: Lists, represented by the List<T> class, are dynamic collections that can grow or shrink based on the number of elements. They provide methods to add, remove, or modify elements at any position within the list. Lists are widely used due to their flexibility and ease of use.
Dictionaries: Dictionaries, represented by the Dictionary<TKey, TValue> class, store key-value pairs. They enable fast retrieval of values based on a unique key. Dictionaries are ideal for scenarios where you need to quickly access elements by their associated keys.
Sets: Sets, represented by the HashSet<T> class, store unique elements without any specific order. They provide methods to add, remove, or check for the existence of elements efficiently. Sets are useful when you need to perform operations like union, intersection, or difference between multiple collections.
Queues: Queues, represented by the Queue<T> class, follow the First-In-First-Out (FIFO) principle. Elements are added to the end of the queue and removed from the front, maintaining the order of insertion. Queues are commonly used in scenarios where you need to process items in the order of their arrival.
Stacks: Stacks, represented by the Stack<T> class, follow the Last-In-First-Out (LIFO) principle. Elements are added to the top of the stack and removed from the same position. Stacks are useful when you need to implement algorithms like depth-first search or undo/redo functionality.
Exploring C# generic collections
C# also provides a powerful feature called generic collections, which allow you to create strongly typed collections. Generic collections are parameterized with a specific type, ensuring type safety and eliminating the need for explicit type casting. Let's explore some commonly used generic collection types in C#:
List: Generic lists provide the flexibility of dynamically resizing collections while ensuring type safety. You can create a list of any type by specifying the desired type within angle brackets. For example, List<int> represents a list of integers, and List<string> represents a list of strings.
Dictionary: Generic dictionaries store key-value pairs, similar to non-generic dictionaries. However, generic dictionaries provide type safety and better performance. You can specify the types of keys and values when creating a dictionary. For example, Dictionary<string, int> represents a dictionary with string keys and integer values.
HashSet: Generic hash sets store unique elements without any specific order. They provide efficient lookup, insertion, and removal operations. You can create a hash set of any type by specifying the desired type within angle brackets. For example, HashSet<string> represents a hash set of strings.
Queue: Generic queues follow the First-In-First-Out (FIFO) principle, similar to non-generic queues. They ensure type safety and provide methods to enqueue and dequeue elements. You can create a queue of any type by specifying the desired type within angle brackets. For example, Queue<int> represents a queue of integers.
Stack: Generic stacks follow the Last-In-First-Out (LIFO) principle, similar to non-generic stacks. They ensure type safety and provide methods to push and pop elements. You can create a stack of any type by specifying the desired type within angle brackets. For example, Stack<string> represents a stack of strings.
By utilizing generic collections, you can write cleaner and more robust code, eliminating potential runtime errors and enhancing code maintainability.
Sample C# codes for working with collections
To illustrate the usage of collections in C#, let's explore some sample code snippets that demonstrate common operations:
Working with Lists:
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Orange");
Console.WriteLine("Total fruits: " + fruits.Count);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
if (fruits.Contains("Apple"))
{
Console.WriteLine("Apple is present in the list.");
}
fruits.Remove("Banana");
Console.WriteLine("Total fruits after removing Banana: " + fruits.Count);
Working with Dictionaries:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Emily", 30);
ages.Add("Michael", 35);
Console.WriteLine("Age of John: " + ages["John"]);
foreach (KeyValuePair<string, int> entry in ages)
{
Console.WriteLine(entry.Key + ": " + entry.Value);
}
if (ages.ContainsKey("Emily"))
{
Console.WriteLine("Emily's age: " + ages["Emily"]);
}
ages.Remove("Michael");
Console.WriteLine("Total entries after removing Michael: " + ages.Count);
These code snippets demonstrate basic operations like adding elements, iterating over collections, checking for element existence, and removing elements. Modify and experiment with these code snippets to understand the behavior of different collection types and their methods.
Examples of common use cases for collections in C
Collections in C# find applications in various scenarios. Let's explore some common use cases where collections prove to be invaluable:
Data storage and retrieval: Collections provide a convenient way to store and retrieve data. For example, you can use a list to store a collection of customer details, a dictionary to store key-value pairs representing configuration settings, or a queue to manage incoming requests.
Sorting and searching: Collections offer built-in methods for sorting and searching elements. You can easily sort a list of objects based on specific properties or search for elements that meet certain criteria. Collections eliminate the need for writing complex sorting or searching algorithms from scratch.
Batch processing and transformations: Collections allow you to iterate over elements using loops, enabling batch processing and transformations. For example, you can apply a discount to each item in a list, convert a list of strings to uppercase, or filter out elements based on specific conditions.
Efficient memory management: Collections provide dynamic resizing capabilities, ensuring efficient memory utilization. Unlike arrays, which have a fixed size, collections automatically resize themselves based on the number of elements. This prevents unnecessary memory allocation or wastage.
Concurrency and thread safety: Collections in C# offer thread-safe alternatives, ensuring safe access and manipulation of data in multi-threaded environments. For example, the ConcurrentDictionary<TKey, TValue> class provides thread-safe operations for dictionary-like functionality.
By leveraging the power of collections, you can simplify complex data management tasks, improve code readability, and enhance the overall efficiency of your C# applications.
Comparing C# collection vs list
One common question that arises when working with collections in C# is the difference between a collection and a list. While a list is a specific type of collection, there are some key distinctions to consider:
Collections: In C#, the term "collection" refers to a general concept of a container that stores and organizes data. Collections encompass various types like arrays, lists, dictionaries, sets, queues, and stacks. Collections provide a higher-level abstraction for data management and offer a range of operations and properties that can be applied to different scenarios.
List: A list, on the other hand, is a specific type of collection provided by the List<T> class in C#. It offers dynamic resizing capabilities, allowing you to add or remove elements as needed. Lists provide methods to insert, remove, or modify elements at any position within the list. Lists are commonly used due to their flexibility and ease of use.
In summary, a list is a type of collection that offers dynamic resizing and additional methods for element manipulation. Collections, on the other hand, encompass a broader range of container types, each designed for specific use cases.
Best practices for efficient data management using collections
To utilize collections effectively and ensure efficient data management in C#, consider the following best practices:
Choose the appropriate collection type: Select the collection type that best suits your specific use case. Consider factors like data size, performance requirements, element uniqueness, and the need for sorting or searching operations. Choosing the right collection type can significantly impact the efficiency of your code.
Use generics for type safety: Whenever possible, utilize generic collections to ensure type safety. By specifying the type of elements stored in a collection, you can eliminate potential runtime errors and improve code maintainability. Generic collections also eliminate the need for explicit type casting.
Prefer foreach loops for iteration: When iterating over elements in a collection, prefer the foreach loop over traditional indexing with a for loop. Foreach loops provide a more concise syntax and handle underlying details like bounds checking and iteration logic automatically.
Consider performance implications: Be mindful of performance implications, especially when dealing with large data sets. For example, using a List<T> for frequent insertions or removals at the beginning of the list may result in poor performance. In such cases, consider using a LinkedList<T> or other suitable collection type.
Dispose disposable collections: If you are using collections that implement the IDisposable interface, ensure proper disposal to release any unmanaged resources. Wrap the usage of such collections in a using statement or manually call the Dispose() method when you are done working with them.
By following these best practices, you can optimize your code for efficient data management and enhance the overall performance of your C# applications.
Advanced techniques for optimizing collection performance
While collections in C# are designed to provide efficient data management out of the box, there are advanced techniques you can employ to further optimize collection performance:
Preallocate collection size: If you know the approximate number of elements that will be stored in a collection, consider preallocating the size using the constructor or the Capacity property. This eliminates unnecessary resizing operations and improves performance.
Avoid unnecessary boxing and unboxing: Boxing and unboxing operations, where value types are converted to reference types and vice versa, can impact performance. Whenever possible, use generic collections to store value types directly, eliminating the need for boxing and unboxing.
Implement custom equality comparers: If you are working with collections that require custom equality checks, consider implementing custom equality comparers. By providing a specialized comparison logic, you can improve the performance of operations like searching, sorting, or removing elements.
Use parallel processing: In scenarios where you need to perform computationally intensive operations on collection elements, consider utilizing parallel processing techniques. C# provides the Parallel class and related constructs to parallelize operations, taking advantage of multi-core processors.
Profile and optimize: Regularly profile your code to identify performance bottlenecks. Use tools like profilers to measure execution times and memory usage. Once identified, optimize the critical sections of your code by employing appropriate algorithms or data structures.
By employing these advanced techniques, you can further enhance the performance of your C# collections and optimize your code for maximum efficiency.
Conclusion and next steps for mastering C# collections
In this article, we explored the world of C# collections and their significance in enhancing your coding skills and streamlining data management. We discussed the benefits of using collections in C#, understanding different collection types, and explored generic collections for strong typing. We also provided sample code snippets and examples of common use cases for collections.
Furthermore, we compared collections to lists, outlined best practices for efficient data management, and explored advanced techniques for optimizing collection performance. By following these guidelines, you can harness the full power of C# collections and elevate your coding skills to the next level.
To master C# collections, continue practicing with different types of collections, experiment with advanced scenarios, and explore additional features and methods provided by the .NET framework. Keep exploring the vast possibilities offered by collections, and strive to write clean, efficient, and maintainable code.
Start your journey to mastering C# collections today and witness the transformation in your coding skills and data management capabilities.
Next Steps: To further enhance your skills and understanding of C# collections, consider exploring the official Microsoft documentation on .NET collections and data structures. Additionally, practice implementing collections in real-world scenarios and collaborate with fellow developers to exchange ideas and best practices. Happy coding!
0 notes
Text
LinkedHashSet Class in Java With Program Example
LinkedHashet is an implementation class of the Set interface which also extends the HashSet class. It was introduced in Java 1.4 version. It behaves in the same manner as HashSet except that it preserves or maintains the insertion order of elements inserted in the set. In simple words, It is an implementation of the set interface that stores and manipulates an ordered collection of elements. It…
View On WordPress
#collection#collection framework#data structure#HashTable#java#java program#Linked List#LinkedHashSet
0 notes
Text
Top Java Interview Questions You Should Know
Preparing for a Java interview can be daunting, especially when you're unsure of what to expect. Mastering common Java questions is crucial for making a lasting impression. This blog covers the top Java interview questions you should know and provides tips for answering them effectively. For a more interactive learning experience, check out this Java interview preparation video, which breaks down key concepts and interview strategies.
1. What is Java?
Answer: Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). It is designed to have as few implementation dependencies as possible, allowing developers to write code that runs on all platforms supporting Java without the need for recompilation.
Pro Tip: Mention the "write once, run anywhere" (WORA) principle during your interview to emphasize your understanding of Java’s cross-platform capabilities.
2. What is the Difference Between JDK, JRE, and JVM?
Answer:
JDK (Java Development Kit): Contains tools for developing Java applications, including the JRE and compilers.
JRE (Java Runtime Environment): A subset of JDK, containing libraries and components required to run Java applications.
JVM (Java Virtual Machine): The part of the JRE responsible for executing Java bytecode on different platforms.
Pro Tip: Explain how these components interact to demonstrate a deeper understanding of Java's execution process.
3. Explain OOP Principles in Java
Answer: Java is based on four main principles of Object-Oriented Programming (OOP):
Encapsulation: Bundling data and methods that operate on the data within one unit (class).
Inheritance: Creating a new class from an existing class to promote code reuse.
Polymorphism: The ability of a method or function to behave differently based on the object calling it.
Abstraction: Hiding complex implementation details and showing only the necessary features.
Pro Tip: Use a real-world example to illustrate these principles for better impact.
4. What are Constructors in Java?
Answer: Constructors are special methods used to initialize objects in Java. They have the same name as the class and do not have a return type. There are two types:
Default Constructor: Automatically created if no other constructors are defined.
Parameterized Constructor: Accepts arguments to initialize an object with specific values.
Pro Tip: Highlight the differences between constructors and regular methods, and explain constructor overloading.
5. What is the Difference Between == and .equals() in Java?
Answer:
==: Used to compare primitive data types or check if two object references point to the same memory location.
.equals(): Used to compare the content within objects. This method should be overridden for custom comparison logic in classes.
Pro Tip: Demonstrating this concept with code snippets can be a game-changer in your interview.
6. What are Java Collections?
Answer: The Java Collections Framework (JCF) provides a set of classes and interfaces to handle collections of objects. Commonly used collections include:
List (e.g., ArrayList, LinkedList)
Set (e.g., HashSet, TreeSet)
Map (e.g., HashMap, TreeMap)
Pro Tip: Be prepared to discuss the performance differences between various collections and when to use each.
7. What is Exception Handling in Java?
Answer: Exception handling in Java involves managing runtime errors to maintain normal program flow. The main keywords used are:
try: Block to wrap code that might throw an exception.
catch: Block to handle the exception.
finally: Block that always executes, used for cleanup code.
throw and throws: Used to manually throw an exception and indicate that a method may throw an exception, respectively.
Pro Tip: Discuss custom exceptions and when it is appropriate to create them for better code design.
8. What is Multithreading in Java?
Answer: Multithreading is a feature in Java that allows concurrent execution of two or more threads. It is useful for performing multiple tasks simultaneously within a program.
Pro Tip: Familiarize yourself with the Thread class and Runnable interface. Highlight synchronization and thread-safe practices to show advanced understanding.
9. What are Lambda Expressions in Java?
Answer: Introduced in Java 8, lambda expressions provide a concise way to implement functional interfaces. They enable writing cleaner, more readable code for single-method interfaces (e.g., using a lambda to sort a list).
Example:
java
Copy code
List<String> list = Arrays.asList("apple", "banana", "cherry");
list.sort((a, b) -> a.compareTo(b));
Pro Tip: Mention how lambda expressions contribute to functional programming in Java.
10. What is the Significance of the final Keyword?
Answer: The final keyword can be used with variables, methods, and classes to restrict their usage:
Variables: Makes the variable constant.
Methods: Prevents method overriding.
Classes: Prevents inheritance.
Pro Tip: Explain how using final can improve security and design integrity in your applications.
Conclusion
Reviewing these questions and understanding their answers can prepare you for technical interviews. For additional explanations and examples, check out this detailed Java interview preparation video.
youtube
0 notes
Text
Set, HashSet, LinkedHashSet, and TreeSet in Java with Sample Programs | Java Collections
Set, HashSet, LinkedHashSet, and TreeSet in Java with Sample Programs | Java Collections
Get a nearer glimpse at Established, HashSet, LinkedHashSet, and TreeSet in Java with sample systems. [Video] by · Sep. 28, 21 · Java Zone · Presentation Resource url

View On WordPress
0 notes
Conversation
Goal-Oriented Behaviours in Artificial Intelligence for Games
Often times, game developers will want to create an AI unit that is looking to accomplish a specific goal or set of goals. In games such as Hyrule Warriors, AI characters attempt to accomplish any given goal, stopping along the way to fight any enemies that hinder their progress. In this case, each character is given an end “destination”, then runs through a Finite State Machine (FSM) to determine when an enemy is prevent the character from progressing. For something as simple as “go to this location, stopping to kill enemies along the way”, FSMs work extremely well. They’re relatively simple to program, relatively efficient for these small-scale projects, and tend to work really well for multiple units that run the same functionality. However, in games that are constantly expanding and have to implement new features, such as F.E.A.R., the AI units also need to be able to adapt. This is where Goal Oriented Behaviours (GOB) come in.
GOBs take FSMs, which have defined entry and exit transitions between two (static) states and completely decouple the code tying any two states together. As such, each “state” (which will now be referred to as an “action”) has preconditions that are required in order to run and effects that are activated once the action has been completed. In implementing the system this way, we can easily add or remove features as we see fit, meaning that the system can be easily expanded for future development without potentially destroying the pre-existing framework. Orkin describes this process that F.E.A.R. uses perfectly, mentioning the
To begin with, every action shares a few characteristics. With this in mind, creating a singular abstract base class that each action will stem from makes the most sense. Each action will have some form of target, which is normally a location where the action will be performed. Additionally, each action should contain a cost (although it’s not necessary) and a handful of abstract functions, such as checking if an action needs to be within a defined range, if the action can be run, and a function to reset the action once it’s been completed. Finally, the base class should also contain a definition for functions to add preconditions and effects. To store each precondition and effect, I’d recommend using HashSets of KeyValuePairs or . It’s an extremely simple way of handling expanding lists of complicated data and works relatively efficiently.
Each class should also be a subclass of the base action class and implement the abstract functions defined above. Additionally, each action's constructors should add each precondition and effect that action requires and completes. With that out of the way, we can now create our behaviour tracker.
GOBs work exceptionally well when used as a state within a FSM. As such, we can create a “GOBState” class, which basically begins running the GOB. This state class knows the other necessary states of the FSM (move, idle, perform), the set of available actions, and an empty queue that will contain the list of actions to execute. When a specific state is to be executed, the GOBState class moves to a “Planner” class, which determines how the AI’s current goal will be achieved. Similar to most pathfinding algorithms, it takes cost into account, determining the cheapest way to accomplish the goal. The algorithm begins by finding the goal within a created tree of possible paths. Afterward, it navigates the tree to the highest node, then sends the result to the GOBState class as a Queue, which will then execute the given commands. The tree itself is created by putting each effect as a leaf, then adding the actions that cause those effects as a parent of that leaf.
The best example of this method can be viewed through Brent Owens’ demo, where multiple AI units have various actions they have to achieve, with their main objective being to collect resources, deposit them, and repair/obtain tools if deemed necessary. A lot of the understanding comes from the article (shown below), so I would highly recommend diving through both his demo and post for extra clarification.
References
Chaudhari, Vedant. “Goal Oriented Action Planning.” Medium, Medium, 12 Dec. 2017, https://medium.com/@vedantchaudhari/goal-oriented-action-planning-34035ed40d0b.
Orkin, Jeff. Three States and a Plan; The A.I. of F.E.A.R. 2006, http://alumni.media.mit.edu/~jorkin/gdc2006_orkin_jeff_fear.pdf.
Owens, Brent. “Goal Oriented Action Planning for a Smarter AI.” Game Development Envato Tuts , 23 Apr. 2014, https://gamedevelopment.tutsplus.com/tutorials/goal-oriented-action-planning-for-a-smarter-ai--cms-20793.
1 note
·
View note
Text
RADIX scrypto 1
Accounts on the Radix network are actually Scrypto components that hold resource containers and define rules for accessing them.
You can instantiate a new account component in the simulator with the resim new-account
This will give you back the created account’s address, public key and private key.
Additionally, at any time, you can find the current default account with the command resim show-configs.
You can send tokens from the default account to another one by running the command:
resim transfer [amount] [resource_address] [recipient_address]
Let’s verify the balance of the second account. You can query the state of an address with the resim show [address] command.
resim show resource_sim1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqs6d89k
to easily create a boilerplate Scrypto package with basic functionality. To do this, simply type the following command scrypto new-package [package_name].
Directory Structure
At the root of the generated package directory, you should find the src, and tests folders plus a Cargo.toml file.
The tests folder is where you write the integration tests for your package. You can run the tests located in this directory with the scrypto test command.
All packages must have a lib.rs file - which is the starting point of your Scrypto package.
You can think of blueprints and components like classes and objects in object-oriented programming.
When you create a new project with the scrypto new-package command, it creates a Scrypto package. A simple package, like the HelloToken example, will only contain a single blueprint but you could “package” together multiple blueprints that need each-other to work when deploying them on the ledger. That way, you are certain that all your blueprints are deployed at the same time and the platform knows that those blueprints are related to each other.
(즉 하나의 팩키지에 여러개의 블루프린트가 있을수있으며 하나의 팩키지안의 여러 블루프린트는 서��� 연관되어있다고 여겨진다)
#[blueprint]. A blueprint definition must contain a struct and an impl section with the name of the blueprint
impl 블락 안에
you will write the functions callable on the blueprint itself and the methods callable on the instantiated components.
It’s important to make a distinction between functions and methods:
Functions can be called on the blueprints and do not have access to any state.
Methods on the other hand are callable on individual components and are able to get data from the state and update or mutate it.
위는 function 의 한 예시
위는 method의 한 예시
&mut self가 전달되면 메소드 가 된다
Safe Types
These types are just like the u8, i8, u16, etc. but they differ in the fact that they panic (and make the transaction fail) if an overflow occurs when doing operations on them. You define these types by using an uppercase U for unsigned numbers and uppercase I for signed numbers:
I8, I16, I32, I64, I128, I256, I384, I512
U8, U16, U32, U64, U128, U256, U384, U512
They also have the benefit of offering 384 bits and 512 bits options instead of a maximum of 128 bits.
Strings
The String type is supported in Scrypto.
Floating points
the Rust types f32 and f64 representing floating point numbers are not supported in Scrypto. Instead, we offer the Decimal and PreciseDecimal types that allow you to represent numbers with a fractional part using fixed point arithmetic (which is deterministic).
you have to wrap the number in quotes (as seen for c and e in the previous example). If you don’t, you will not be able to compile your package because it will detect the use of floating point numbers.
The Decimal type supports a maximum of 18 decimal places -if you need more you should use PreciseDecimal which supports up to 64 decimal places:
Collections
Scrypto supports the basic Rust collections like Vec, HashMap and HashSet. We also provide a new type KeyValueStore which is like a HashMap, but it does not load the full content of the Map until you request it. Here are some examples:
Scrypto Types
The PackageAddress, ComponentAddress and ResourceAddress types are used to work with the different address types. The Scrypto types you will work with the most are the Bucket and Vault types
Creating Custom Types
You create a custom type by writing a struct outside of the blueprint! definition. It is important to remember to add the line #[scrypto(ScryptoCategorize, ScryptoEncode, ScryptoDecode, LegacyDescribe)] before the struct block. This adds, at compile time, methods to the type to make it compatible with the Radix Engine. Here is an example:
To test our blueprint locally we will use resim. You may recall we saw how to use resim to create accounts and transfer tokens in the simulator. By running the resim --help command you will see that you can do much more with resim. In our case, we will use it to publish our package to the local simulator, instantiate our component, and call a method to interact with it.
To ensure we have a clean slate to begin with let’s run resim reset and then generate a new default account by running resim new-account be sure to save the account address as we will want to inspect it later. You can save this as an environment variable for convenience or just create a file for your own reference to copy and paste.
The next step is to build and deploy the package. You can do that with the following command: resim publish . (make sure you are in the hello_token directory!).
To create an instance of our deployed blueprint we will use the package address that we just received to instantiate our component by calling the instantiate_hello function on the Hello blueprint by running
resim call-function [package_address] [blueprint_name] [function]
which will look something like this:
resim call-function package_sim1qxxkyjgkyryztmtlsypzd8244xkvqeln32aqdersgk3szcwxzq Hello instantiate_hello
After running the call-function command above, you will get various information about the transaction that was executed.
Now that we have an instantiated Hello component, all the methods defined by its blueprint are exposed to us and callable. We are going to call the free_token method on it with a resim command resim call-method [component_address] [method]
token도 resource 중의 한가지 이다
Resources are built into the platform
Resources on Radix need to always be placed in some kind of resource containers. Resource containers, as the name suggest, hold resources. Each resource container can only hold one type of resource and the purpose of these resource containers are to properly move, secure, and account for the resources that are being transacted. There are two types of resource containers: Bucket and Vault.
Bucket - Buckets are temporary containers and are used to move resources during a transaction; therefore, only exist in the duration of the transaction.
Vault - Vaults are permanent containers and at the end of each transaction, all resources must be stored in a Vault.
Scrypto offers a handful of utilities to conveniently create and manage resources.
ResourceBuilder - The ResourceBuilder is used to create Fungible and NonFungible resources.
ResourceManager - When a resource is created, a ResourceManager is also created to manage the resource.
The ResourceBuilder is a Scrypto utility that we use to create Fungible and NonFungible resources. Below is a table summarizing the methods provided by the ResourceBuilder for Fungible resources.
Notice that we have fields such as color and rarity. These values are a selection of enums and if you're not familiar with enums, the Rust handbook provides a section on enums.
Creating a NonFungible Resource
Creating a NonFungible resource is a little different from creating a Fungible resource as we saw in the earlier section. To give some context, when we create a NonFungible resource, the collection of the NonFungible resource will have one ResourceAddress. However, each individual NonFungible that we decide to mint will have its own unique identifiers called NonFungibleLocalId. We have an option of data types we can declare to be our NonFungibleLocalId, but it is a requirement to declare a type.
아래는 integer를 id 로 사용하는 경우이다
Creating NFTs with a Mutable Supply
You can create NFTs with no specified initial supply. To do so, we would need to create a badge that will be held by the component Vault.
Viewing, Utilizing, and Mutating NonFungibleData
full example code
0 notes