#convert string to int java
Explore tagged Tumblr posts
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.
#how to convert string to int in java#how to convert string to int in java example#how to convert a string to int in java#how to convert string to integer in java#convert string to int java#convert string to int in java#how can convert string to int in java#how to convert a string to integer in java#convert int to string in java#string to integer in java#java convert string to int#convert string to int#how to convert integer to string in java#string to int java
1 note
·
View note
Text
Dynamically vs Statically-Typed Programming Languages
Hiya!🌍💻 I know I haven't done one of these posts in a while but now I came up with a new topic to talk about!
Today, we're going to dive into the world of programming languages and explore the differences between dynamically-typed and statically-typed ones. I actually got the idea from explaining the whole difference between languages such as C# and Java to Lua and Python! Also just wanted to talk about how various languages handle data types~! So, buckle up, and let's get started~! 🚀
The Main Difference
It all lies in how they handle data types:
In a dynamically-typed language, the type of a variable is determined at runtime, which means you don't have to specify the type explicitly when declaring a variable.
In a statically-typed language, the type of a variable is determined at compile-time, and you must declare the type explicitly when defining a variable.
Example Code
Not getting the picture of what I'm talking about? No worries, let's take a look at some code examples to illustrate the difference. I'll use my beloved Lua (a dynamically-typed language) and C# (a statically-typed language)~!
Lua
C#
In the Lua example, we can see that we don't need to specify the data type of the variable x. We can even change its type later in the code and it would still work!
In the C# example, we must specify the data type of x when declaring it, and attempting to change its type later will result in a compile-time error. Remember though, you can convert an int to string in C# via 'Convert.ToString()'!
Recap!
In dynamically-typed language, the type of a variable is determined at runtime.
Lua, Python, and JavaScript are programming languages that are dynamically typed.
In a statically-typed language, the type of a variable is determined at compile-time.
C#, Java, and Go are programming languages that are statically typed.
Obviously, there is more to know about each type as dynamically-typed and statically-typed languages each have their advantages and disadvantages - but I wanted to focus more on the data type declaration part~!
Here are some further reading pages:
Dynamic Typing vs Static Typing - LINK
Advantages and Disadvantages of Dynamic and Static Typing - LINK
That's all, thanks for reading, and hope you learned something new! Happy coding, folks~! 🌟💻🚀
#xc: programming blog post#coding#programming#studying#studyblr#codeblr#progblr#computer science#project#tech#developer#web dev#comp sci#learn how to code
83 notes
·
View notes
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
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
Text
j
Swing is not thread-safe. Updating UI components from background threads (not the Event Dispatch Thread) causes race conditions, freezes, or crashes.
Use SwingUtilities.invokeLater() or SwingWorker to handle background tasks safely.
Component Overlap or Z-order Issues Components might overlap or not render correctly if layout and repainting aren’t managed properly.
revalidate() and repaint() are often needed after dynamic UI changes.
Scaling and DPI Conflicts On high-DPI displays, Swing apps can look blurry or improperly scaled if not configured.
Java 9+ supports HiDPI better, but older setups require workarounds.
Architecture Conflicts Mixing UI logic with business logic leads to spaghetti code and maintenance problems.
Not following patterns like MVC or separating concerns can make the design fragile.
Event Handling Conflicts Multiple listeners acting on the same component or event can cause logic errors.
Improper handling of key bindings or focus can result in unresponsive controls. // Updating a JTable in Java Swing can be done in a few different ways Using a DefaultTableModel (most common way)
Access the model:DefaultTableModel model = (DefaultTableModel) table.getModel(); Refreshing the UI If you're updating the model directly, the JTable usually updates automatically. But if needed:
java model.fireTableDataChanged();
// If you update the JTable (or any Swing component) from a non-EDT thread, you risk:
UI glitches
Random exceptions
Unpredictable behavior
The Fix: Use SwingUtilities.invokeLater() // Always wrap the JTable in a JScrollPane to handle large datasets.
Use BorderLayout.CENTER to make it fill the frame.
This design makes JTable the main UI element—perfect for apps like:
Inventory systems
Admin dashboards
// Custom Cell Rendering (How Data is Displayed) To change how a cell looks, implement a custom TableCellRenderer.
// Make Only Certain Columns Editable Override isCellEditable() in your model:
java Copy Edit DefaultTableModel model = new DefaultTableModel(data, columnNames) { @Override public boolean isCellEditable(int row, int column) {
//
Custom Cell Editors (How Data is Edited) To control how a user edits a cell, use a TableCellEditor.
Example: Use a combo box editor for a column java
String[] roles = {"Developer", "Designer", "Manager"}; JComboBox comboBox = new JComboBox<>(roles);
table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor // Format Displayed Values You can convert raw data (like timestamps, enums, booleans) into human-readable text using renderers or by overriding getValueAt() in a custom TableModel.
//
GridLayout Divides space into equal-sized rows and columns.
java
BoxLayout Aligns components vertically or horizontally.
GridBagLayout Most flexible, but also the most complex.
Allows fine-grained control over row/column span, alignment, padding. //
Optimized event-driven programming for efficient user interactions and system performance.
Implemented MVC architecture to ensure scalability and maintainability of Java Swing applications.
Enhanced multithreading in Swing applications to improve responsiveness using SwingWorker.
Debugged and resolved UI rendering issues, ensuring cross-platform compatibility.
Worked with Look and Feel (LAF) customization for a modern and branded UI experience.
//
ava Swing Application Works JFrame (Main Window) – The base container that holds all UI components.
JPanel (Layout Container) – Used to organize components inside the frame.
Swing Components – Buttons (JButton), labels (JLabel), text fields (JTextField), tables (JTable), etc.
Event Handling – Listeners (like ActionListener) handle user interactions.
Threading (SwingWorker) – Ensures UI remains responsive during background tasks.
Example Use Cases Point of Sale (POS) Systems – Cashier interfaces for processing transactions.
Inventory Management – Applications for tracking stock levels.
Data Entry Forms – GUI forms for database input and management.
Media Players – Applications for playing audio/video with Swing UI.\
JFrame Main application window JPanel Container for organizing UI elements JButton Clickable button JLabel Display text or images JTextField Single-line input field JTextArea Multi-line text input JTable Displays tabular data JMenuBar Menu bar with dropdown menus JList List of selectable items
.. //
Use of Modern Look and Feel (LAF) FlatLaf – A modern, flat UI theme for Swing that provides a better-looking UI.
Improved Concurrency with CompletableFuture Handles long-running tasks without freezing the UI.
Example:
java
CompletableFuture.supplyAsync(() -> fetchData()) .thenAccept(data -> SwingUtilities.invokeLater(() -> label.setText(data)));
// Use a Layout Manager Java Swing provides various layout managers like:
BorderLayout – Divides the window into 5 regions (North, South, East, West, Center).
GridBagLayout – Flexible and customizable grid-based layout.
BoxLayout – Arranges components in a single row or column.
GroupLayout – Best for complex resizable designs (used in NetBeans GUI Builder).
Use JScrollPane to make JTable scrollable ✔ Use DefaultTableModel for editing rows ✔ Add event listeners to detect row selection ✔ Integrate with a database using JDBC
Performance Issues in JTable & How to Optimize When dealing with large datasets in JTable, performance can degrade due to factors like slow rendering, inefficient data models, excessive event handling, Large Dataset Causes UI Lag Issue: If the table has thousands of rows, JTable may slow down because it loads all rows at once.
Solution: Use pagination or lazy loading instead of loading everything upfront.
✅ Example: Paginated JTable (Loading 100 Rows at a Time)
java Copy Edit int pageSize = 100; // Load 100 rows at a time int currentPage = 0; List data = fetchDataFromDatabase(currentPage * pageSize, pageSize); // Load only a subset
DefaultTableModel model = (DefaultTableModel) table.getModel(); for (Object[] row : data) {
//
Slow Rendering Due to Default Renderer Issue: The default cell renderer calls Component.setOpaque(false), causing unnecessary painting.
Solution: Use a custom renderer with setOpaque(true).
✅ Example: Custom Fast Renderer
java Copy Edit class FastRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); label.setOpaque(true); // Prevents repainting issues
;;
Frequent Repainting & Event Listeners Cause Overhead Issue: JTable repaints everything after every update, even when unnecessary.
Solution: Temporarily disable auto updates, batch updates, then re-enable.
✅ Example: Batch Update with Table Locking
java Copy Edit DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setRowCount(0); // Clear table without repainting table.setAutoCreateColumnsFromModel(false); // Avoid unnecessary updates
// Batch insert rows for (int i = 0; i < 1000; i++) { model.addRow(new Object[]{"ID " + i, "Name " + i, i + 20}); }
table.setAutoCreateColumnsFromModel(true); //
Using DefaultTableModel for Large Data Handling Issue: DefaultTableModel is inefficient for large datasets because it stores all data in memory.
Solution: Use a custom TableModel that fetches data dynamically.
✅ Example: Custom Lazy Loading Table Model
java Copy Edit class CustomTableModel extends AbstractTableModel { private final int rowCount = 1000000; // Simulating large dataset@Override public int getRowCount() { return rowCount;
Slow Sorting & Filtering Issue: Default sorting can be slow for large datasets.
Solution: Use RowSorter with custom sorting instead of sorting all rows at once.
✅ Example: Optimized Sorting
java Copy Edit TableRowSorter sorter = new TableRowSorter<>(table.getModel()); table.setRowSorter(sorter);
Use pagination or lazy loading for large datasets. ✅ Optimize cell rendering with setOpaque(true). ✅ Batch updates & disable auto updates temporarily. ✅ Use a custom TableModel instead of DefaultTableModel. ✅ Implement RowSorter for efficient sorting.
0 notes
Text
Understanding the toupper() Function: Converting Text to Uppercase in Programming
When working with strings in programming, there are often situations where we need to convert text to uppercase. The toupper function is one of the most common ways to achieve this in various programming languages. In this discussion, let's explore how toupper() works, its applications, and potential alternatives.
What is toupper()? The toupper() function is typically used to convert lowercase characters to uppercase. It is available in many programming languages, including C, C++, Python (as upper()), and others.
In C and C++, toupper() is defined in the ctype.h or cctype header files. It takes a single character as input and returns its uppercase equivalent if the character is a lowercase letter. If the character is already uppercase or is not an alphabetic character, it remains unchanged.
Basic Syntax in C and C++: c Copy Edit
include
include
int main() { char ch = 'a'; char upperCh = toupper(ch); printf("Uppercase: %c\n", upperCh); // Output: A return 0; } For strings, we can iterate through each character and apply toupper() to convert the entire string to uppercase:
c Copy Edit
include
include
include
int main() { char str[] = "hello world"; for (int i = 0; i < strlen(str); i++) { str[i] = toupper(str[i]); } printf("Uppercase String: %s\n", str); return 0; } Using toupper() in Other Languages Python: Instead of toupper(), Python provides the .upper() method for strings: python Copy Edit text = "hello world" print(text.upper()) # Output: HELLO WORLD Java: Java provides toUpperCase() as part of the String class: java Copy Edit String text = "hello world"; System.out.println(text.toUpperCase()); // Output: HELLO WORLD Common Use Cases of toupper() User Input Normalization: Ensuring case consistency in user input (e.g., usernames, passwords). Comparing Strings Case-Insensitively: Converting both strings to uppercase before comparison. Text Formatting: Making certain words stand out by converting them to uppercase. Processing Data: When working with CSV files, databases, or logs where case uniformity is required. Potential Issues and Considerations toupper() only works on single characters, so iterating over a string is necessary. It does not handle locale-specific characters well (e.g., accented letters). Some languages have better built-in alternatives, like str.upper() in Python or toUpperCase() in Java. Discussion Questions: How do you typically use toupper() in your projects? Have you encountered any edge cases or challenges when working with toupper()? Do you prefer alternative methods for converting text to uppercase in your programming language?
0 notes
Text
Difference Between Java and JavaScript
When it comes to programming, Java and JavaScript are two of the most widely used languages. Despite their similar names, they are quite different in terms of functionality, usage, and even underlying principles. This often leads to confusion among beginners who may assume that the two technologies are related. However, understanding the differences between Java and JavaScript can give developers the clarity they need to decide which tool is best suited for their specific needs.
In this blog, we will explore the key differences between Java and JavaScript by discussing their features, syntax, platforms, and use cases. By the end, you will have a clearer understanding of when and why to use each of these languages.
1. What is Java?
Java is a powerful, object-oriented programming (OOP) language developed by Sun Microsystems (now owned by Oracle). It was first released in 1995 and is designed to be a platform-independent language that allows developers to "write once, run anywhere." This means that Java code can be written on one platform (e.g., Windows, macOS, Linux) and run on any device that has a Java Virtual Machine (JVM) installed. The JVM translates the compiled Java bytecode into machine-specific code, making it platform-independent.
Java is primarily used for developing standalone applications, large enterprise systems, Android applications, and server-side applications. It’s known for its stability, scalability, and performance.
2. What is JavaScript?
JavaScript, on the other hand, is a lightweight, interpreted scripting language that was created for web development. Originally designed to run in web browsers, it allows developers to create dynamic and interactive elements on websites. JavaScript was created by Brendan Eich at Netscape Communications in 1995 and has since evolved into one of the most important languages in web development.
JavaScript is a client-side language, which means it runs in the browser, but it can also be used on the server side through Node.js. Unlike Java, JavaScript is not a strictly object-oriented language; it supports multiple programming paradigms such as procedural, functional, and event-driven programming.
3. Syntax Differences Between Java and JavaScript
One of the most noticeable differences between Java and JavaScript lies in their syntax. While they may share some similar constructs (like curly braces for code blocks), the syntax rules and programming paradigms they follow are quite different.
Java is a statically-typed language, meaning that you must declare the type of variable before using it. For example:javaCopyint number = 10; String message = "Hello, World!"; The types (like int and String) must be specified and can’t be changed once the variable is declared.
JavaScript, on the other hand, is dynamically typed. This means you do not have to specify the type of the variable before using it, and the type can change as the program runs. For example:javascriptCopylet number = 10; let message = "Hello, World!"; Here, the type of number and message is determined dynamically at runtime.
4. Compiling vs. Interpreting
Another significant difference between Java and JavaScript is how they are executed.
Java is a compiled language. This means that Java code is first written and then compiled into bytecode by a Java compiler. The bytecode is platform-independent and can be run on any device that has a Java Virtual Machine (JVM). This provides portability and allows Java applications to run across different systems without modification.Steps in Java Execution:
Write Java source code (.java file).
Compile the code using a Java compiler, which converts it into bytecode (.class file).
The bytecode is then executed by the JVM.
JavaScript, on the other hand, is an interpreted language, which means the code is executed line-by-line by an interpreter (usually within a web browser). The JavaScript engine in a browser reads the JavaScript code, interprets it, and executes it in real-time.Steps in JavaScript Execution:
Write JavaScript code (.js file).
The code is directly interpreted and executed by a web browser or JavaScript runtime environment like Node.js.
5. Execution Environment
Java and JavaScript also differ greatly in terms of their execution environments:
Java is typically used for building standalone applications that run on the JVM. These applications can be anything from mobile apps (Android) to large-scale enterprise applications or even desktop software.
JavaScript, on the other hand, is designed for web development. It is mostly used to create dynamic web pages, handle user interactions, and perform client-side tasks. JavaScript code runs within a web browser (Chrome, Firefox, Safari, etc.) and can also run on the server side through Node.js.
6. Object-Oriented vs. Multi-Paradigm
Java is primarily an object-oriented programming (OOP) language, which means it is based on the principles of encapsulation, inheritance, and polymorphism. Java focuses heavily on classes and objects, and most Java programs are organized around these core concepts.
JavaScript, however, is a multi-paradigm language. While it can support object-oriented programming (OOP) through prototypes, it also supports functional programming and event-driven programming. JavaScript uses prototypes for inheritance rather than classes (though modern JavaScript has introduced classes, they are syntactic sugar over prototypes).
7. Memory Management
Both Java and JavaScript have automatic memory management, but they handle it differently:
Java uses garbage collection to automatically manage memory. The JVM’s garbage collector automatically frees up memory that is no longer in use. Java also allows developers to manually control memory management through various memory allocation techniques.
JavaScript also uses garbage collection for memory management, but since JavaScript runs in a single-threaded environment (in the browser), memory management is typically more lightweight and less complex compared to Java.
8. Use Cases
The primary use cases for each language highlight their distinct roles in the software development landscape.
Java:
Enterprise Applications: Java is often used in large-scale business systems due to its scalability, robustness, and extensive libraries.
Mobile Development: Java is the official language for Android app development.
Backend Systems: Java powers many server-side applications, particularly in environments that require high performance.
Embedded Systems: Java is used in various embedded systems due to its portability and efficiency.
JavaScript:
Web Development: JavaScript is essential for front-end web development, enabling dynamic and interactive web pages.
Backend Development: With the rise of Node.js, JavaScript can also be used on the server side to build web servers and APIs.
Mobile Apps: JavaScript frameworks like React Native and Ionic allow developers to create mobile applications for both iOS and Android.
Game Development: JavaScript is increasingly used in building browser-based games or game engines like Phaser.js.
9. Performance
Performance is another area where Java and JavaScript differ significantly.
Java generally performs better in comparison to JavaScript because it is a compiled language. The compiled bytecode is optimized by the JVM and can be executed more efficiently. Java is well-suited for large-scale applications that require high performance.
JavaScript is typically slower than Java due to its interpreted nature and the overhead involved in real-time interpretation. However, JavaScript has made significant strides in performance, especially with modern engines like V8 (used in Google Chrome and Node.js), which optimize execution.
10. Learning Curve
Java can be more difficult to learn for beginners because it’s a statically-typed language with a focus on OOP principles. The syntax and structure are more complex, and it requires understanding various programming concepts such as classes, interfaces, and inheritance.
JavaScript is often considered easier to learn, especially for web developers, because it is dynamically typed and has a simpler syntax. Additionally, JavaScript is very forgiving with variable types, making it easier to experiment with code.
Conclusion
While Java and JavaScript have similar names, they are fundamentally different languages with different uses, execution models, and ecosystems. Java is a versatile, platform-independent, and high-performance language primarily used for backend applications, mobile development, and large-scale enterprise solutions. JavaScript, on the other hand, is a lightweight, interpreted language that powers the dynamic, interactive elements of the web.
Choosing between Java and JavaScript depends on the specific needs of your project. If you are working on a web-based application or interactive front-end elements, JavaScript will be the way to go. If you are building complex back-end systems, enterprise software, or mobile apps, Java might be more appropriate. Both languages are crucial in their own domains, and mastering them can open up a world of development opportunities.
1 note
·
View note
Text
The Basics of Java: Understanding Variables and Data Types
Java, one of the most widely-used programming languages, is the foundation for a range of applications from web development to mobile applications, especially on the Android platform. For those new to Java, understanding its core concepts like variables and data types is essential to grasp how the language operates. These elements form the building blocks of Java programming and will set you up for success as you learn more advanced topics.
To gain a deeper understanding and hands-on experience, consider joining CADL’s Java Programming Course. Our course offers a structured approach to Java, covering everything from the basics to advanced topics.
1. What Are Variables?
In Java, a variable is a named location in memory used to store data. Variables act as containers for storing information that can be referenced and manipulated throughout a program. Whenever you need to work with data (numbers, text, etc.), you will need to assign it to a variable.
Declaring Variables in Java
Declaring a variable in Java involves specifying its data type, followed by the variable name, and optionally initializing it with a value. Here’s the basic syntax:
java
Copy code
dataType variableName = value;
For example:
java
Copy code
int age = 25;
String name = "John";
In the first line, an integer (int) variable called age is declared and initialized with the value 25. In the second line, a String variable named name is declared and initialized with the text "John".
2. Types of Variables in Java
Java has three primary types of variables:
Local Variables: Defined within methods or blocks and accessible only within that method or block.
Instance Variables: Also known as non-static fields, they are defined within a class but outside any method. They are unique to each instance of a class.
Static Variables: Also known as class variables, they are shared among all instances of a class. Defined with the static keyword.
3. Understanding Data Types in Java
Data types specify the type of data a variable can hold. Java has two main categories of data types: Primitive Data Types and Non-Primitive Data Types.
Primitive Data Types
Primitive data types are the most basic data types and are predefined by Java. They include:
int: Stores integer values (e.g., int age = 30;).
double: Stores decimal numbers (e.g., double price = 9.99;).
char: Stores single characters (e.g., char grade = 'A';).
boolean: Stores true or false values (e.g., boolean isJavaFun = true;).
Java also includes byte, short, long, and float data types, each used for specific types of numeric values.
Examples:
java
Copy code
int count = 10; // integer type
double height = 5.9; // double (floating-point) type
char letter = 'A'; // character type
boolean isActive = true; // boolean type
Each primitive type has a specific range and size in memory. For instance, int values range from -2,147,483,648 to 2,147,483,647, while double values allow for larger decimal numbers.
Non-Primitive Data Types
Non-primitive data types are created by the programmer and can include multiple values and methods. The most common non-primitive data types are Strings, Arrays, and Classes.
String: A sequence of characters (e.g., String message = "Hello, World!";).
Array: Used to store multiple values of the same type in a single variable (e.g., int[] numbers = {1, 2, 3, 4};).
Class: Used to define custom data types in Java, which can hold both variables and methods.
4. Variable Naming Conventions
Naming conventions help make code more readable and maintainable. In Java:
Variable names should be meaningful and descriptive.
Use camelCase for variable names (e.g., userName, itemCount).
Avoid starting variable names with numbers or using special characters except _.
Following these conventions ensures your code is more understandable, especially as projects grow.
5. Java Type Casting
Type casting is the process of converting one data type to another. Java allows two types of type casting: Implicit Casting and Explicit Casting.
Implicit Casting (Widening Casting)
Java automatically converts a smaller data type to a larger one without data loss. For example, converting an int to a double:
java
Copy code
int num = 10;
double doubleNum = num; // Implicit casting from int to double
Explicit Casting (Narrowing Casting)
When converting a larger data type to a smaller one, you must perform explicit casting. This process may result in data loss, so proceed with caution.
java
Copy code
double price = 19.99;
int discountedPrice = (int) price; // Explicit casting from double to int
6. Common Data Type Examples in Java
Let’s look at some examples to see how variables and data types work together in Java:
Example 1: Working with Different Data Types
java
Copy code
public class Main {
public static void main(String[] args) {
int quantity = 5; // integer variable
double pricePerItem = 15.50; // double variable
String itemName = "Pen"; // String variable
boolean isInStock = true; // boolean variable
double totalPrice = quantity * pricePerItem;
System.out.println("Item: " + itemName);
System.out.println("Total Price: " + totalPrice);
System.out.println("In Stock: " + isInStock);
}
}
Example 2: Using Type Casting
java
Copy code
public class Main {
public static void main(String[] args) {
double num = 9.78;
int data = (int) num; // Explicit casting: double to int
System.out.println("Original Number (double): " + num);
System.out.println("Converted Number (int): " + data);
}
}
In the second example, the decimal part of num is lost because int can only store whole numbers. Type casting helps control data representation but requires careful consideration.
7. Final Thoughts on Variables and Data Types in Java
Understanding variables and data types in Java is crucial for writing efficient, error-free code. Java’s versatility in handling data types allows developers to manage various data with ease, whether you're dealing with text, numbers, or more complex data structures. Starting with these basic concepts will give you the foundation needed to explore more advanced programming topics, such as control flow, object-oriented programming, and data structures.
Mastering the fundamentals of Java is easier with structured guidance, so why not join CADL’s Java Programming Course? This course provides hands-on lessons, practical examples, and insights into core Java concepts, setting you on the right path to becoming a skilled Java developer.
0 notes
Text
Common Java String Methods Explained
You can convert a numeric string into a number. To convert a string into an int value, use the Integer.parseInt : intintValue = Integer.parseInt(inString); Where intString is a numeric string such as “378”. To convert a string into a double value, use the Double.parseDouble method: double doubleValue = Double.parseDouble(doubleString); Where doubleString is a numeric string such as…
View On WordPress
0 notes
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.
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!
#java#Java String to Int#how to convert string to int in java#how to convert string to int in java example#how to convert a string to int in java#how to convert string to integer in java#convert string to int java#convert string to int in java#how can convert string to int in java#how to convert a string to integer in java#convert int to string in java#string to integer in java#java convert string to int#convert string to int#how to convert integer to string in java#string to int java
1 note
·
View note
Text
hi
fizzbuzz reverse string implement stack
convert integer to roman numeral longest palindrome substring
design hashset
Java group by sort – multiple comparators example https://leetcode.com/discuss/interview-question/848202/employee-implementation-online-assessment-hackerrank-how-to-solve
SELECT SUBQUERY1.name FROM (SELECT ID,name, RIGHT(name, 3) AS ExtractString FROM students where marks > 75 ) SUBQUERY1 order by SUBQUERY1.ExtractString ,SUBQUERY1.ID asc ;
SELECT *
FROM CITY
WHERECOUNTRYCODE = 'USA' AND POPULATION > 100000;
Regards
Write a simple lambda in Java to transpose a list of strings long value to a list of long reversed. Input: [“1”,”2”,”3”,”4”,”5”] output: [5,4,3,2,1] 2. Write a Java Program to count the number of words in a string using HashMap.
Sample String str = "Am I A Doing the the coding exercise Am" Data model for the next 3 questions:
Write a simple lambda in Java to transpose a list of strings long value to a list of long reversed. Input: [“1”,”2”,”3”,”4”,”5”] output: [5,4,3,2,1] 2. Write a Java Program to count the number of words in a string using HashMap.
Sample String str = "Am I A Doing the the coding exercise Am" Data model for the next 3 questions:
Customer :
CustomerId : int Name : varchar(255)
Account :
AccountId : int CustomerId : int AccountNumber : varchar(255) Balance : int
Transactions : Transactionid : int AccountId: int TransTimestamp : numeric(19,0) Description : varchar(255) Amount(numeric(19,4)) 3. Write a select query to find the most recent 10 transactions. 4. Write a select query, which, given an customer id, returns all the transactions of that customer. 5. What indexes should be created for the above to run efficiently? CustomerId, AccountId 6. Write a program to sort and ArrayList.
Regards
0 notes
Text
Why we need different data types in programming

Different data types in programming are essential for several reasons:
### 1. **Memory Efficiency**
- **Specific Size**: Different data types have different memory requirements. For example, an `int` might require 4 bytes, while a `char` typically requires only 1 byte. By using the appropriate data type, you can manage memory more efficiently and avoid wastage.
### 2. **Performance Optimization**
- **Faster Operations**: Certain data types allow for faster processing. For example, operations on integers are generally quicker than operations on floating-point numbers. Choosing the right data type can improve the performance of your program.
### 3. **Data Integrity**
- **Appropriate Operations**: Data types enforce rules about what operations are valid. For instance, you can't perform arithmetic operations on strings without explicitly converting them. This helps in preventing logical errors and ensuring that data is manipulated correctly.
### 4. **Type Safety**
- **Error Prevention**: Strongly typed languages (like C++ and Java) check the data types at compile time, reducing the risk of type-related errors. For instance, trying to use a string in a context where an integer is expected will cause a compile-time error.
### 5. **Clear Intent**
- **Code Readability**: Using specific data types clarifies the intended use of a variable. For example, declaring a variable as `float` makes it clear that it is intended for decimal values, while a `bool` is meant for true/false values. This enhances the readability and maintainability of the code.
### 6. **Data Representation**
- **Variety of Data**: Different data types are designed to represent different kinds of data. For example:
- **Integers** for whole numbers.
- **Floating-point numbers** for numbers with decimal points.
- **Characters** for individual letters or symbols.
- **Strings** for sequences of characters.
- **Booleans** for true/false values.
- By using appropriate types, you can accurately represent and manipulate different forms of data.
### 7. **Functionality**
- **Specialized Operations**: Different data types support specialized operations. For instance, lists or arrays support operations like indexing and iteration, while objects support methods and properties. Choosing the right type allows you to leverage these specialized functionalities.
### 8. **Interoperability**
- **Data Exchange**: In systems where different components or modules interact, data types ensure that data is correctly interpreted. For example, when exchanging data between a database and an application, having consistent data types ensures accurate communication.
### Summary
By using different data types, programmers can:
- Optimize memory and performance.
- Prevent errors and ensure correct data manipulation.
- Enhance code readability and maintainability.
- Represent and process a variety of data accurately.
These factors contribute to more robust, efficient, and understandable code.
TCCI Computer classes provide the best training in online computer courses through different learning methods/media located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.
For More Information:
Call us @ +91 98256 18292
Visit us @ http://tccicomputercoaching.com/
#best programming course at tcci#computer course at tcci#coaching for programming language#computer coaching class in bopal-Ahmedabad#computer institute in bopal-Ahmedabad
0 notes
Text
Covert String to Java using Integer.parseInt()
Let's see the simple code to convert a string to an int in java:
#java#javalanguage#javaprogramming#programming#coding#code#trending#education#technology#tech#training#engineering#software#development#softwaredevelopment#besttraininginstitute#online#onlinetraining#traininginstitute#tutorial
1 note
·
View note
Text
Direct RAM Access
All programs operate on RAM regardless of its programming language, operating system or hardware, be it a smartphone, cloud, desktop, laptop or a machine as tiny as Arduino.
Nowadays, RAM is used as a synonym for main computer memory. In reality, it is an abbreviation for "Random-Access Memory". Here, random means not as in something random; the last thing you expect from a RAM is randomness. The connection between words "random" and "access" with the hyphen means any data in memory is accessed arbitrarily by the programs.
In this context, the opposite of random is sequential, which means the memory is accessed one-by-one as we can still see in SQL result-sets. In old times, memory hardware like "tape" was sequential; to access an arbitrary location, all previous locations on the band should be visited. The access types of memory hardware may seem outdated today as tapes are obsoleted as storage devices; almost all memory are "random" for the last 20 years.
Memory types like hard disks and CD/DVDs are randomly-accessed, but one thing separates RAM from the former is the fixed access time for each location. For disks, a device called "head" should be rotated so that access times may vary depending on the location. Nowadays, hard disks are rapidly replaced by SSDs (Solid State Drive) that can store as much data as disks and provide fixed access time as RAMs.
From now on, let's assume a RAM is a sea of bytes that is addressed by a number which is represented by the data type int.
In C, you can directly access RAM via its address. Let's start with an example:
#include <stdio.h> int main(int argc, char* argv[]) { char* p = 0; printf("%c\n", *p); return 0; }
Here, we start introducing the infamous "pointers" in C. Pointers are used like "references" in modern languages, but they really are memory addresses in C.
The term "char" (character) in the variable definition is the main mental block for understanding pointers while learning C. In reality, any type of variable definition with an asterisk (*) is always an int. The preceding type specifier is used to represent data in that address later.
The variable p is assigned the address 0, or in other words, the location of the very first byte in memory to p.
char *p = 0;
Here, *p represents the data in address p as char. We'll try to write it on the standard out (stdout) with printf():
printf("%c\n", *p);
When you run this program in a PC, it crashes with the following message:
Segmentation fault (core dumped)
In Windows, it pops a message box that says "Access Violation". This fault is similar to NullPointerException, NullReferenceException etc. in modern languages.
The above program crashes because the ability to reach an address doesn't mean the memory location it refers really exists. Because modern operating systems like Linux, Windows run many programs (or processes as they are called in that context) simultaneously, they should manage precious RAM resources carefully by a mechanism called "virtual memory" that often abbreviated as VM.
Modern systems would block writing to address 0 because it almost always means a programming fault like the exceptions mentioned above. But C is also used for embedded programming, which means writing programs for very tiny CPUs which helps electronic controller hardware. Those machines have constrained hardware resources so they may not have the luxury for controlling memory access. In this instance, reading the memory at 0 or an arbitrary location may not crash.
Now let's try to assign an arbitrary address to the p:
char *p = 5500;
The compiler would give a warning for that number.
warning: initialization makes pointer from integer without a cast
This error won't halt the compilation process. But as a wise programmer, we should not accumulate warnings. Thanks to "casting", it is possible to convince the compiler that we know what we are doing with a cast:
char *p = (char *)5500;
When you run the program, the result is again the segmentation fault. As you can see, C makes it possible to shoot yourself in the foot. But you are still lucky if you shoot yourself in the foot because at least you can go to a hospital. However, if that kind of error results in reading or writing from a legal memory, then your data integrity breaks and god knows where this error pops in the future.
Playing with Valid Memory Locations
Enough of crashes. Let's use some valid memory addresses, starting with the following example program:
#include <stdio.h> int main(int argc, char* argv[]) { char c = 'A'; printf("%u\n", &c); return 0; }
Here we define a variable of 1 byte (or 1 ASCII character) as c. It represents a location in RAM which stores a byte of data. The & operator takes the address of a variable, so the output is something like this:
1868946151
Let's play a little bit more and add any variable we've encountered throughout our little program:
printf("argc %u\n", &argc); printf("argv %u\n", &argv); printf("c %u\n", &c); printf("main %u\n", main);
It outputs something like this:
argc 1527215996 argv 1527215984 c 1527216007 main 448100010
As you can see, our main function's assembly code is located somewhere in our RAM.
Now let's play with them via a pointer:
char c = 'A'; char* p = &c; printf("c %c\n", c); printf("*p %c\n", *p); *p = 'B'; printf("c %c\n", c);
Here we define a pointer p and assign it to the address of c. So p becomes a reference to the c. The output is:
c A *p A c B
Now let's do something dangerous:
char* p = main; printf("%c\n", *p); *p = 'A';
This program has the ability to read and print the first character of the main() function but crashes when trying to write into it. Modern CPUs can distinguish between code and data and prevents overwriting the code.
U Segmentation fault (core dumped)
If you try the example above, you probably get warnings but, it doesn't stop compiling anyway.
To get even more dangerous, we will use a technique called the "pointer arithmetic".
char c1 = 'A'; char c2 = 'B'; char *p = &c1; printf("C1 %u %c\n", &c1, c1); printf("C2 %u %c\n", &c2, c2); p++; *p = 'Z'; printf("C2 %u %c\n", &c2, c2);
When you run this program, the output will be:
C1 69358686 A C2 69358687 B C2 69358687 Z
As you can see, the value of c2 is changed magically by a series of manipulations.
char *p = &c1;
We first assign pointer p to the address of c1.
p++; *p = 'Z'; printf("C2 %u %c\n", &c2, c2);
Remember, a pointer is actually an int that represents a memory address. Since it is an int, it is perfectly legal to increment it. By that, we can magically change the value of c2 without mentioning it.
Control is costly. Programs written in C are very fast because allowing direct manipulation of RAM avoids that cost.
Other Languages' Perspective on Accessing RAM
Most modern languages other than C and C++ prevent direct access to RAM. Instead, they control accessing it through carefully defined interfaces called "references". First, there is no notion of taking the address of a variable for basic types like char, int, double etc.
Second, object instances are stored in a variable of reference type. The reference is an opaque type; you can't take the address of it. They are used as-is. Of course, you can change the object which the reference points to, but you can't make it pointing an invalid arbitrary address like 5500 as we have given above.
Of course, object instances do live somewhere in RAM and in the 1990s references may leak that info when you convert them into a string. Today garbage collectors (GC) may move objects around the RAM for efficiency and heap defragmentation, so that info should contain something more independent than a mere memory address.
The following Java program creates two instances of class Object and converts them into a string:
public class Xyz { public static void main(String[] args) { Object o1 = new Object(); Object o2 = new Object(); System.out.println("O1 " + o1); System.out.println("O2 " + o2); } }
The outputs are some random hash values that uniquely identify the instance that is managed by the GC. As you can see, the hexadecimal numbers are unrelated.
O1 java.lang.Object@3af49f1c O2 java.lang.Object@19469ea2
One of the main design principles of modern languages is preventing pointer errors as you can see in the preceding paragraphs. As we said before, direct RAM manipulation is what makes C programming language very fast. However, most modern software doesn't need to be fast as much. Correctness is more valued since programmers are forced to deploy programs fast in this Internet era.
Zero, Null, Nil, Undefined
References can have a special value called null or nil or undefined when they do not point to any object instance. Let's make them fail by abusing them:
String s = null; System.out.println("Length " + s.length());
The result is the Java-style "Segmentation Fault".
Exception in thread "main" java.lang.NullPointerException at Xyz.main(Xyz.java:6)
Let me stress again. In a modern programing language, the reference may be null or something real, not in-between like in C/C++.
Some more modern languages like Kotlin (a Java dialect) go even further and prevent null value assignment if you don't specifically mark the reference with a question mark:
val String s = null; // Incorrect, don't compile var String? s = null; // Correct ```` ## Leaky Abstraction Operating Systems like Linux and Windows provide C APIs for their services. A modern programming language runtime should call that APIs at some point to do meaningful things like I/O and creating windows. Each of those languages provides some means of accessing C libraries and interacting with C so you can taste the pleasure of direct memory manipulation. For example, C# programming language and its associated runtime .NET provides "Interop" library to interface with the operating system. Interop library contains a big class called Marshal, which has many dirty and dangerous static methods against all OOP principles. For example, the following methods are available to read and write a byte to/from the RAM directly:
public static byte ReadByte(IntPtr ptr); public static void WriteByte(IntPtr ptr, byte val);
IntPtr type represents a C pointer. These methods are ready to throw an "AccessViolationException" when you do the same experiments as in the above paragraphs. But when you access some valid C memory by some means outside the scope of this topic, you can use them conveniently. Read/Write methods have other variants which allow accessing different basic types like int and blocks of byte arrays at once. Now, as always, let's do some naughty things:
using System; using System.Runtime.InteropServices;
namespace savas { class Program { static void Main(string[] args) { byte b = 33; GCHandle h = GCHandle.Alloc(b, GCHandleType.Pinned); IntPtr p = h.AddrOfPinnedObject(); byte b2 = Marshal.ReadByte(p); Console.WriteLine("b2 = " + b2);
} }
} ```
After defining the variable b, we "pinned" it so the GC won't move its place in memory. Then we get its address via AddrOfPinnedObject() method just like the & operator in C, read its value and print it. The output is "b2 = 33" as expected.
But if you call Marshal.WriteByte() to manipulate p, it doesn't write into b because once you pin the object, the connection between b and p is lost. This allows C# to stay pure because the Marshal class' memory methods are designed to manipulate buffers provided by the C libraries, not the other way around.
Python programming language has been written in C. At the same time, it provides a C interface that allows built-in classes and libraries be written in C. If that kind of classes supports a "buffer protocol", its raw bytes can be manipulated by memoryview class of Python. By default, Python's standard byte and bytearray objects support that protocol.
Without memoryview, Python-way of manipulating buffers is inefficient since any operation on arrays and slices requires creating a copy of the object. Using memoryview allows C-style direct control of memory in a controlled way; "best of both worlds" in certain scenarios.
1 note
·
View note
Text
How To Read Lined JSON files with Java 8
Came across this, seeming trivial at a glance, task of parsing a relatively well-formatted data feed just recently. Sure, you may say, what could be easier than parsing a JSON format given that there are plenty of tools for that, especially for Java? Well, sorry, not exactly JSON... In effect, compared to other unstructured data sources I previously worked with, this feed used a lined JSON format (i.e. IJSON). Example:
{“id”: “us-cia-world-leaders.bc0...”, “type”: “individual”, ...} {“id”: “us-cia-world-leaders.924...”, “type”: “entity”, ...} {...}
Even though this format is widely used, mainstream JSON parsers such as Jackson cannot handle this structure since it’s not a valid JSON file. Looks like we have a little problem here?
Tackling IJSON with Java
A quick solution is to simply read the lined JSON file line by line and transform each line to a POJO entry. Combined with streamed input readers, the lined JSON format appeared to be more efficacious than the “classic” JSON, merely because we no longer need to preload the entire structure in memory and then transform it. With 30Mb+ files, the performance benefits are evidently noticeable.
The below code snippet illustrates how this can be achieved:
import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Stream; /** * Simple streamed reader to go through Lined JSON files, convert each line to POJO entry * and perform a specified action on every row. * @author Vladimir Salin */ public class LineBasedJsonReader { private static final Logger log = LoggerFactory.getLogger(LineBasedJsonReader.class); private ObjectMapper objectMapper; public LineBasedJsonReader(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** * Parses a provided input in a streamed way. Converts each line in it * (which is supposed to be a JSON) to a specified POJO class * and performs an action provided as a Java 8 Consumer. * * @param stream lined JSON input * @param entryClass POJO class to convert JSON to * @param consumer action to perform on each entry * @return number of rows read */ public int parseAsStream(final InputStream stream, final Class entryClass, final Consumer<? super Object> consumer) { long start = System.currentTimeMillis(); final AtomicInteger total = new AtomicInteger(0); final AtomicInteger failed = new AtomicInteger(0); try (Stream<String> lines = new BufferedReader(new InputStreamReader(stream)).lines()) { lines .map(line -> { try { total.incrementAndGet(); return objectMapper.readerFor(entryClass).readValue(line); } catch (IOException e) { log.error("Failed to parse a line {}. Reason: {}", total.get()-1, e.getMessage()); log.debug("Stacktrace: ", e); failed.incrementAndGet(); return null; } }) .filter(Objects::nonNull) .forEach(consumer); } long took = System.currentTimeMillis() - start; log.info("Parsed {} lines with {} failures. Took {}ms", total.get(), failed.get(), took); return total.get() - failed.get(); } }
As you can see, we simply need to pass a source as an InputStream, a POJO class for the JSON we want to parse to, a Java 8 Consumer to act on each parsed row, and that’s it. The above is just a simple snippet for illustrative purposes. In a production environment, one should add more robust error handling.
So why Lined JSON?
Indeed, with these numerous JSON parsing tools, why the heck someone decided to go Lined JSON? Is it any fancy writing every single line in this JSON-y object format?
Actually, yes, it is fancy. Just think of it for a second -- you read the line and get a valid JSON object. Let me put it this way: you load just one line into memory and get a valid JSON object you can work with in your code. Another line -- another object. Worked with it, released from memory, going next. And this is how you proceed through the entire file, no matter how long it is.
Just imagine a huge JSON array weighting a good couple of huundred MBs. Going straightforward and reading in full would take quite a bunch of memory. Going lined JSON approach would allow you iterating through each line and spending just a little of your precious memory. For sure, in some cases we need the whole thing loaded, but for others it's just fine to go one by one. So, lessons learned, another convenient data structure to use and to handle!
Originally posted in Reading Lined JSON files with Java 8
1 note
·
View note
Text
Week 3 Notes - Processing - Java Robot
Addressing this section by section.
import processing.serial.*; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent;
This code imports the library dependencies.
Serial is a built-in library (no download needed) that lets us read serial values coming into our computer.
The Java robot class is a built in Java library that lets us automate keyboard and mouse commands.
Serial port; Robot robot; int button1Pressed; int button2Pressed;
Here we are declaring objects to represent our serial connection and also our robot that will take over our keyboard. We’ll call built-in methods on these objects in our code.
We also make two integers to store the values that we’ll be getting from serial.
void setup() { println(Serial.list()); port = new Serial(this, Serial.list()[3], 9600); port.bufferUntil('\n'); try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); exit(); } }
Setting up our objects. First we print out all available serial connections that the computer sees. This might be other USB devices, it might be a bluetooth connection, or any number of other things. When we instantiate port, we need to use the number of the serial connection that belongs to the arduino USB cable. In my computer its number 3, and that goes in the Serial() constructor with “this”, and the baud rate which in our Arduino code we set to 9600.
The next step is a slightly more complicated thing than normal. We have to use a try / catch to make sure that we’re able to create the robot properly. You can look up what it does exactly if you’re curious.
void serialEvent(Serial port) { String inString = port.readStringUntil('\n'); if (inString != null) { inString = trim(inString); //println(inString); int[] allButtons = int(split(inString, ';')); if (allButtons.length == 2) { button1Pressed = allButtons[0]; button2Pressed = allButtons[1]; } } }
Here is the serialEvent function, which is automatically called when serial data is received. It’s similar to how mousePressed() is automatically called by Processing too.
First we read the value of our serial data as a string and cut off at a new line.
Then we make sure that the data isn’t null, trim off any extra whitespace (new lines, tabs, spaces), parse each element based on the semicolon delimiter (the ; ), make an integer array to store the data after we convert it to an integer, then assign our variables based on our new array.
void draw() { //println("button 1 is: " + button1Pressed); //println("button 2 is: " + button2Pressed); if (button1Pressed == 0) { robot.keyPress(KeyEvent.VK_X); //robot.delay(50); } else { robot.keyRelease(KeyEvent.VK_X); } if (button2Pressed == 0) { robot.keyPress(KeyEvent.VK_C); //robot.delay(50); } else { robot.keyRelease(KeyEvent.VK_C); } }
I have a few lines commented out that just confirm that we’re getting the data from serial that we expect.
After that is a few conditionals to press the X button or the C button via robot, depending which button plugged into arduino is pressed.
Here is the link to the documentation for the Java Robot KeyEvent class.
1 note
·
View note