#heap java
Explore tagged Tumblr posts
specindiablog · 1 year ago
Text
Stack vs Heap Java: A Breif Comparison
Tumblr media
When comparing Stack and Heap in Java, it's helpful to think of them in everyday terms. The Stack is like a notepad for Java's temporary notes—quick to write on and read from, but with limited space. It's perfect for keeping track of what's happening right now, like the current page in a book you're reading. However, if you jot down too much without flipping to a new page, you run out of space, which in Java terms, causes a "stack overflow."
On the other hand, the Heap is Java's storage room, spacious enough to hold all the big items, like objects that need to stick around. It's managed by Java's own cleanup crew, the garbage collector, which tidies up by removing objects that are no longer needed. While the Heap offers plenty of space, finding something specific can take a bit longer, similar to searching for a particular toy in a cluttered playroom.
In essence, the Stack is your go-to for quick, short-term storage, while the Heap is where you store things that are larger and need to last longer. The Stack is faster because it's like having what you need within arm's reach, whereas the Heap, with its larger capacity, is a bit slower to access but essential for managing more substantial data. Understanding this balance is key to optimizing Java applications for speed and memory efficiency.
Want to read a detailed comparison? Check the article; Stack vs Heap Java
0 notes
today-i-am-thinking-about · 11 months ago
Text
null pointer exception handling
0 notes
frog707 · 1 year ago
Text
Mystery solved
I believe I've solved the mysterious/scary bug I blogged about yesterday.
Last week I tried to eliminate some repeated code by turning it into "inline" methods that return references to objects. I changed code like this (simplified for clarity):
float getForceX(jlong bodyVa) { Body *pBody = reinterpret_cast<Body *> (bodyVa); const Vec3& result = pBody->GetForce(); return vec3.GetX(); } float getForceY(jlong bodyVa) { Body *pBody = reinterpret_cast<Body *> (bodyVa); const Vec3& result = pBody->GetForce(); return vec3.GetY(); } float getForceZ(jlong bodyVa) { Body *pBody = reinterpret_cast<Body *> (bodyVa); const Vec3& result = pBody->GetForce(); return vec3.GetZ(); }
into code like this (also simplified):
inline const Vec3& getF(jlong bodyVa) { Body *pBody = reinterpret_cast<Body *> (bodyVa); const Vec3& result = pBody->GetForce(); return result; }
float getForceX(jlong bodyVa) { const Vec3& vec3 = getF(bodyVa); return vec3.GetX(); } float getForceY(jlong bodyVa) { const Vec3& vec3 = getF(bodyVa); return vec3.GetY(); } float getForceZ(jlong bodyVa) { const Vec3& vec3 = getF(bodyVa); return vec3.GetZ(); }
In the back of my mind, I assumed Body::GetForce() was returning a reference to a Vec3, so it made sense for getF() to do likewise. But in fact, Body::getForce() returns a copy of a Vec3. Because of this, the compiler allocated stack space for a copy, then returned a reference to that copy. But the copy is only live during execution of getF(). Once the function returns, the copy can (and does) get trashed.
The correct solution, I think, is for getF() to likewise return a copy:
inline static const Vec3 getF(jlong bodyVa) { Body *pBody = reinterpret_cast<Body *> (bodyVa); const Vec3 result = pBody->GetForce(); return result; }
Two little ampersands can make a big difference!
This bug illustrates a couple subtle differences between C++ and Java. In Java, objects are passed and returned by reference, never by copy, so the latter possibility didn't occur to me. Furthermore, Java objects live on a heap, not a stack; as long as a reference lives, objects don't get trashed. Upshot: I'm out of practice thinking about this sort of issue.
Part of what made the bug hard to find was that it only caused failures when optimization was turned on. For various reasons, most of my testing is done with optimization turned off.
I'm not 100% sure how compiler optimization surfaced this bug, but I have some ideas. I could disassemble the compiled code, but I'm not curious enough to do that today.
The interesting question is: how does one solve a bug like this? I wish I'd used some clever tools or techniques, which I could now recommend. In fact, I solved it by trial and error, and my only relevant advice is to be persistent.
0 notes
sandeep2363 · 1 year ago
Text
Dbeaver Java heap space error during SQL Query
How to fix Dbeaver java heap space error while executing SQL Query While executing the SQL Query in Dbeaver, I am getting java heap space error. It occurred due to large tables not able to fetched in Dbeaver heap space. java.lang.OutOfMemoryError: Java heap space Solution: From open the dbeaver shortcut you can add the following line in dbeaver shortcut key: -vmargs -Xmx*m    * -- 2048 or…
View On WordPress
0 notes
anheliotrope · 8 months ago
Text
Rambling About C# Being Alright
I think C# is an alright language. This is one of the highest distinctions I can give to a language.
Warning: This post is verbose and rambly and probably only good at telling you why someone might like C# and not much else.
~~~
There's something I hate about every other language. Worst, there's things I hate about other languages that I know will never get better. Even worse, some of those things ALSO feel like unforced errors.
With C# there's a few things I dislike or that are missing. C#'s feature set does not obviously excel at anything, but it avoids making any huge misstep in things I care about. Nothing in C# makes me feel like the language designer has personally harmed me.
C# is a very tolerable language.
C# is multi-paradigm.
C# is the Full Middle Malcomist language.
C# will try to not hurt you.
A good way to describe C# is "what if Java sucked less". This, of course, already sounds unappealing to many, but that's alright. I'm not trying to gas it up too much here.
C# has sins, but let's try to put them into some context here and perhaps the reason why I'm posting will become more obvious:
C# didn't try to avoid generics and then implement them in a way that is very limiting (cough Go).
C# doesn't hamstring your ability to have statement lambdas because the language designer dislikes them and also because the language designer decided to have semantic whitespace making statement lambdas harder to deal with (cough Python).
C# doesn't require you to explicitly wrap value types into reference types so you can put value types into collections (cough Java).
C# doesn't ruin your ability to interact with memory efficiently because it forbids you from creating custom value types, ergo everything goes to the heap (cough cough Java, Minecraft).
C# doesn't have insane implicit type coercions that have become the subject of language design comedy (cough JavaScript).
C# doesn't keep privacy accessors as a suggestion and has the developers pinkie swear about it instead of actually enforcing it (cough cough Python).
Plainly put, a lot of the time I find C# to be alright by process of elimination. I'm not trying to shit on your favorite language. Everyone has different things they find tolerable. I have the Buddha nature so I wish for all things to find their tolerable language.
I do also think that C# is notable for being a mainstream language (aka not Haskell) that has a smaller amount of egregious mistakes, quirks and Faustian bargains.
The Typerrrrr
C# is statically typed, but the typing is largely effortless to navigate unlike something like Rust, and the GC gives a greater degree of safety than something like C++.
Of course, the typing being easy to work it also makes it less safe than Rust. But this is an appropriate trade-off for certain kinds of applications, especially considering that C# is memory safe by virtue of running on a VM. Don't come at me, I'm a Rust respecter!!
You know how some people talk about Python being amazing for prototyping? That's how I feel about C#. No matter how much time I would dedicate to Python, C# would still be a more productive language for me. The type system would genuinely make me faster for the vast majority of cases. Of course Python has gradual typing now, so any comparison gets more difficult when you consider that. But what I'm trying to say is that I never understood the idea that doing away entirely with static typing is good for fast iteration.
Also yes, C# can be used as a repl. Leave me alone with your repls. Also, while the debugger is active you can also evaluate arbitrary code within the current scope.
I think that going full dynamic typing is a mistake in almost every situation. The fact that C# doesn't do that already puts it above other languages for me. This stance on typing is controversial, but it's my opinion that is really shouldn't be. And the wind has constantly been blowing towards adding gradual typing to dynamic languages.
The modest typing capabilities C# coupled with OOP and inheritance lets you create pretty awful OOP slop. But that's whatever. At work we use inheritance in very few places where it results in neat code reuse, and then it's just mostly interfaces getting implemented.
C#'s typing and generic system is powerful enough to offer you a plethora of super-ergonomic collection transformation methods via the LINQ library. There's a lot of functional-style programming you can do with that. You know, map, filter, reduce, that stuff?
Even if you make a completely new collection type, if it implements IEnumerable<T> it will benefit from LINQ automatically. Every language these days has something like this, but it's so ridiculously easy to use in C#. Coupled with how C# lets you (1) easily define immutable data types, (2) explicitly control access to struct or class members, (3) do pattern matching, you can end up with code that flows really well.
A Friendly Kitchen Sink
Some people have described C#'s feature set as bloated. It is getting some syntactic diversity which makes it a bit harder to read someone else's code. But it doesn't make C# harder to learn, since it takes roughly the same amount of effort to get to a point where you can be effective in it.
Most of the more specific features can be effortlessly ignored. The ones that can't be effortlessly ignored tend to bring something genuinely useful to the language -- such as tuples and destructuring. Tuples have their own syntax, the syntax is pretty intuitive, but the first time you run into it, you will have to do a bit of learning.
C# has an immense amount of small features meant to make the language more ergonomic. They're too numerous to mention and they just keep getting added.
I'd like to draw attention to some features not because they're the most important but rather because it feels like they communicate the "personality" of C#. Not sure what level of detail was appropriate, so feel free to skim.
Stricter Null Handling. If you think not having to explicitly deal with null is the billion dollar mistake, then C# tries to fix a bit of the problem by allowing you to enable a strict context where you have to explicitly tell it that something can be null, otherwise it will assume that the possibility of a reference type being null is an error. It's a bit more complicated than that, but it definitely helps with safety around nullability.
Default Interface Implementation. A problem in C# which drives usage of inheritance is that with just interfaces there is no way to reuse code outside of passing function pointers. A lot of people don't get this and think that inheritance is just used because other people are stupid or something. If you have a couple of methods that would be implemented exactly the same for classes 1 through 99, but somewhat differently for classes 100 through 110, then without inheritance you're fucked. A much better way would be Rust's trait system, but for that to work you need really powerful generics, so it's too different of a path for C# to trod it. Instead what C# did was make it so that you can write an implementation for methods declared in an interface, as long as that implementation only uses members defined in the interface (this makes sense, why would it have access to anything else?). So now you can have a default implementation for the 1 through 99 case and save some of your sanity. Of course, it's not a panacea, if the implementation of the method requires access to the internal state of the 1 through 99 case, default interface implementation won't save you. But it can still make it easier via some techniques I won't get into. The important part is that default interface implementation allows code reuse and reduces reasons to use inheritance.
Performance Optimization. C# has a plethora of features regarding that. Most of which will never be encountered by the average programmer. Examples: (1) stackalloc - forcibly allocate reference types to the stack if you know they won't outlive the current scope. (2) Specialized APIs for avoiding memory allocations in happy paths. (3) Lazy initialization APIs. (4) APIs for dealing with memory more directly that allow high performance when interoping with C/C++ while still keeping a degree of safety.
Fine Control Over Async Runtime. C# lets you write your own... async builder and scheduler? It's a bit esoteric and hard to describe. But basically all the functionality of async/await that does magic under the hood? You can override that magic to do some very specific things that you'll rarely need. Unity3D takes advantage of this in order to allow async/await to work on WASM even though it is a single-threaded environment. It implements a cooperative scheduler so the program doesn't immediately freeze the moment you do await in a single-threaded environment. Most people don't know this capability exists and it doesn't affect them.
Tremendous Amount Of Synchronization Primitives and API. This ones does actually make multithreaded code harder to deal with, but basically C# erred a lot in favor of having many different ways to do multithreading because they wanted to suit different usecases. Most people just deal with idiomatic async/await code, but a very small minority of C# coders deal with locks, atomics, semaphores, mutex, monitors, interlocked, spin waiting etc. They knew they couldn't make this shit safe, so they tried to at least let you have ready-made options for your specific use case, even if it causes some balkanization.
Shortly Begging For Tagged Unions
What I miss from C# is more powerful generic bounds/constraints and tagged unions (or sum types or discriminated unions or type unions or any of the other 5 names this concept has).
The generic constraints you can use in C# are anemic and combined with the lack of tagged unions this is rather painful at times.
I remember seeing Microsoft devs saying they don't see enough of a usecase for tagged unions. I've at times wanted to strangle certain people. These two facts are related to one another.
My stance is that if you think your language doesn't need or benefit from tagged unions, either your language is very weird, or, more likely you're out of your goddamn mind. You are making me do really stupid things every time I need to represent a structure that can EITHER have a value of type A or a value of type B.
But I think C# will eventually get tagged unions. There's a proposal for it here. I would be overjoyed if it got implemented. It seems like it's been getting traction.
Also there was an entire section on unchecked exceptions that I removed because it wasn't interesting enough. Yes, C# could probably have checked exceptions and it didn't and it's a mistake. But ultimately it doesn't seem to have caused any make-or-break in a comparison with Java, which has them. They'd all be better off with returning an Error<T>. Short story is that the consequences of unchecked exceptions have been highly tolerable in practice.
Ecosystem State & FOSSness
C# is better than ever and the tooling ecosystem is better than ever. This is true of almost every language, but I think C# receives a rather high amount of improvements per version. Additionally the FOSS story is at its peak.
Roslyn, the bedrock of the toolchain, the compiler and analysis provider, is under MIT license. The fact that it does analysis as well is important, because this means you can use the wealth of Roslyn analyzers to do linting.
If your FOSS tooling lets you compile but you don't get any checking as you type, then your development experience is wildly substandard.
A lot of stupid crap with cross-platform compilation that used to be confusing or difficult is now rather easy to deal with. It's basically as easy as (1) use NET Core, (2) tell dotnet to build for Linux. These steps take no extra effort and the first step is the default way to write C# these days.
Dotnet is part of the SDK and contains functionality to create NET Core projects and to use other tools to build said projects. Dotnet is published under MIT, because the whole SDK and runtime are published under MIT.
Yes, the debugger situation is still bad -- there's no FOSS option for it, but this is more because nobody cares enough to go and solve it. Jetbrains proved anyone can do it if they have enough development time, since they wrote a debugger from scratch for their proprietary C# IDE Rider.
Where C# falls flat on its face is the "userspace" ecosystem. Plainly put, because C# is a Microsoft product, people with FOSS inclinations have steered clear of it to such a degree that the packages you have available are not even 10% of what packages a Python user has available, for example. People with FOSS inclinations are generally the people who write packages for your language!!
I guess if you really really hate leftpad, you might think this is a small bonus though.
Where-in I talk about Cross-Platform
The biggest thing the ecosystem has been lacking for me is a package, preferably FOSS, for developing cross-platform applications. Even if it's just cross-platform desktop applications.
Like yes, you can build C# to many platforms, no sweat. The same way you can build Rust to many platforms, some sweat. But if you can't show a good GUI on Linux, then it's not practically-speaking cross-platform for that purpose.
Microsoft has repeatedly done GUI stuff that, predictably, only works on Windows. And yes, Linux desktop is like 4%, but that 4% contains >50% of the people who create packages for your language's ecosystem, almost the exact point I made earlier. If a developer runs Linux and they can't have their app run on Linux, they are not going to touch your language with a ten foot pole for that purpose. I think this largely explains why C#'s ecosystem feels stunted.
The thing is, I'm not actually sure how bad or good the situation is, since most people just don't even try using C# for this usecase. There's a general... ecosystem malaise where few care to use the language for this, chiefly because of the tone that Microsoft set a decade ago. It's sad.
HOWEVER.
Avalonia, A New Hope?
Today we have Avalonia. Avalonia is an open-source framework that lets you build cross-platform applications in C#. It's MIT licensed. It will work on Windows, macOS, Linux, iOS, Android and also somehow in the browser. It seems to this by actually drawing pixels via SkiaSharp (or optionally Direct2D on Windows).
They make money by offering migration services from WPF app to Avalonia. Plus general support.
I can't say how good Avalonia is yet. I've researched a bit and it's not obviously bad, which is distinct from being good. But if it's actually good, this would be a holy grail for the ecosystem:
You could use a statically typed language that is productive for this type of software development to create cross-platform applications that have higher performance than the Electron slop. That's valuable!
This possibility warrants a much higher level of enthusiasm than I've seen, especially within the ecosystem itself. This is an ecosystem that was, for a while, entirely landlocked, only able to make Windows desktop applications.
I cannot overstate how important it is for a language's ecosystem to have a package like this and have it be good. Rust is still missing a good option. Gnome is unpleasant to use and buggy. Falling back to using Electron while writing Rust just seems like a bad joke. A lot of the Rust crates that are neither Electron nor Gnome tend to be really really undercooked.
And now I've actually talked myself into checking out Avalonia... I mean after writing all of that I feel like a charlatan for not having investigated it already.
72 notes · View notes
vatt-world · 9 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
bfitgroup · 1 month ago
Text
Tips For Cracking Amazon, Google, And Microsoft Interviews
Tumblr media
A large portion of youths nurtures a dream of cracking an interview at the tech giants of the world, such as Amazon, Google, and Microsoft, and securing a job there. Do you know the reason behind it? Well, there are a number of reasons that support this and allure the youths towards it, such as career and overall growth, earning potential, work-life balance, salability, effective office culture, availability of innovative technology, and many more.
All these advantages together support the individuals to appear in front of these companies’ hiring team and crack Amazon, Google, and Microsoft interviews. So do you belong to such an area of population who have the same dream? If so, then look at the information given in this blog to know how to crack the interview and secure a dream job there.
Prepare For FAANG Interviews: Follow These Steps For A Successful Hiring
A notice for hiring invites a number of candidates and fills them with an urge to apply for an interview. But things become difficult when it comes to preparing for the interview because with it a lot of stress and confusion come along the way and make it hard to choose the right thing to bring ease. To help you in the preparation, we have mentioned some of the effective strategies that you can follow and prepare for FAANG interviews.
Prepare Technical Aspects
One of the important steps to follow in order to master the strategy of clearing the interview is to prepare the technical aspects, such as data structures and algorithms. Keep a good command of linked lists, arrays, heaps, queues, hash maps, trees, strings, stacks, and graphs. Along with this, keep focus on graph traversal, sorting, sliding window, searching, backtracking, recursion, and dynamic programming. Using LeetCode, Codeforces, InterviewBit, and HackerRank are also good for practice. At last, do practice by solving various kinds of problems.
Learn System Design
It is also very crucial to learn system designs if you are applying for mid or senior-level roles. In order to do so, first start with basics such as sharding, load balancing, CAP theorem, caching, and consistency models. Along with this, you can learn designs such as scalable storage, recommendation systems, URL shortener, and chat apps to enhance the chances of selection. Do not avoid it as it is one of the most crucial tech interview tips for top companies that you can practice before facing the interview panel.
Keep The Command On Low-level Design
Have a good practice of object relationships, class diagrams, and design patterns. Coupled with this, you can also practice use cases such as parking lots, elevator systems, and book readers. This is one of the important tech interview tips for top companies that you should not miss out on anyhow.
Own A Language Perfectly
It is very important to have a good knowledge of any one programming language to crack Amazon, Google, Microsoft interviews, such as Python, C++, Java….
To read more, Visit: https://bfitgroup.in/tips-for-cracking-amazon-google-microsoft-interviews/
0 notes
java-highlight · 1 month ago
Text
Kiểu Dữ Liệu Trong Java - Phân Loại & Ví Dụ
Kiểu dữ liệu trong Java là một khái niệm nền tảng mà bất kỳ lập trình viên nào cũng cần nắm vững khi học và làm việc với ngôn ngữ lập trình Java. Kiểu dữ liệu xác định loại giá trị mà một biến có thể lưu trữ, cách nó được lưu trữ trong bộ nhớ và các thao tác có thể thực hiện trên biến đó. Trong bài viết này, chúng ta sẽ tìm hiểu chi tiết về các loại kiểu dữ liệu trong Java, cách phân loại chúng, ví dụ minh họa cụ thể.
Kiểu Dữ Liệu Trong Java Là Gì?
Kiểu dữ liệu trong Java là tập hợp các quy tắc xác định loại giá trị mà một biến có thể ch��a, chẳng hạn như số nguyên, số thực, chuỗi ký tự hay các đối tượng phức tạp. Java là một ngôn ngữ lập trình hướng đối tượng và có tính kiểm tra kiểu dữ liệu chặt chẽ (strongly typed), nghĩa là bạn phải khai báo rõ ràng kiểu dữ liệu của biến trước khi sử dụng.
Java chia kiểu dữ liệu thành hai loại chính:
Kiểu dữ liệu nguyên thủy (Primitive Data Types): Các kiểu dữ liệu cơ bản, không phải đối tượng.
Kiểu dữ liệu tham chiếu (Reference Data Types): Các kiểu dữ liệu phức tạp hơn, chẳng hạn như đối tượng hoặc mảng.
Tumblr media
Ảnh mô tả hệ thống các kiểu dữ liệu trong Java
1. Kiểu Dữ Liệu Nguyên Thủy (Primitive Data Types)
Kiểu dữ liệu nguyên thủy là các kiểu dữ liệu cơ bản được định nghĩa sẵn trong Java. Chúng không phải là đối tượng và lưu trữ trực tiếp giá trị trong bộ nhớ. Có 8 kiểu dữ liệu nguyên thủy trong Java, bao gồm:
1.1. Kiểu số nguyên (Integer Types)
byte: Kích thước 1 byte, lưu trữ số nguyên từ -128 đến 127.
short: Kích thước 2 byte, lưu trữ số nguyên từ -32,768 đến 32,767.
int: Kích thước 4 byte, lưu trữ số nguyên từ -2^31 đến 2^31-1.
long: Kích thước 8 byte, lưu trữ số nguyên từ -2^63 đến 2^63-1.
Ví dụ:
int age = 25;
long population = 8000000000L;
1.2. Kiểu số thực (Floating-Point Types)
float: Kích thước 4 byte, lưu trữ số thực với độ chính xác đơn.
double: Kích thước 8 byte, lưu trữ số thực với độ chính xác kép.
Ví dụ:
double pi = 3.14159;
float temperature = 36.6f;
1.3. Kiểu ký tự (Character Type)
char: Kích thước 2 byte, lưu trữ một ký tự Unicode.
Ví dụ: char letter = 'A';
1.4. Kiểu logic (Boolean Type)
boolean: Lưu trữ hai giá trị true hoặc false.
Ví dụ: boolean is Student = true;
Tumblr media
Bảng tóm tắt kiểu dữ liệu nguyên thủy
2. Kiểu Dữ Liệu Tham Chiếu (Reference Data Types)
Kiểu dữ liệu tham chiếu lưu trữ tham chiếu (địa chỉ) đến dữ liệu thay vì giá trị thực tế. Các kiểu này bao gồm:
Lớp (Class): Các đối tượng được tạo từ lớp, chẳng hạn như String, Scanner.
Giao diện (Interface): Các giao diện như List, Map.
Mảng (Array): Tập hợp các phần tử cùng kiểu dữ liệu.
Chuỗi (String): Một kiểu đặc biệt dùng để lưu trữ chuỗi ký tự.
Ví dụ:
String name = "Nguyen Van A";
int[] numbers = {1, 2, 3, 4, 5};
Đặc điểm của kiểu dữ liệu tham chiếu:
Có thể là null (không tham chiếu đến đối tượng nào).
Được lưu trữ trong Heap Memory và quản lý bởi Garbage Collector.
Hỗ trợ các phương thức và thuộc tính của đối tượng.
Tumblr media
Heap Memory và Stack Memory
Khi Nào Nên Sử Dụng Kiểu Dữ Liệu Nào?
Sử dụng kiểu dữ liệu nguyên thủy khi cần lưu trữ các giá trị đơn giản như số, ký tự hoặc giá trị logic để tối ưu hóa hiệu suất.
Sử dụng kiểu dữ liệu tham chiếu khi làm việc với các đối tượng phức tạp, chuỗi hoặc mảng.
Ví dụ thực tế:
public class Example {
public static void main(String[] args) {
// Kiểu dữ liệu nguyên thủy
int age = 30;
double salary = 50000.75;
boolean isEmployed = true;
// Kiểu dữ liệu tham chiếu
String employeeName = "Tran Thi B";
int[] workingDays = {20, 22, 21};
System.out.println("Name: " + employeeName + ", Age: " + age + ", Salary: " + salary);
}
}
Tumblr media
Mã nguồn ví dụ
Mẹo Tối Ưu Khi Làm Việc Với Kiểu Dữ Liệu Trong Java
Chọn kiểu dữ liệu phù hợp: Sử dụng byte hoặc short thay cho int nếu giá trị nhỏ để tiết kiệm bộ nhớ.
Hiểu rõ phạm vi giá trị: Tránh lỗi tràn số (overflow) khi làm việc với int hoặc long.
Sử dụng StringBuilder cho chuỗi lớn: Thay vì dùng String để nối chuỗi nhiều lần.
Kiểm tra null: Với kiểu dữ liệu tham chiếu, luôn kiểm tra giá trị null để tránh lỗi NullPointerException.
Kết Luận
Hiểu rõ kiểu dữ liệu trong Java là bước đầu tiên để viết mã hiệu quả và tránh lỗi không mong muốn. Kiểu dữ liệu nguyên thủy phù hợp với các giá trị đơn giản, trong khi kiểu dữ liệu tham chiếu cần thiết cho các đối tượng phức tạp. Hy vọng bài viết này đã cung cấp cho bạn cái nhìn tổng quan và những ví dụ thực tế để áp dụng trong lập trình Java.
Nếu bạn muốn tìm hiểu sâu hơn về kiểu dữ liệu hoặc các chủ đề khác trong Java, hãy để lại câu hỏi hoặc theo dõi các bài viết tiếp theo của chúng tôi!
Kiểu Dữ Liệu Trong Java – Phân Loại & Ví Dụ Dễ Hiểu Tìm hiểu các kiểu dữ liệu cơ bản và tham chiếu trong Java. Bao gồm ví dụ minh hoạ rõ ràng giúp bạn học nhanh và nhớ lâu! 🌍 Website: Java Highlight
0 notes
fromdevcom · 1 month ago
Text
The current trend followed by most of the mobile app users and tech freaks are everyone stays connected and in sync with technology by keeping a check on their emails and all their other web content on their gadgets at regular intervals. Mobile app development is the hottest trend currently and all the apps should be equipped with necessary mobile app testing tools to ensure they don’t crash mid usage. Thus, to combat mobile app traffic and also to keep the app successfully running, a very important part of the mobile app development process includes performance testing for app. Mobile app developers and quality analysts use various mobile app testing and web app testing tools to ensure the apps function smoothly and in a stable manner. The consistency, stability and ultimately the user experience of the app depends on how well the tech consultants perform the mobile app testing and web app testing. Here’s a roundup of the 3 best performance tools all developers and testers swear by : Tool Evaluation With the augmenting of its degree it has been as of late utilized broadly to test the useful execution of the frameworks under various conditions. This device has the ability to be stacked into any server or system making it a flexible device. It is of awesome use in testing the useful execution of the assets, for example, Servlets, Perl Scripts and JAVA objects. To whole up, it is the best alternative for web application load testing, regardless of on which stage it keeps running on. This heap and stretch testing instrument is to quantify the execution of the mobile application and the web application and afterward give reasonable arrangements encouraging outline and advancement of the upgraded application. Created by a French organization named as Neotys, it is good on working frameworks like Microsoft windows, Linux and Solaris. This apparatus concentrates on the execution of the applications by heightening the activity to the site and afterward the execution under overwhelming burden is resolved. WebLOAD WebLOAD gives you a chance to perform load and stretch testing on any web application utilizing Ajax, Adobe Flex, .NET, Oracle Forms, HTML5 and numerous more innovations. You can create stack from the cloud and on-premises machines. WebLOAD's qualities are its convenience with components like DOM-based recording/playback, programmed connection and JavaScript scripting dialect. The instrument underpins extensive scale execution testing with substantial client burden and complex situations, and gives clear examination on the usefulness and execution of the web application. WebLOAD has 3500 clients worldwide and has won different recompenses. Another highlight of the device is its adaptable authorizing instrument and valuing. Rational Performance Tester The Rational execution analyzer is a mechanized execution testing instrument which can be utilized for a web application or a server based application where there is a procedure of information and yield is included. This apparatus makes a demo of the first exchange process between the client and the web administration. Before the end of everything the measurable data are accumulated and they are examined to build the proficiency. Any spillage in the site or the server can be distinguished and amended instantly with the assistance of this apparatus. This apparatus can be the best choice in building a compelling and mistake free distributed computing administration. This Rational Performance analyzer was created by IBM (Rational programming division). They have concocted numerous renditions of this robotized testing apparatus. Ritesh Patil is the co-founder of Mobisoft Infotech that helps startups and enterprises in mobile technology. He loves technology, especially mobile technology. He’s an avid blogger and writes on mobile application. He works in an iPhone app development company.
0 notes
codezup · 2 months ago
Text
Optimize Java Memory Usage: Effective Heap Management Strategies
1. Introduction Understanding the Importance Optimizing Java memory usage is crucial for building efficient and scalable applications. The heap, a critical component of Java’s memory model, is where objects are stored. Effective heap management prevents issues like OutOfMemoryError, improves performance, and enhances user experience. What You’ll Learn This tutorial covers strategies to…
0 notes
hackernewsrobot · 2 months ago
Text
How ZGC allocates memory for the Java heap
https://joelsiks.com/posts/zgc-heap-memory-allocation/
0 notes
praveennareshit · 3 months ago
Text
Must-Know Core Java Concepts for Every Programmer
(A Guide for Full Stack Software Testing Enthusiasts in KPHB)
Java remains the backbone of enterprise applications, and a strong grasp of its core concepts is essential for every programmer. Whether you are an aspiring software tester, a backend developer, or a full-stack engineer, understanding Java fundamentals is non-negotiable. Let’s break down the most crucial Java concepts that you must master.
Tumblr media
1. Object-Oriented Programming (OOP)
Java is inherently object-oriented, which means everything revolves around objects and classes. The four key pillars of OOP in Java are:
✔ Encapsulation – Bundling data and methods together to protect data integrity. ✔ Abstraction – Hiding implementation details and exposing only what’s necessary. ✔ Inheritance – Allowing one class to derive properties from another. ✔ Polymorphism – Enabling multiple implementations of a method.
Why It Matters?
For software testers, understanding OOP principles helps in creating reusable and scalable test automation frameworks.
2. Java Memory Management
Memory management is a crucial aspect that determines the performance of Java applications. It consists of:
✔ Heap & Stack Memory – Heap stores objects, while Stack holds method calls and local variables. ✔ Garbage Collection (GC) – Java has an automatic garbage collector that frees up memory by removing unused objects.
Why It Matters?
Full Stack Testers must understand memory leaks and performance bottlenecks in Java-based applications.
3. Exception Handling
Exception handling ensures that runtime errors don’t crash the application. Java provides:
✔ try-catch-finally – Handles exceptions and ensures resource cleanup. ✔ throws & throw – Used for explicitly handling custom exceptions. ✔ Checked vs. Unchecked Exceptions – Checked exceptions (like IOException) must be handled, while unchecked exceptions (like NullPointerException) occur at runtime.
Why It Matters?
Testers need to handle exceptions effectively in automation scripts to avoid script failures.
4. Multithreading & Concurrency
Multithreading allows multiple parts of a program to run simultaneously. Important concepts include:
✔ Thread Lifecycle – From creation to termination. ✔ Runnable & Callable Interfaces – Implementing threads in Java. ✔ Synchronization & Locks – Avoiding race conditions and ensuring thread safety.
Why It Matters?
In performance testing, understanding multithreading helps simulate real-world user load.
5. Collections Framework
Java provides a robust Collections Framework for handling groups of objects efficiently. The key interfaces are:
✔ List (ArrayList, LinkedList) – Ordered and allows duplicates. ✔ Set (HashSet, TreeSet) – Unordered and doesn’t allow duplicates. ✔ Map (HashMap, TreeMap) – Stores key-value pairs.
Why It Matters?
Test automation frameworks use collections extensively for data handling and assertions.
6. File Handling & I/O Operations
File handling is critical for reading, writing, and manipulating files in Java.
✔ BufferedReader & BufferedWriter – Efficient file reading and writing. ✔ FileInputStream & FileOutputStream – Handling binary data. ✔ Serialization – Converting objects into byte streams.
Why It Matters?
For automation testers, handling logs, reports, and configuration files is a routine task.
7. JDBC & Database Connectivity
Java Database Connectivity (JDBC) allows applications to interact with databases.
✔ DriverManager – Manages database connections. ✔ PreparedStatement – Prevents SQL injection. ✔ ResultSet – Retrieves query results.
Why It Matters?
Full Stack Testers should understand JDBC for validating database operations in automation scripts.
8. Java Frameworks
Mastering Java alone isn’t enough; knowing key frameworks is essential.
✔ Spring Boot – Microservices and dependency injection. ✔ Selenium with Java – Web automation testing. ✔ TestNG & JUnit – Test automation frameworks.
Why It Matters?
These frameworks power large-scale software applications and automation testing.
Frequently Asked Questions (FAQ)
Q1: What is the best way to practice Core Java concepts? A: Work on small projects, participate in coding challenges, and contribute to open-source repositories.
Q2: How is Java used in Full Stack Software Testing? A: Java is used for writing test automation scripts, interacting with databases, and integrating test frameworks.
Q3: What is the difference between Checked and Unchecked Exceptions? A: Checked exceptions must be handled (e.g., IOException), whereas unchecked exceptions occur at runtime (e.g., NullPointerException).
Q4: Why is Java preferred for automation testing? A: Java offers robust libraries like Selenium, TestNG, and JUnit, making automation testing efficient and scalable.
Q5: What are the key Java concepts needed for API Testing? A: Understanding HTTP methods, JSON parsing, and REST API calls using libraries like RestAssured and Jackson is crucial.
Final Thoughts
Mastering Java fundamentals is the key to excelling in software development and automation testing. Whether you are preparing for a Full Stack Software Testing role in KPHB or looking to enhance your coding skills, these core Java concepts will set you apart.
0 notes
learning-code-ficusoft · 4 months ago
Text
Understanding the Java Virtual Machine (JVM): Internals and Optimization
Tumblr media
Introduction
Briefly introduce the JVM and its role in running Java applications.
Highlight why understanding JVM internals is crucial for developers.
Mention key aspects like performance, memory management, and optimizations.
1. JVM Architecture: An Overview
Explain how JVM acts as an abstraction layer between Java code and the underlying hardware.
Key components:
Class Loader: Loads bytecode into memory.
Runtime Memory Areas: Heap, Stack, Method Area, etc.
Execution Engine: Converts bytecode into native code.
Garbage Collector (GC): Manages memory automatically.
2. JVM Memory Management
Heap vs. Stack Memory: What each is used for.
Method Area & Runtime Constant Pool: Storage for metadata and constants.
Garbage Collection (GC) Mechanisms:
Serial, Parallel, CMS, G1, and ZGC collectors.
When and how GC runs.
Tuning GC for performance (using JVM options like -XX:+UseG1GC).
3. Just-In-Time (JIT) Compilation
How JIT compiles frequently used bytecode into native machine code for performance.
Difference between:
Interpreter Mode (slower execution but quick startup).
JIT Compilation (optimizes hot code paths).
JVM optimizations like:
Method Inlining
Loop Unrolling
Escape Analysis
4. JVM Optimization Techniques
Tuning JVM with Command-line Flags
-Xms and -Xmx for memory allocation.
-XX:+PrintGCDetails for monitoring GC.
Profiling and Monitoring Tools
JVisualVM, JConsole, Java Flight Recorder.
Code-level Optimizations
Reducing object creation to avoid excessive GC.
Using efficient data structures (ArrayList vs. LinkedList).
Avoiding memory leaks (proper use of WeakReferences, ThreadLocal).
5. JVM Performance Best Practices
Selecting the right GC algorithm for different workloads.
Analyzing JVM logs to detect performance bottlenecks.
Using Ahead-of-Time (AOT) Compilation (like GraalVM) for even faster execution.
Conclusion
Summarize key takeaways: JVM architecture, memory management, JIT compilation, and optimizations.
Emphasize the importance of tuning JVM settings for different applications.
WEBSITE: https://www.ficusoft.in/core-java-training-in-chennai/
0 notes
atplblog · 5 months ago
Text
Price: [price_with_discount] (as of [price_update_date] - Details) [ad_1] Introduction to Java Programming and Data Structures seamlessly integrates programming, data structures, and algorithms into one text. With a fundamentals-first approach, the text builds a strong foundation of basic programming concepts and techniques before teaching students object-oriented programming and advanced Java programming. Liang explains programming in a problem-driven way that focuses on problem solving rather than syntax, illustrating basic concepts by example and providing a large number of exercises with various levels of difficulty for students to practice. The 12th Edition is completely revised in every detail to enhance clarity, presentation, content, examples, and exercises.Features –NEW: Both Comparable and Comparator are used to compare elements in Heap, Priority-Queue, BST, and AVLTree. This is consistent with the Java API and is more useful and flexible. NEW: String matching algorithms are introduced in Chapter 22: Developing Efficient Algorithms. UPDATED: Java 9, 10, 11 and FX11 are covered to keep the text up to date with current technologies. Examples are improved and simplified. UPDATED: Lambda expressions are used in more examples and exercises in the data structures chapters to simplify coding. UPDATED: Programming Exercises are grouped by sections to provide students with opportunities to apply the new skills they have learned on their own. From the brand Publisher ‏ : ‎ Pearson Education (15 April 2024); Pearson Education Language ‏ : ‎ English Paperback ‏ : ‎ 1240 pages ISBN-10 ‏ : ‎ 9357055045 ISBN-13 ‏ : ‎ 978-9357055048 Reading age ‏ : ‎ 16 years and up Item Weight
‏ : ‎ 1 kg 850 g Dimensions ‏ : ‎ 25.4 x 20.5 x 4.8 cm Net Quantity ‏ : ‎ 1 Piece Importer ‏ : ‎ Pearson Education Packer ‏ : ‎ Pearson Education Generic Name ‏ : ‎ Textbook [ad_2]
0 notes
sunbeaminfo · 6 months ago
Text
Enhance Your Coding Skills with Data Structures and Algorithms Classes at Sunbeam Institute, Pune
Elevate your programming expertise by enrolling in the Data Structures and Algorithms course at Sunbeam Institute, Pune. This comprehensive program is designed for students, freshers, and working professionals aiming to deepen their understanding of essential data structures and algorithms using Java.
Course Highlights:
Algorithm Analysis: Learn to evaluate time and space complexity for efficient coding.
Linked Lists: Master various types, including singly, doubly, and circular linked lists.
Stacks and Queues: Understand their implementation using arrays and linked lists, and apply them in expression evaluation and parenthesis balancing.
Sorting and Searching: Gain proficiency in algorithms like Quick Sort, Merge Sort, Heap Sort, Linear Search, Binary Search, and Hashing.
Trees and Graphs: Explore tree traversals, Binary Search Trees (BST), and graph algorithms such as Prim’s MST, Kruskal’s MST, Dijkstra's, and A* search.
Course Details:
Duration: 60 hours
Schedule: Weekdays (Monday to Saturday), 5:00 PM to 8:00 PM
Upcoming Batch: January 27, 2025, to February 18, 2025
Fees: ₹7,500 (including 18% GST)
Prerequisites:
Basic knowledge of Java programming, including classes, objects, generics, and Java collections (e.g., ArrayList).
Why Choose Sunbeam Institute?
Sunbeam Institute is renowned for its effective IT training programs in Pune, offering a blend of theoretical knowledge and practical application to ensure a thorough understanding of complex concepts.
Enroll Now: Secure your spot in this sought-after course to advance your programming skills and enhance your career prospects. For registration and more information, visit:
0 notes
fromdevcom · 3 months ago
Text
Java Mastery Challenge: Can You Crack These 10 Essential Coding Questions? Are you confident in your Java programming skills? Whether you're preparing for a technical interview or simply want to validate your expertise, these ten carefully curated Java questions will test your understanding of core concepts and common pitfalls. Let's dive into challenges that every serious Java developer should be able to tackle. 1. The Mysterious Output Consider this seemingly simple code snippet: javaCopypublic class StringTest public static void main(String[] args) String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); System.out.println(str1 == str2); System.out.println(str1 == str3); System.out.println(str1.equals(str3)); What's the output? This question tests your understanding of string pooling and object reference comparison in Java. The answer is true, false, true. The first comparison returns true because both str1 and str2 reference the same string literal from the string pool. The second comparison returns false because str3 creates a new object in heap memory. The third comparison returns true because equals() compares the actual string content. 2. Threading Troubles Here's a classic multithreading puzzle: javaCopypublic class Counter private int count = 0; public void increment() count++; public int getCount() return count; If multiple threads access this Counter class simultaneously, what potential issues might arise? This scenario highlights the importance of thread safety in Java applications. Without proper synchronization, the increment operation isn't atomic, potentially leading to race conditions. The solution involves either using synchronized methods, volatile variables, or atomic classes like AtomicInteger. 3. Collection Conundrum javaCopyList list = new ArrayList(); list.add("Java"); list.add("Python"); list.add("JavaScript"); for(String language : list) if(language.startsWith("J")) list.remove(language); What happens when you run this code? This question tests your knowledge of concurrent modification exceptions and proper collection iteration. The code will throw a ConcurrentModificationException because you're modifying the collection while iterating over it. Instead, you should use an Iterator or collect items to remove in a separate list. 4. Inheritance Insight javaCopyclass Parent public void display() System.out.println("Parent"); class Child extends Parent public void display() System.out.println("Child"); public class Main public static void main(String[] args) Parent p = new Child(); p.display(); What's the output? This tests your understanding of method overriding and runtime polymorphism. The answer is "Child" because Java uses dynamic method dispatch to determine which method to call at runtime based on the actual object type, not the reference type. 5. Exception Excellence javaCopypublic class ExceptionTest public static void main(String[] args) try throw new RuntimeException(); catch (Exception e) throw new RuntimeException(); finally System.out.println("Finally"); What gets printed before the program terminates? This tests your knowledge of exception handling and the finally block. "Finally" will be printed because the finally block always executes, even when exceptions are thrown in both try and catch blocks. 6. Interface Implementation javaCopyinterface Printable default void print() System.out.println("Printable"); interface Showable default void print() System.out.println("Showable"); class Display implements Printable, Showable // What needs to be added here? What must be
added to the Display class to make it compile? This tests your understanding of the diamond problem in Java 8+ with default methods. The class must override the print() method to resolve the ambiguity between the two default implementations. 7. Generics Genius javaCopypublic class Box private T value; public void setValue(T value) this.value = value; public T getValue() return value; Which of these statements will compile? javaCopyBox intBox = new Box(); Box strBox = new Box(); Box doubleBox = new Box(); This tests your understanding of bounded type parameters in generics. Only intBox and doubleBox will compile because T is bounded to Number and its subclasses. String isn't a subclass of Number, so strBox won't compile. 8. Memory Management javaCopyclass Resource public void process() System.out.println("Processing"); protected void finalize() System.out.println("Finalizing"); What's wrong with relying on finalize() for resource cleanup? This tests your knowledge of Java's memory management and best practices. The finalize() method is deprecated and unreliable for resource cleanup. Instead, use try-with-resources or implement AutoCloseable interface for proper resource management. 9. Lambda Logic javaCopyList numbers = Arrays.asList(1, 2, 3, 4, 5); numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * 2) .forEach(System.out::println); What's the output? This tests your understanding of Java streams and lambda expressions. The code filters even numbers, doubles them, and prints them. The output will be 4 and 8. 10. Serialization Scenarios javaCopyclass User implements Serializable private String username; private transient String password; // Constructor and getters/setters What happens to the password field during serialization and deserialization? This tests your knowledge of Java serialization. The password field, marked as transient, will not be serialized. After deserialization, it will be initialized to its default value (null for String). Conclusion How many questions did you get right? These problems cover fundamental Java concepts that every developer should understand. They highlight important aspects of the language, from basic string handling to advanced topics like threading and serialization. Remember, knowing these concepts isn't just about passing interviews – it's about writing better, more efficient code. Keep practicing and exploring Java's rich features to become a more proficient developer. Whether you're a beginner or an experienced developer, regular practice with such questions helps reinforce your understanding and keeps you sharp. Consider creating your own variations of these problems to deepen your knowledge even further. What's your next step? Try implementing these concepts in your projects, or create more complex scenarios to challenge yourself. The journey to Java mastery is ongoing, and every challenge you tackle makes you a better programmer.
0 notes