#Java String to Int
Explore tagged Tumblr posts
tpointtechblog · 1 year ago
Text
Java String to Int: A Comprehensive Guide for Developers
Introduction to Java String to Int: In the world of Java programming, converting strings to integers is a common task that developers encounter frequently.
Whether you're parsing user input, manipulating data from external sources, or performing calculations, understanding how to convert strings to integers is essential.
Tumblr media
In this comprehensive guide, we'll explore the various techniques, best practices, and considerations for converting strings to integers in Java.
Understanding String to Int Conversion:
Before diving into the conversion process, it's important to understand the difference between strings and integers in Java.
Strings are sequences of characters, while integers are numeric data types used to represent whole numbers. The process of converting a string to an integer involves parsing the string and extracting the numerical value it represents.
Using parseInt() Method:
One of the most common methods for converting strings to integers in Java is the parseInt() method, which is part of the Integer class. This method takes a string as input and returns the corresponding integer value. It's important to note that parseInt() can throw a NumberFormatException if the string cannot be parsed as an integer, so error handling is essential.
Example:
String str = "123"; int num = Integer.parseInt(str); System.out.println("Integer value: " + num);
Handling Exceptions:
As mentioned earlier, the parseInt() method can throw a NumberFormatException if the string is not a valid integer.
To handle this exception gracefully, developers should use try-catch blocks to catch and handle the exception appropriately. This ensures that the application doesn't crash unexpectedly if invalid input is provided.
Using valueOf() Method:
In addition to parseInt(), Java also provides the valueOf() method for converting strings to integers. While value Of() performs a similar function to parseInt(), it returns an Integer object rather than a primitive int. This can be useful in certain situations where an Integer object is required instead of a primitive int.
Example:
String str = "456"; Integer num = Integer.valueOf(str); System.out.println("Integer value: " + num);
Considerations and Best Practices:
When converting strings to integers in Java, there are several considerations and best practices to keep in mind:
Always validate input strings to ensure they represent valid integers before attempting conversion.
Handle exceptions gracefully to prevent application crashes and improve error handling.
Use parseInt() or valueOf() depending on your specific requirements and whether you need a primitive int or Integer object.
Consider performance implications, especially when dealing with large volumes of data or performance-critical applications.
Conclusion:
Converting strings to integers is a fundamental task in Java programming Language, and understanding the various techniques and best practices is essential for developers.
By following the guidelines outlined in this comprehensive guide, you'll be well-equipped to handle string to int conversion efficiently and effectively in your Java projects.
Happy coding!
1 note · View note
snixx · 1 year ago
Text
bitch java is so fucking annoying why does the S in String need to be capitalized but the i in int has to be in lowercase??? why do you need to import a whole ass module just to take an input from the user??? why are all the commands so fucking long and hard to remember??? JUST DIE
138 notes · View notes
vala-official · 1 month ago
Text
int main (string args[]) {
hi! i can't believe nobody has created this account yet!
but anyway... ever wished your java had more segfaults and undefined behavior?
4 notes · View notes
digitaldetoxworld · 1 month ago
Text
The C Programming Language Compliers – A Comprehensive Overview
 C is a widespread-purpose, procedural programming language that has had a profound have an impact on on many different contemporary programming languages. Known for its efficiency and energy, C is frequently known as the "mother of all languages" because many languages (like C++, Java, and even Python) have drawn inspiration from it.
C Lanugage Compliers 
Tumblr media
Developed within the early Seventies via Dennis Ritchie at Bell Labs, C changed into firstly designed to develop the Unix operating gadget. Since then, it has emerge as a foundational language in pc science and is still widely utilized in systems programming, embedded systems, operating systems, and greater.
2. Key Features of C
C is famous due to its simplicity, performance, and portability. Some of its key functions encompass:
Simple and Efficient: The syntax is minimalistic, taking into consideration near-to-hardware manipulation.
Fast Execution: C affords low-degree get admission to to memory, making it perfect for performance-critical programs.
Portable Code: C programs may be compiled and run on diverse hardware structures with minimal adjustments.
Rich Library Support: Although simple, C presents a preferred library for input/output, memory control, and string operations.
Modularity: Code can be written in features, improving readability and reusability.
Extensibility: Developers can without difficulty upload features or features as wanted.
Three. Structure of a C Program
A primary C application commonly consists of the subsequent elements:
Preprocessor directives
Main function (main())
Variable declarations
Statements and expressions
Functions
Here’s an example of a easy C program:
c
Copy
Edit
#include <stdio.H>
int important() 
  �� printf("Hello, World!N");
    go back zero;
Let’s damage this down:
#include <stdio.H> is a preprocessor directive that tells the compiler to include the Standard Input Output header file.
Go back zero; ends this system, returning a status code.
4. Data Types in C
C helps numerous facts sorts, categorised particularly as:
Basic kinds: int, char, glide, double
Derived sorts: Arrays, Pointers, Structures
Enumeration types: enum
Void kind: Represents no fee (e.G., for functions that don't go back whatever)
Example:
c
Copy
Edit
int a = 10;
waft b = three.14;
char c = 'A';
five. Control Structures
C supports diverse manipulate structures to permit choice-making and loops:
If-Else:
c
Copy
Edit
if (a > b) 
    printf("a is more than b");
 else 
Switch:
c
Copy
Edit
switch (option) 
    case 1:
        printf("Option 1");
        smash;
    case 2:
        printf("Option 2");
        break;
    default:
        printf("Invalid option");
Loops:
For loop:
c
Copy
Edit
printf("%d ", i);
While loop:
c
Copy
Edit
int i = 0;
while (i < five) 
    printf("%d ", i);
    i++;
Do-even as loop:
c
Copy
Edit
int i = zero;
do 
    printf("%d ", i);
    i++;
 while (i < 5);
6. Functions
Functions in C permit code reusability and modularity. A function has a return kind, a call, and optionally available parameters.
Example:
c
Copy
Edit
int upload(int x, int y) 
    go back x + y;
int important() 
    int end result = upload(3, 4);
    printf("Sum = %d", result);
    go back zero;
7. Arrays and Strings
Arrays are collections of comparable facts types saved in contiguous memory places.
C
Copy
Edit
int numbers[5] = 1, 2, three, 4, five;
printf("%d", numbers[2]);  // prints three
Strings in C are arrays of characters terminated via a null character ('').
C
Copy
Edit
char name[] = "Alice";
printf("Name: %s", name);
8. Pointers
Pointers are variables that save reminiscence addresses. They are powerful but ought to be used with care.
C
Copy
Edit
int a = 10;
int *p = &a;  // p factors to the address of a
Pointers are essential for:
Dynamic reminiscence allocation
Function arguments by means of reference
Efficient array and string dealing with
9. Structures
C
Copy
Edit
struct Person 
    char call[50];
    int age;
;
int fundamental() 
    struct Person p1 = "John", 30;
    printf("Name: %s, Age: %d", p1.Call, p1.Age);
    go back 0;
10. File Handling
C offers functions to study/write documents using FILE pointers.
C
Copy
Edit
FILE *fp = fopen("information.Txt", "w");
if (fp != NULL) 
    fprintf(fp, "Hello, File!");
    fclose(fp);
11. Memory Management
C permits manual reminiscence allocation the usage of the subsequent functions from stdlib.H:
malloc() – allocate reminiscence
calloc() – allocate and initialize memory
realloc() – resize allotted reminiscence
free() – launch allotted reminiscence
Example:
c
Copy
Edit
int *ptr = (int *)malloc(five * sizeof(int));
if (ptr != NULL) 
    ptr[0] = 10;
    unfastened(ptr);
12. Advantages of C
Control over hardware
Widely used and supported
Foundation for plenty cutting-edge languages
thirteen. Limitations of C
No integrated help for item-oriented programming
No rubbish collection (manual memory control)
No integrated exception managing
Limited fashionable library compared to higher-degree languages
14. Applications of C
Operating Systems: Unix, Linux, Windows kernel components
Embedded Systems: Microcontroller programming
Databases: MySQL is partly written in C
Gaming and Graphics: Due to performance advantages
2 notes · View notes
redfoxbytes · 5 months ago
Text
Java
Eines meiner ersten Codes die ich in Java geschrieben habe, war das hier:
public class JunusVideo { public static void main(String[] args) {
String name = "Mulder"; String beruf = "Programmierer";
gruss(19);
System.out.println("Ich heiße " + name + " und Arbeite als " + beruf + "."); }
public static void gruss(int hour) {
if (hour < 12) { System.out.println("Guten Morgen!"); } else if (hour < 18) { System.out.println("Guten Tag!"); } else { System.out.println("Guten Abend!"); } } }
Das erste was ich getippt habe und verstanden habe. Ich war sehr stolz darauf. :) Vor allem, weil ich ihn etwas anders gemacht hatte, als im Tutorial und sehr stolz darauf war.
Apropos Tutorial, gelernt habe ich von Junus auf Youtube. Tolle Videos. Sehr einfach erklärt. Kann ich jedem wärmstens ans Herz legen, der erst einsteigt.
youtube
2 notes · View notes
sqlinjection · 8 months ago
Text
LDAP testing & defense
LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements through techniques similar to SQL Injection. 
LDAP injection attacks are common due to two factors:
The lack of safer, parameterized LDAP query interfaces
The widespread use of LDAP to authenticate users to systems.
How to test for the issue
During code review
Please check for any queries to the LDAP escape special characters, see here.
Automated Exploitation
Scanner module of tool like OWASP ZAP have module to detect LDAP injection issue.
Remediation
Escape all variables using the right LDAP encoding function
The main way LDAP stores names is based on DN (distinguished name). You can think of this like a unique identifier. These are sometimes used to access resources, like a username.
A DN might look like this
cn=Richard Feynman, ou=Physics Department, dc=Caltech, dc=edu
or
uid=inewton, ou=Mathematics Department, dc=Cambridge, dc=com
There are certain characters that are considered special characters in a DN. The exhaustive list is the following: \ # + < > , ; " = and leading or trailing spaces
Each DN points to exactly 1 entry, which can be thought of sort of like a row in a RDBMS. For each entry, there will be 1 or more attributes which are analogous to RDBMS columns. If you are interested in searching through LDAP for users will certain attributes, you may do so with search filters. In a search filter, you can use standard boolean logic to get a list of users matching an arbitrary constraint. Search filters are written in Polish notation AKA prefix notation.
Example:
(&(ou=Physics)(| (manager=cn=Freeman Dyson,ou=Physics,dc=Caltech,dc=edu) (manager=cn=Albert Einstein,ou=Physics,dc=Princeton,dc=edu) ))
When building LDAP queries in application code, you MUST escape any untrusted data that is added to any LDAP query. There are two forms of LDAP escaping. Encoding for LDAP Search and Encoding for LDAP DN (distinguished name). The proper escaping depends on whether you are sanitising input for a search filter, or you are using a DN as a username-like credential for accessing some resource.
Safe Java for LDAP escaping Example:
public String escapeDN (String name) {
//From RFC 2253 and the / character for JNDI
final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'};
String escapedStr = new String(name);
//Backslash is both a Java and an LDAP escape character,
//so escape it first escapedStr = escapedStr.replaceAll("\\\\\\\\","\\\\\\\\");
//Positional characters - see RFC 2253
escapedStr = escapedStr.replaceAll("\^#","\\\\\\\\#");
escapedStr = escapedStr.replaceAll("\^ | $","\\\\\\\\ ");
for (int i=0 ; i < META_CHARS.length ; i++) {
escapedStr = escapedStr.replaceAll("\\\\" + META_CHARS[i],"\\\\\\\\" + META_CHARS[i]);
}
return escapedStr;
}
3 notes · View notes
nectoy7 · 8 months ago
Text
Understanding Java Data Types: A Comprehensive Guide
Java, one of the most widely used programming languages, is known for its portability, security, and rich set of features. At the core of Java programming are data types, which define the nature of data that can be stored and manipulated within a program. Understanding data types is crucial for effective programming, as they determine how data is stored, how much memory it occupies, and the operations that can be performed on that data.
What are Data Types?
In programming, data types specify the type of data that a variable can hold. They provide a way to classify data into different categories based on their characteristics and operations. Java categorizes data types into two main groups:
1. Primitive Data Types
2. Reference Data Types
Why Use Data Types?
1. Memory Management: Different data types require different amounts of memory. By choosing the appropriate data type, you can optimize memory usage, which is particularly important in resource-constrained environments.
2. Type Safety: Using data types helps catch errors at compile time, reducing runtime errors. Java is a statically typed language, meaning that type checks are performed during compilation.
3. Code Clarity: Specifying data types makes the code more readable and understandable. It allows other developers (or your future self) to quickly grasp the intended use of variables.
4. Performance Optimization: Certain data types can enhance performance, especially when dealing with large datasets or intensive calculations. For example, using int instead of long can speed up operations when the range of int is sufficient.
5. Defining Operations: Different data types support different operations. For example, you cannot perform mathematical operations on a String data type without converting it to a numeric type.
When and Where to Use Data Types?
1. Choosing Primitive Data Types:
Use int when you need a whole number without a decimal, such as counting items.
Use double for fractional numbers where precision is essential, like financial calculations.
Use char when you need to store a single character, such as a letter or symbol.
Use boolean when you need to represent true/false conditions, like in conditional statements.
2. Choosing Reference Data Types:
Use String for any textual data, such as names, messages, or file paths.
Use Arrays when you need to store multiple values of the same type, such as a list of scores or names.
Use Custom Classes to represent complex data structures that include multiple properties and behaviors. For example, a Car class can encapsulate attributes like model, year, and methods for actions like starting or stopping the car.
1. Primitive Data Types
Primitive data types are the most basic data types built into the Java language. They serve as the building blocks for data manipulation in Java. There are eight primitive data types:
Examples of Primitive Data Types
1. Byte Example
byte age = 25; System.out.println(“Age: ” + age);
2. Short Example
short temperature = -5; System.out.println(“Temperature: ” + temperature);
3. Int Example
int population = 1000000; System.out.println(“Population: ” + population);
4. Long Example
long distanceToMoon = 384400000L; // in meters System.out.println(“Distance to Moon: ” + distanceToMoon);
5. Float Example
float pi = 3.14f; System.out.println(“Value of Pi: ” + pi);
6. Double Example
double gravitationalConstant = 9.81; // m/s^2 System.out.println(“Gravitational Constant: ” + gravitationalConstant);
7. Char Example
char initial = ‘J’; System.out.println(“Initial: ” + initial);
8. Boolean Example
boolean isJavaFun = true; System.out.println(“Is Java Fun? ” + isJavaFun);
2. Reference Data Types
Reference data types, unlike primitive data types, refer to objects and are created using classes. Reference data types are not defined by a fixed size; they can store complex data structures such as arrays, strings, and user-defined classes. The most common reference data types include:
Strings: A sequence of characters.
Arrays: A collection of similar data types.
Classes: User-defined data types.
Examples of Reference Data Types
1. String Example
String greeting = “Hello, World!”; System.out.println(greeting);
2. Array Example
int[] numbers = {1, 2, 3, 4, 5}; System.out.println(“First Number: ” + numbers[0]);
3. Class Example
class Car {     String model;     int year;
    Car(String m, int y) {         model = m;         year = y;     } }
public class Main {     public static void main(String[] args) {         Car car1 = new Car(“Toyota”, 2020);         System.out.println(“Car Model: ” + car1.model + “, Year: ” + car1.year);     } }
Type Conversion
In Java, type conversion refers to converting a variable from one data type to another. This can happen in two ways:
1. Widening Conversion: Automatically converting a smaller data type to a larger data type (e.g., int to long). This is done implicitly by the Java compiler.
int num = 100; long longNum = num; // Widening conversion
2. Narrowing Conversion: Manually converting a larger data type to a smaller data type (e.g., double to int). This requires explicit casting.
double decimalNum = 9.99; int intNum = (int) decimalNum; // Narrowing conversion
Conclusion
Understanding data types in Java is fundamental for effective programming. It not only helps in managing memory but also enables programmers to manipulate data efficiently. Java’s robust type system, consisting of both primitive and reference data types, provides flexibility and efficiency in application development. By carefully selecting data types, developers can optimize performance, ensure type safety, and maintain code clarity.
By mastering data types, you’ll greatly enhance your ability to write efficient, reliable, and maintainable Java programs, setting a strong foundation for your journey as a Java developer.
3 notes · View notes
reversedumbrella · 2 years ago
Note
your colour seperating program, I made something basically identical a few years ago in Python, would love to hear an in depth everything about it, especially how you made the spinning gif
Sorry for the delay I've been kinda busy. I also had various reasons I didn't want to share my code, but I've thought about a better/different way so here it goes (but for the time being I'm as far away from my computer as I possibly could)
I used processing, which is, as far as I remember, based on java but focused on visual media
Starting with the gif part, processing has the save() and saveFrame() methods that save the image displayed, and it also has the "movie maker" that allows you to make GIFs (and others but I don't remember)
I don't know about other languages but processing runs setup() when it starts and draw() every frame
In setup() I load an image as a PImage (processing's image data type like an array or string) and access it's pixel list. Using that I fill a 256x256x256 int array where every color corresponds to a place in the array. This 3d int array is filled with the amount of times each color appears
Lastly I use a log function to convert those numbers into the dot size
During draw() I run through this array and use the point() method to draw every dot (I can define a dot's color using stroke() and it's size using stroke weight() )
There are some optimisations I don't have the patience to explain at the moment
Processing has various render modes. I've made 3d images using the 2d render but I didn't want to repeat the feat (pov: you make 3d in 2d and then your teacher explains the existence of 3d to you). It also has the translate() that moves the origin and rotate(), rotateX() rotateY() and rotateZ() that allows you to rotate the image
I don't know how much you know about processing so sorry if you don't understand or if I'm explaining things you already know
8 notes · View notes
tpointtechblog · 1 year ago
Text
Java Convert String to int | TpointTech
In Java, you can convert a Java String to an int using the Integer.parseInt() or Integer.valueOf() method.
Example:
String str = "123"; int num = Integer.parseInt(str); // Converts String to int System.out.println(num); //
Output:
123
int num = Integer.valueOf(str); // Also converts String to int
Both methods work similarly, but valueOf() returns an Integer object, while parseInt() returns a primitive int.
1 note · View note
java-highlight · 6 days ago
Text
Từ Khóa: this trong Java | Các Cách Sử Dụng và Ý Nghĩa
Từ Khóa this trong Java là một từ khóa quan trọng, đóng vai trò thiết yếu trong lập trình hướng đối tượng (OOP). Từ khóa này được sử dụng để tham chiếu đến đối tượng hiện tại của lớp, giúp lập trình viên xử lý các tình huống liên quan đến biến, phương thức, hoặc hàm tạo một cách rõ ràng và hiệu quả. Trong bài viết này, chúng ta sẽ khám phá ý nghĩa của this trong Java, các cách sử dụng phổ biến và những lưu ý quan trọng khi áp dụng. Bài viết được tối ưu hóa để bạn dễ dàng hiểu và áp dụng từ khóa this trong các dự án lập trình Java.
Tumblr media
Ảnh mô tả các chức năng của từ khóa this.
This trong Java là gì?
This trong Java là một tham chiếu đặc biệt, được sử dụng để chỉ đối tượng hiện tại của lớp mà phương thức hoặc hàm tạo đang được gọi. Nói một cách đơn giản, this giúp phân biệt giữa các biến instance (biến của đối tượng) và các biến cục bộ hoặc tham số có cùng tên. Từ khóa này thường xuất hiện trong các lớp Java khi bạn cần làm rõ ràng ngữ cảnh của đối tượng.
Ví dụ, nếu bạn có một lớp với một biến instance và một tham số cùng tên trong hàm tạo, this sẽ giúp bạn xác định rõ biến nào thuộc về đối tượng hiện tại.
class SinhVien { String ten; int tuoi; SinhVien(String ten, int tuoi) { this.ten = ten; // Phân biệt biến instance "ten" và tham số "ten" this.tuoi = tuoi; } }
Trong ví dụ trên, this.ten tham chiếu đến biến instance của lớp SinhVien, còn ten là tham số được truyền vào hàm tạo.
Các cách sử dụng this trong Java
Từ khóa this có nhiều ứng dụng khác nhau trong Java. Dưới đây là các cách sử dụng phổ biến nhất:
1. This để phân biệt biến instance và tham số
Đây là cách sử dụng phổ biến nhất của this trong Java. Khi tên biến instance và tham số hoặc biến cục bộ trùng nhau, this được sử dụng để chỉ rõ biến instance của lớp. class NhanVien { String hoTen; void setHoTen(String hoTen) { this.hoTen = hoTen; // Gán giá trị tham số hoTen cho biến instance hoTen } }
Trong trường hợp này, this.hoTen là biến instance, còn hoTen là tham số của phương thức setHoTen.
2. Gọi hàm tạo khác trong cùng một lớp
This trong Java cũng có thể được sử dụng để gọi một hàm tạo khác trong cùng một lớp. Điều này giúp tái sử dụng mã và tránh lặp lại logic khởi tạo.
class SanPham { String ten; double gia; SanPham(String ten) { this(ten, 0.0); // Gọi hàm tạo khác } SanPham(String ten, double gia) { this.ten = ten; this.gia = gia; } }
Trong ví dụ này, hàm tạo SanPham(String ten) gọi hàm tạo SanPham(String ten, double gia) bằng cách sử dụng this.
3. Truyền this như một tham số
This trong Java có thể được truyền như một tham số cho phương thức hoặc hàm tạo khác, thường được sử dụng khi một đối tượng cần truyền chính nó vào một phương thức khác.
class Xe { String tenXe; Xe(String tenXe) { this.tenXe = tenXe; } void hienThi(Xe xe) { System.out.println("Tên xe: " + xe.tenXe); } void goiHienThi() { hienThi(this); // Truyền đối tượng hiện tại làm tham số } }
4. Trả về đối tượng hiện tại
This cũng có thể được sử dụng để trả về đối tượng hiện tại từ một phương thức, hỗ trợ kỹ thuật gọi chuỗi phương thức (method chaining).
class TaiKhoan { double soDu; TaiKhoan napTien(double soTien) { this.soDu += soTien; return this; // Trả về đối tượng hiện tại } TaiKhoan rutTien(double soTien) { this.soDu -= soTien; return this; } }
Ví dụ trên cho phép gọi chuỗi phương thức như sau: TaiKhoan tk = new TaiKhoan(); tk.napTien(1000).rutTien(500);
Lưu ý khi sử dụng this trong Java
Mặc dù this trong Java rất hữu ích, bạn cần lưu ý một số điểm để sử dụng nó hiệu quả:
Không sử dụng trong phương thức static: This chỉ hoạt động trong ngữ cảnh của một đối tượng (instance). Trong các phương thức static, this không thể được sử dụng vì chúng không thuộc về một đối tượng cụ thể.
Cẩn thận khi gọi hàm tạo: Khi sử dụng this để gọi hàm tạo khác, câu lệnh this() phải là câu lệnh đầu tiên trong hàm tạo.
Tối ưu hóa mã: Chỉ sử dụng this khi cần thiết để tránh làm mã trở nên phức tạp hoặc khó đọc.
Vì sao this trong Java quan trọng?
This trong Java giúp mã nguồn rõ ràng hơn, đặc biệt khi làm việc với các lớp phức tạp có nhiều biến và phương thức. Việc sử dụng this không chỉ giúp phân biệt các biến mà còn hỗ trợ tái sử dụng mã, cải thiện tính dễ đọc và bảo trì. Hơn nữa, this là một công cụ mạnh mẽ trong lập trình hướng đối tượng, giúp lập trình viên tận dụng tối đa các tính năng của Java.
Kết luận
This trong Java là một từ khóa không thể thiếu trong lập trình hướng đối tượng. Từ việc phân biệt biến instance và tham số, gọi hàm tạo, đến hỗ trợ method chaining, this mang lại sự linh hoạt và rõ ràng cho mã nguồn. Bằng cách hiểu rõ cách sử dụng và các lưu ý liên quan, bạn có thể áp dụng this một cách hiệu quả trong các dự án Java của mình.
Hãy luyện tập với các ví dụ thực tế và áp dụng this trong Java vào các dự án của bạn để nắm vững từ khóa này. Nếu bạn có thắc mắc hoặc cần thêm ví dụ, hãy để lại câu hỏi để được giải đáp chi tiết!
Từ Khóa: this trong Java | Ý nghĩa, cách sử dụng và lưu ý quan trọng Hướng dẫn đầy đủ cách áp dụng this trong constructor, method và khi phân biệt biến toàn cục. 🌍 Website: Java Highlight | Website Học Lập Trình Java | Blogs Java
0 notes
vatt-world · 7 days ago
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
mukundanebritah · 12 days ago
Text
java- single constructor Vs multiple constructors
❌ The Multiple Constructor Example
public class Human {
private String name;
private int limbs;
private String skinColor;
public Human(String name) {
this(name, 4, "Unknown"); // Magic numbers!
}
public Human(String name, int limbs) {
this(name, limbs, "Unknown");
}
Why this fails: Hidden assumptions (Why default limbs = 4?), duplicate validation (What if limbs < 0?), brittle maintenance (Adding bloodType breaks all constructors)
✅ The Single Constructor Solution
public class Human {
private final String name; // Required
private final int limbs; // Required
private final String skinColor; // Required
public Human(String name, int limbs, String skinColor) {
Objects.requireNonNull(name);
if (limbs < 0) throw new IllegalArgumentException("Limbs cannot be negative");
this.name = name;
this.limbs = limbs;
this.skinColor = skinColor;
}
}
benefits: No magic defaults -Forces explicit values, validation in one place - Fail fast principle, immutable by design - Thread-safe and predictable
Handling Optional Fields: The Builder Pattern For complex cases (like optional eyeColor), use a Builder:
Human britta = new Human.Builder("Britta", 4)
.skinColor("dark")
.eyeColor("blue")
.build();
Why Builders win: Clear defaults (`.skinColor("dark")` vs. constructor overloading), flexible (Add new fields without breaking changes), readable (Named parameters > positional args)
When Multiple Constructors Make Sense
Simple value objects (e.g., Point(x, y)), framework requirements (JPA/Hibernate no-arg constructor), most classes need just one constructor. Pair it with: factory methods for alternative creation logic and builders for optional parameters
This approach eliminates: hidden defaults, validation duplication and maintenance nightmares Do you prefer single or multiple constructors? Have you been bitten by constructor overload? Share your war stories in the comments!
#Java #CleanCode #OOP #SoftwareDevelopment #Programming
1 note · View note
savageroses-programming · 18 days ago
Text
AFOS BASIC - primitive data types
To start simple I will only adopt four primitive data types.
byte - represented by the byte in JAVA (8bit signed)
integer - represented by the int in JAVA (32bit signed)
float - represented by float in JAVA
string - represented by the string in JAVA
Variable declaration is as follows:
[static] Var [shared] symbolname = expression[, symbolname = expression]
I will try to follow FreeBasic syntax as much as I can. This means datatype is autodetected (as opposed to explicitly declared). FreeBasic uses the Cast keyword to explicitly declare a datatype.
0 notes
spydekkn-blog · 28 days ago
Text
🔰 Starting out in Java? You’ve probably seen this line over and over: public static void main(String[] args) { // your code here } But did you know Java allows several valid variations of the main method? Let’s break it down for clarity! 👇 ✅ 𝑽𝒂𝒍𝒊𝒅 𝒎𝒂𝒊𝒏 𝑴𝒆𝒕𝒉𝒐𝒅 𝑺𝒚𝒏𝒕𝒂𝒙𝒆𝒔: 1️⃣ public static void main(String[] args) → Standard & most widely used 2️⃣ public static void main(String args[]) → Old-school array syntax (still valid) 3️⃣ public static void main(String... args) → Uses varargs — flexible and works the same 4️⃣ public static void main(String[] myCustomName) → Parameter name can be anything! ❌ 𝙄𝙣𝙫𝙖𝙡𝙞𝙙 𝙎𝙮𝙣𝙩𝙖𝙭𝙚𝙨: 🚫 public void main(String[] args) → Missing static 🚫 static void main(String[] args) → Missing public 🚫 public static void main(int[] args) → Wrong parameter type 🔎 The JVM specifically looks for: public static void main(String[] args) 🧠 𝙁𝙪𝙣 𝙁𝙖𝙘𝙩: You can overload the main method, but only the correct one (String[] args) will run by default! 📚 𝗡𝗲𝘄 𝘁𝗼 𝗝𝗮𝘃𝗮? Check out my full beginner-friendly blog post on this topic: 👉 https://wp.me/paNbWh-2l 💬 Got any Java tricks you wish you knew earlier? Drop them below 👇 Let’s grow together. #Java #100DaysOfCode #FullStackDevelopment #CodingJourney #LinkedInLearning #Beginners
0 notes
nllyf · 1 month ago
Text
Optimize Letter Counting in Java Arrays
public class CountLettersInArray { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Declare and create an array 5 char[] chars = createArray(); 6 7 // Display the array 8 System.out.println("The lowercase letters are:"); 9 displayArray(chars); 10 11 // Count the occurrences of each letter 12 int[] counts = countLetters(chars); 13 14 // Display counts 15…
Tumblr media
View On WordPress
0 notes
korshubudemycoursesblog · 1 month ago
Text
Building FullStack E-Commerce App using SpringBoot & React: A Complete Guide
Tumblr media
The rise of digital commerce has made e-commerce development a high-demand skill. Whether you're a backend engineer, frontend developer, or aspiring full-stack professional, learning how to build a full-stack e-commerce app using SpringBoot and React can transform your career opportunities.
This comprehensive guide walks you through the key concepts, architecture, and implementation details required to build a modern, scalable, and responsive e-commerce application. Let’s explore how you can leverage SpringBoot for your backend and React for your frontend to deliver a complete shopping experience.
🔍 Why Choose SpringBoot and React for E-Commerce Development?
SpringBoot and ReactJS are two of the most widely used frameworks in modern web development.
SpringBoot simplifies Java backend development by offering a robust and production-ready environment with minimal configuration.
React empowers developers to build dynamic, high-performance frontends with a component-based architecture.
When combined, these technologies enable you to build a responsive, scalable, and secure full-stack e-commerce platform.
🧠 Key Features of a FullStack E-Commerce Application
Before jumping into the implementation, let’s break down the core features that a well-structured e-commerce app should support:
✅ User Authentication and Authorization (JWT, OAuth)
✅ Product Management (CRUD operations)
✅ Shopping Cart and Wishlist functionality
✅ Order Management
✅ Payment Gateway Integration
✅ Admin Dashboard for Inventory and Orders
✅ Responsive Design for Mobile and Desktop
✅ API-First Development (RESTful APIs)
⚙️ Setting Up the Development Environment
🖥 Backend (SpringBoot)
Technologies Needed:
Java 17+
SpringBoot 3+
Spring Data JPA
Spring Security
Hibernate
MySQL/PostgreSQL
Maven/Gradle
Setup:
Initialize SpringBoot Project via Spring Initializr
Add dependencies: Web, JPA, Security, DevTools
Configure application.yml/application.properties
Set up entity models for User, Product, Order, etc.
💻 Frontend (React)
Technologies Needed:
Node.js & npm
React.js (CRA or Vite)
Redux Toolkit
Axios
React Router
Tailwind CSS or Material UI
Setup:
bash
CopyEdit
npx create-react-app ecommerce-frontend
cd ecommerce-frontend
npm install axios react-router-dom redux-toolkit @reduxjs/toolkit react-redux
📦 Designing the Backend with SpringBoot
📁 Entity Structure
java
CopyEdit
@Entity
public class Product {
   @Id @GeneratedValue
   private Long id;
   private String name;
   private String description;
   private BigDecimal price;
   private String imageUrl;
   private int stockQuantity;
}
You’ll also define entities for User, Order, CartItem, etc., along with their repositories and service layers.
🔐 Authentication with JWT
Use Spring Security and JWT (JSON Web Tokens) for secure login and protected routes.
🌐 RESTful APIs
Create REST endpoints using @RestController to handle:
/api/products
/api/users
/api/orders
/api/auth/login
Use @CrossOrigin to allow frontend access during development.
🌐 Creating the Frontend with React
🧩 Folder Structure
css
CopyEdit
src/
├── components/
├── pages/
├── redux/
├── services/
├── App.js
🛍 Product Display Page
Use Axios to fetch product data from SpringBoot APIs.
jsx
CopyEdit
useEffect(() => {
  axios.get('/api/products').then(res => setProducts(res.data));
}, []);
Render the products in a responsive grid using Tailwind or MUI.
🛒 Shopping Cart with Redux
Manage cart state globally using Redux Toolkit:
javascript
CopyEdit
const cartSlice = createSlice({
  name: 'cart',
  initialState: [],
  reducers: {
    addToCart: (state, action) => { ... },
    removeFromCart: (state, action) => { ... },
  }
});
🔑 User Login
Implement a login form that sends credentials to /api/auth/login and stores JWT in localStorage for authenticated routes.
💳 Integrating Payment Gateway
Integrate a payment solution like Stripe or Razorpay on the frontend.
Use React SDK to collect payment details
Send transaction info to backend to create orders
Store order confirmation in the database
Stripe setup example:
jsx
CopyEdit
const handlePayment = async () => {
  const response = await axios.post('/api/payment', { cart });
  window.location.href = response.data.checkoutUrl;
};
🧾 Building the Admin Panel
Use role-based authentication to restrict access.
Admin Features:
View/Add/Edit/Delete products
Manage orders
Track customer data
Create a separate React route /admin with a dashboard UI using Material UI’s components or Bootstrap.
🛠 Best Practices for FullStack E-Commerce Development
Use DTOs to reduce payload size and protect internal structure.
Enable CORS in SpringBoot to allow frontend access.
Implement Lazy Loading in React for route-based code splitting.
Use React Query or SWR for advanced data fetching if needed.
Apply form validation using Formik + Yup or React Hook Form.
Cache static content (e.g., product images) using a CDN.
Use HTTPS and secure cookies for production environments.
🚀 Deployment Strategy
🧳 Backend:
Use Docker for containerization.
Host on AWS EC2, Heroku, or DigitalOcean.
Use NGINX as reverse proxy.
🧳 Frontend:
Build static files using npm run build.
Host on Netlify, Vercel, or GitHub Pages.
Use environment variables for API URLs.
📊 SEO Optimization for E-Commerce Site
Even for a full-stack developer, basic SEO is crucial. Here’s what to apply:
Use React Helmet to add meta titles and descriptions.
Apply structured data (JSON-LD) for product listings.
Ensure mobile responsiveness and fast load times.
Optimize images and lazy-load them.
Create a sitemap.xml for crawlers.
🎯 Who Should Take a FullStack E-Commerce Approach?
This tech stack is perfect for:
Java developers transitioning to full-stack roles
Frontend devs learning backend architecture
Students building real-world portfolio projects
Freelancers creating scalable client apps
Teams building startup MVPs
🎓 Learn This Stack with a Real Course
Looking for structured learning instead of cobbling it together? Explore a complete Udemy course on building a FullStack E-Commerce App using SpringBoot & React, available on Korshub with a 100% free coupon (limited seats only!).
✅ Conclusion
Building a full-stack e-commerce app with SpringBoot and React is not just about coding—it’s about creating a scalable, secure, and user-centric application. From designing RESTful APIs to integrating Stripe and managing complex state with Redux, you gain a robust skill set that employers and clients seek.
Start building today and take the first step toward becoming a complete full-stack developer.
0 notes