#how can convert string to int in java
Explore tagged Tumblr posts
tpointtechblog · 1 year ago
Text
Java Convert String to int | TpointTech
In Java, you can convert a Java String to an int using the Integer.parseInt() or Integer.valueOf() method.
Example:
String str = "123"; int num = Integer.parseInt(str); // Converts String to int System.out.println(num); //
Output:
123
int num = Integer.valueOf(str); // Also converts String to int
Both methods work similarly, but valueOf() returns an Integer object, while parseInt() returns a primitive int.
1 note · View note
izicodes · 2 years ago
Text
Dynamically vs Statically-Typed Programming Languages
Tumblr media
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~! 🚀
Tumblr media
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.
Tumblr media
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
Tumblr media
C#
Tumblr media
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()'!
Tumblr media
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
Tumblr media
That's all, thanks for reading, and hope you learned something new! Happy coding, folks~! 🌟💻🚀
Tumblr media
83 notes · View notes
nectoy7 · 6 months ago
Text
Understanding Java Data Types: A Comprehensive Guide
Java, one of the most widely used programming languages, is known for its portability, security, and rich set of features. At the core of Java programming are data types, which define the nature of data that can be stored and manipulated within a program. Understanding data types is crucial for effective programming, as they determine how data is stored, how much memory it occupies, and the operations that can be performed on that data.
What are Data Types?
In programming, data types specify the type of data that a variable can hold. They provide a way to classify data into different categories based on their characteristics and operations. Java categorizes data types into two main groups:
1. Primitive Data Types
2. Reference Data Types
Why Use Data Types?
1. Memory Management: Different data types require different amounts of memory. By choosing the appropriate data type, you can optimize memory usage, which is particularly important in resource-constrained environments.
2. Type Safety: Using data types helps catch errors at compile time, reducing runtime errors. Java is a statically typed language, meaning that type checks are performed during compilation.
3. Code Clarity: Specifying data types makes the code more readable and understandable. It allows other developers (or your future self) to quickly grasp the intended use of variables.
4. Performance Optimization: Certain data types can enhance performance, especially when dealing with large datasets or intensive calculations. For example, using int instead of long can speed up operations when the range of int is sufficient.
5. Defining Operations: Different data types support different operations. For example, you cannot perform mathematical operations on a String data type without converting it to a numeric type.
When and Where to Use Data Types?
1. Choosing Primitive Data Types:
Use int when you need a whole number without a decimal, such as counting items.
Use double for fractional numbers where precision is essential, like financial calculations.
Use char when you need to store a single character, such as a letter or symbol.
Use boolean when you need to represent true/false conditions, like in conditional statements.
2. Choosing Reference Data Types:
Use String for any textual data, such as names, messages, or file paths.
Use Arrays when you need to store multiple values of the same type, such as a list of scores or names.
Use Custom Classes to represent complex data structures that include multiple properties and behaviors. For example, a Car class can encapsulate attributes like model, year, and methods for actions like starting or stopping the car.
1. Primitive Data Types
Primitive data types are the most basic data types built into the Java language. They serve as the building blocks for data manipulation in Java. There are eight primitive data types:
Examples of Primitive Data Types
1. Byte Example
byte age = 25; System.out.println(“Age: ” + age);
2. Short Example
short temperature = -5; System.out.println(“Temperature: ” + temperature);
3. Int Example
int population = 1000000; System.out.println(“Population: ” + population);
4. Long Example
long distanceToMoon = 384400000L; // in meters System.out.println(“Distance to Moon: ” + distanceToMoon);
5. Float Example
float pi = 3.14f; System.out.println(“Value of Pi: ” + pi);
6. Double Example
double gravitationalConstant = 9.81; // m/s^2 System.out.println(“Gravitational Constant: ” + gravitationalConstant);
7. Char Example
char initial = ‘J’; System.out.println(“Initial: ” + initial);
8. Boolean Example
boolean isJavaFun = true; System.out.println(“Is Java Fun? ” + isJavaFun);
2. Reference Data Types
Reference data types, unlike primitive data types, refer to objects and are created using classes. Reference data types are not defined by a fixed size; they can store complex data structures such as arrays, strings, and user-defined classes. The most common reference data types include:
Strings: A sequence of characters.
Arrays: A collection of similar data types.
Classes: User-defined data types.
Examples of Reference Data Types
1. String Example
String greeting = “Hello, World!”; System.out.println(greeting);
2. Array Example
int[] numbers = {1, 2, 3, 4, 5}; System.out.println(“First Number: ” + numbers[0]);
3. Class Example
class Car {     String model;     int year;
    Car(String m, int y) {         model = m;         year = y;     } }
public class Main {     public static void main(String[] args) {         Car car1 = new Car(“Toyota”, 2020);         System.out.println(“Car Model: ” + car1.model + “, Year: ” + car1.year);     } }
Type Conversion
In Java, type conversion refers to converting a variable from one data type to another. This can happen in two ways:
1. Widening Conversion: Automatically converting a smaller data type to a larger data type (e.g., int to long). This is done implicitly by the Java compiler.
int num = 100; long longNum = num; // Widening conversion
2. Narrowing Conversion: Manually converting a larger data type to a smaller data type (e.g., double to int). This requires explicit casting.
double decimalNum = 9.99; int intNum = (int) decimalNum; // Narrowing conversion
Conclusion
Understanding data types in Java is fundamental for effective programming. It not only helps in managing memory but also enables programmers to manipulate data efficiently. Java’s robust type system, consisting of both primitive and reference data types, provides flexibility and efficiency in application development. By carefully selecting data types, developers can optimize performance, ensure type safety, and maintain code clarity.
By mastering data types, you’ll greatly enhance your ability to write efficient, reliable, and maintainable Java programs, setting a strong foundation for your journey as a Java developer.
3 notes · View notes
reversedumbrella · 2 years ago
Note
your colour seperating program, I made something basically identical a few years ago in Python, would love to hear an in depth everything about it, especially how you made the spinning gif
Sorry for the delay I've been kinda busy. I also had various reasons I didn't want to share my code, but I've thought about a better/different way so here it goes (but for the time being I'm as far away from my computer as I possibly could)
I used processing, which is, as far as I remember, based on java but focused on visual media
Starting with the gif part, processing has the save() and saveFrame() methods that save the image displayed, and it also has the "movie maker" that allows you to make GIFs (and others but I don't remember)
I don't know about other languages but processing runs setup() when it starts and draw() every frame
In setup() I load an image as a PImage (processing's image data type like an array or string) and access it's pixel list. Using that I fill a 256x256x256 int array where every color corresponds to a place in the array. This 3d int array is filled with the amount of times each color appears
Lastly I use a log function to convert those numbers into the dot size
During draw() I run through this array and use the point() method to draw every dot (I can define a dot's color using stroke() and it's size using stroke weight() )
There are some optimisations I don't have the patience to explain at the moment
Processing has various render modes. I've made 3d images using the 2d render but I didn't want to repeat the feat (pov: you make 3d in 2d and then your teacher explains the existence of 3d to you). It also has the translate() that moves the origin and rotate(), rotateX() rotateY() and rotateZ() that allows you to rotate the image
I don't know how much you know about processing so sorry if you don't understand or if I'm explaining things you already know
8 notes · View notes
vultrsblog · 2 months ago
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
hexahome-india · 2 months ago
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
learnwithcadl123 · 5 months ago
Text
Tumblr media
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
vatt-world · 7 months ago
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
fullstackme · 5 years ago
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
new-arcade · 6 years ago
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
tpointtechblog · 1 year ago
Text
Java String to Int: A Comprehensive Guide for Developers
Introduction to Java String to Int: In the world of Java programming, converting strings to integers is a common task that developers encounter frequently.
Whether you're parsing user input, manipulating data from external sources, or performing calculations, understanding how to convert strings to integers is essential.
Tumblr media
In this comprehensive guide, we'll explore the various techniques, best practices, and considerations for converting strings to integers in Java.
Understanding String to Int Conversion:
Before diving into the conversion process, it's important to understand the difference between strings and integers in Java.
Strings are sequences of characters, while integers are numeric data types used to represent whole numbers. The process of converting a string to an integer involves parsing the string and extracting the numerical value it represents.
Using parseInt() Method:
One of the most common methods for converting strings to integers in Java is the parseInt() method, which is part of the Integer class. This method takes a string as input and returns the corresponding integer value. It's important to note that parseInt() can throw a NumberFormatException if the string cannot be parsed as an integer, so error handling is essential.
Example:
String str = "123"; int num = Integer.parseInt(str); System.out.println("Integer value: " + num);
Handling Exceptions:
As mentioned earlier, the parseInt() method can throw a NumberFormatException if the string is not a valid integer.
To handle this exception gracefully, developers should use try-catch blocks to catch and handle the exception appropriately. This ensures that the application doesn't crash unexpectedly if invalid input is provided.
Using valueOf() Method:
In addition to parseInt(), Java also provides the valueOf() method for converting strings to integers. While value Of() performs a similar function to parseInt(), it returns an Integer object rather than a primitive int. This can be useful in certain situations where an Integer object is required instead of a primitive int.
Example:
String str = "456"; Integer num = Integer.valueOf(str); System.out.println("Integer value: " + num);
Considerations and Best Practices:
When converting strings to integers in Java, there are several considerations and best practices to keep in mind:
Always validate input strings to ensure they represent valid integers before attempting conversion.
Handle exceptions gracefully to prevent application crashes and improve error handling.
Use parseInt() or valueOf() depending on your specific requirements and whether you need a primitive int or Integer object.
Consider performance implications, especially when dealing with large volumes of data or performance-critical applications.
Conclusion:
Converting strings to integers is a fundamental task in Java programming Language, and understanding the various techniques and best practices is essential for developers.
By following the guidelines outlined in this comprehensive guide, you'll be well-equipped to handle string to int conversion efficiently and effectively in your Java projects.
Happy coding!
1 note · View note
bestwallartdesign · 2 years ago
Text
The JSON Data Type in MySQL: Pluses and Minuses
Tumblr media
Optimizing data architecture is an important part of your application development process. Data in MySQL is generally stored in the record format, and when the data is called from the database by UI/UX or any other function, Java converts the data format to JSON before sending it to the client.
Related articles
InfluxDB: A modern approach to monitoring IoT & System
Here’s how DevSecOps is taking over from DevOps to help businesses gain an edge
Data saved in record format
Data saved in JSON format
Retrieve data faster by storing it as JSON
Conversion from row data to JSON is an extra layer of effort, and it takes more time and processing power to complete the action.
Exporting MySQL data to JSON can be done using any of the following methods:
Using the CONCAT() and GROUP_CONCAT() functions
Using JSON_OBJECT and JSON_ARRAYAGG functions
Using MySQL Shell and JSON Format Output
Using third-party software such as ApexSQL Database Power Tools for VS Code
Since version 5.7.8, MySQL has supported the JSON data type and allowed users to save in JSON format directly. However, since record format is the default, many users prefer to continue with this more traditional data format. By investing in the right data architecture services, you can optimize your data formats and data types to get the most out of your data architecture.
What is the JSON data format?
JSON, or JavaScript Object Notation, is a lightweight data-interchange format that’s similar to other data types. The storage size of a JSON document (also known as a NoSQL database) is around the same as that of LONGBLOB or LONGTEXT data.
Now that MySQL can store JSON data in binary format, the server can efficiently store, search and retrieve JSON data from the MySQL database.
When do you use it?
JSON data stores configuration data of multiple attributes. For example, let’s say you have the attributes of a customizable character in a game. One player’s character may have a hat, while another may have shoes a particular shade of red. All these data points can be captured in JSON tabular data.
How do you use it?
The syntax for a JSON column is column_name JSON. Data can be stored as JSON in MySQL by using the JSON data type.
Why should you use it?
The JSON data type provides certain advantages over storing JSON-format strings in a string column:
Automatic content validation: When you’re adding JSON data to MySQL, the database automatically confirms that the data format fits the data and doesn’t allow you to save it if it doesn’t match.
Faster data transfer: All calls from other clients require data conversion from record to JSON. Saving data directly in JSON makes data transfer more efficient. In addition, JSON can have a substantially lower character count, reducing the overhead in data transfers.
Readability: Since JSON data is saved in text format, not XML, it’s more easily readable by the human eye.
Easy exchange: JSON is helpful when it comes to data exchange between heterogeneous systems since you can also use the JSON format with other programming languages.
Potential to combine and store: JSON documents with multiple keys and value attributes can be saved in the same document.
What are the disadvantages of using JSON?
Indexing: MySQL doesn’t support indexing of JSON columns, which means that if you want to search through your JSON documents, you could trigger a full table scan. A JSON column cannot be indexed directly. However, if you wish to perform more efficient searches, you can generate a column with values extracted from the JSON column, on which you can create an index.
Limited storage: JSON documents stored in MySQL can only reach a theoretical maximum size of 1GB.
Inefficient storage: JSON could be more storage efficient. If your priority is optimizing data architecture by prioritizing storage efficiency in your database schema, you may be better off with more traditional data types such as INT, CHAR, VARCHAR, and the like.
At CloudNow, we understand that using the correct data types and formats is key to optimizing your data architecture. That’s why we stay up-to-date with the functionalities available on MySQL and the benefits of using different data types for different requirements, to provide top quality data architecture services.
0 notes
news4u95 · 2 years ago
Link
1 note · View note
courtgreys · 2 years ago
Text
Java string to codepoints
Tumblr media
JAVA STRING TO CODEPOINTS HOW TO
StringToCharArray_Java8Test. In this step, I will create two JUnit tests to convert a String into an array of characters. Public StringToCharArray(String message) 4.2 Convert String to Char Array Java 8 Test Create a Codepoint from a byte array using the default encoding (UTF-8) (byte bytes, encoding). mapToObj (c -> String.valueOf ( ( char) c)) 5.
Then we can use String.valueOf () or Character.toString () to convert the characters to a String object: Stream stringStream dePoints ().
Strings are constant their values cannot be changed after they are created. The mapping process involves converting the integer values to their respective character equivalents first. All string literals in Java programs, such as 'abc', are implemented as instances of this class.
JAVA STRING TO CODEPOINTS HOW TO
In this step, I will show you how to use the methods above to convert a String into an array of characters. The String class represents character strings. toCharArray() – return a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. Questions : How can I iterate through the unicode codepoints of a Java String using StringcharAt(int) to get the char at an index testing whether the char is.charAt(int index) – return the char value at the specified index.
Tumblr media
0 notes
pythonprogram2 · 2 years ago
Text
Lexicographical Order
 The term Lexicographical order is a mathematical term known by names: lexical order, lexicographic(al) product, alphabetical order, or dictionary order.
This section will cover the topic lexicographical order, its definition, and other detailed information. After that, we will learn how to use the concept of lexicographical order in the Java programming language.
Tumblr media
Defining Lexicographical Order
Lexicographical order or lexicographic in mathematics is a generalization of the alphabetical sequence of the dictionaries to the sequences of the ordered symbols or elements of a totally ordered list. The term lexicographical order is motivated by the word 'lexicon'. Lexicon is the set of words used in some of the other languages and has a conventional ordering. Thus, lexicographical order is a way for formalizing word order where the order of the underlying symbols is given.
In programming, lexicographical order is popularly known as Dictionary order and is used to sort a string array, compare two strings, or sorting array elements. It becomes quite easy to sort elements lexically. It is because lexicographical order has several variants and generalizations in which:
One variant is applicable to the sequences of different lengths as before considering the particular elements, lengths of the sequences are compared.
The second variant is used in order subsets of a given finite set. It does so by assigning a total order to the finite set. Then it is converting subsets into increasing sequences to which the lexicographical order is applied.
The generalization refers to the Cartesian product sequence of partially ordered sets, and such sequence is a total order, if and only if each factor of the Cartesian product are ordered totally.
Understanding the Formal Notion of Lexicographical Order
In order to understand the formal notion of the lexicographical order:
It begins with a finite set A, which is known as the alphabet and is completely sequenced. It further means that for a and b (any two symbols which are different and not the same) in A, either a < b or b < a.
Here, the words of A are the finite sequence of symbols from A and including words of length 1 holding a single symbol, words of length 2 with two symbols, and for words of length three, it's 3, and so on. With regards, it also includes the empty sequence ? holding no symbols at all. Thus the lexicographical order for the finite set A can be described as:
Suppose, for the two different worlds of the same length, a=a1a2…ak and b=b1b2…bk is given. Here, two words order depends on the alphabetic order of the symbols in the first place i where two words vary when counting from the beginning of the words, i.e., satisfying the condition a < b if and only if ai < bi within the order of the alphabet A.
If two words have varied in length, the usual lexicographical order pads the word with shorter length with blanks at the end until both words become the same in length, and then the words are compared.
Implementing Lexicographical in Java
As discussed above that lexicographical order can be used either for comparing two strings or sorting the elements. Here, we will discuss both the methods and will Implement each.
Sorting Elements in Lexicographical Order
Arranging words in order is known as lexicographical order or also known as Dictionary order. It means that on applying lexicographical order, the words are ordered alphabetically as per their component alphabets. For sorting a string array in lexicographical order, we have the following two methods:
Method 1: Applying any sorting method
Below is the example code given that will let us understand that how we can perform sorting on elements in Lexicographical order:
public class Main {  
   public static void main(String[] args) {  
      String[] name = { "John","Remo","Mixy","Julie","Ronny"};  
      int n = 5;  
      System.out.println("Before Sorting");  
      for(int i = 0; i < n; i++) {  
         System.out.println(name[i]);  
      }  
      for(int i = 0; i < n-1; ++i) {  
         for (int j = i + 1; j < n; ++j) {  
            if (name[i].compareTo(name[j]) > 0) {  
               String temp = name[i];  
               name[i] = name[j];  
               name[j] = temp;  
            }  
         }  
      }  
      System.out.println("\nAfter performing lexicographical order: ");  
      for(int i = 0; i < n; i++) {  
         System.out.println(name[i]);  
      }  
   }  
}  
Code Explanation:
In the above code, we have created a class Main within which the main () method is created.
A string has been initialized, holding some values to it, and each word will get printed as per for loop.
Then, we have implemented the main logic within another for loop with the help of which we can form the lexicographical order of the words given.
Finally, via for loop, the arranged words are printed on the screen.
Tumblr media
From the output, we can analyze that the given sequence of the words was not in alphabetical order but after applying the lexicographical order code, we can see that every word is sequenced now in alphabetical order.
Method 2: Applying sort () function
The sort () method is available in the Arrays class within the util package.
Below is the example code given that will let us understand that how we can perform sorting on elements in Lexicographical order:
import java.io.*;  
import java.util.Arrays;  
    
class Main {  
    public static void printArray(String str[])  
    {  
        for (String string : str)  
            System.out.print(string + " ");  
        System.out.println();  
    }  
    public static void main(String[] args)  
    {  
        String arr[]  
            = {"John","Harry","Emlie","Ronny","Julie","Mary" };  
  
        Arrays.sort(arr,String.CASE_INSENSITIVE_ORDER);  
        printArray(arr);  
    }  
}  
On executing the above output, we got the below-shown output:
Tumblr media
Comparing two strings using Lexicographical order in Java
For comparing two strings using Lexicographical order, we have the following two methods:
Using compareTo () method
Let's begin one by  one:
Using compareTo () method
Below is an example implementation by which we can compare to strings lexicographically:
import java.lang.*;  
public class StringExample {  
   public static void main(String[] args) {  
      String str1 = "String", str2 = "Comparison";  
       int get_val = str1.compareTo(str2);  
  
      if (get_val < 0) {  
         System.out.println("str1 is greater than str2");  
      } else if (get_val == 0) {  
         System.out.println("str1 is equal to str2");  
      } else {  
         System.out.println("str1 is less than str2");  
      }  
   }  
}  
Code Explanation:
We have created a class StringExample where we have implemented the main () method.
We have initialized two strings, i.e., str1 and str2.
Next, using the compareTo () method, we have compared the strings str1 and str2.
After it, if the get_val value is found less than 0, it means str1 is greater than str2.
Else if the get_val value is equal to 0, it means both str1 and str2 strings are equal.
Else, both the strings str1 is less than str2.
Tumblr media
By creating a user-defined function
Below we have created a user-defined function using which we can compare two strings lexicographically. The code is as follows:
public class StringExample {  
  public static void main(String[] args) {  
      
    String firstString = "Red";  
    String secondString = "Red";  
    String thirdString = "Green";  
    String fourthString = "Yellow";  
    String fifthString = "REdGreen";  
      
    System.out.println("Comparing two strings lexicographically by user defined function");  
      
    System.out.print("\nCompairing firstString ("+firstString+") to the secondString ("+secondString+") returns: ");  
    System.out.println(compareString(firstString, secondString));  
      
    System.out.print("\nCompairing secondString ("+secondString+") to the thirdString ("+thirdString+") returns: ");  
    System.out.println(compareString(secondString, thirdString));  
      
    System.out.print("\nCompairing thirdString ("+thirdString+") to the fourthString ("+fourthString+") returns: ");  
    System.out.println(compareString(thirdString, fourthString));  
      
    System.out.print("\nCompairing fourthString ("+fourthString+") to the firstString ("+firstString+") returns: ");  
    System.out.println(compareString(fourthString, firstString));  
   
    System.out.print("\nCompairing firstString ("+firstString+") to the fifthString ("+fifthString+") returns: ");  
    System.out.println(compareString(firstString, fifthString));  
  }  
  
  public static int compareString(String str, String argString) {  
      
    int lim= Math.min(str.length(), argString.length());  
      
    int k=0;  
    while(k
      if(str.charAt(k)!= argString.charAt(k)) {  
        return (int) str.charAt(k)- argString.charAt(k);  
      }  
      k++;  
    }  
    return str.length() - argString.length();  
  }  
}  
Tumblr media
Code Explanation:
We have created a Java class where we have initialized five strings.
Next, we have compared the first string with the second string, the second to the third-string, and so on..
For making the comparison, we have created a user-defined function compareString () whereby comparing the length and each character of the strings, and we got the results.
Therefore, in this way, we can make use of the lexicographical order in Java for performing such tasks.
1 note · View note
simplexianpo · 4 years ago
Text
Java: Error&Exception - Exceptional features of Java7
##Abnormal
**If there is an error in the code, the program will stop running.**  
Exceptions do not refer to syntax errors, syntax errors, compilation failures, no bytecode files, and no operation at all.
   Exception handling is one of the criteria to measure whether a language is mature. The mainstream languages such as Java, C++ and C# support exception handling mechanisms, which can make programs more fault-tolerant and make program codes more robust(Unfortunately, the traditional C# has no exception handling, and only programs can express abnormal situations by using specific return values of methods, and use if statements to judge normal and abnormal situations.).
 ###There is no shortcoming of exception mechanism
```
1:Using the return value of the method to represent exceptions is limited, and it is impossible to exhaust all exceptions
2:Abnormal flow code and normal flow code are mixed together, which increases the complexity of the program and is poor in readability
3:With the continuous expansion of the system scale, the maintainability of the program is extremely low
```
###Aiming at the defect that there is no exception mechanism with the previous group, the solution is:
```
1:Describe different types of abnormal situations as different classes (called abnormal classes)
2:Separate abnormal flow code from correct flow code
3:Flexible handling of exceptions, if the current method can not handle it, it should be handed over to the caller for handling
```
**Note: Throwable class is a superclass of all errors or exceptions in Java language**
 ###Abnormal conditions (the program will terminate after occurrence)
```
Error : Indicates an error, which generally refers to an irreparable error related to JVM. Such as system crash, memory overflow, JVM error, etc., which are thrown by JVM, we don't need to deal with it.  
Almost all subclasses use Error as the suffix of the class name(However, the designers of the test framework set a large number of exception classes as Error.).  
Exception : It indicates abnormality, which means that an abnormal condition occurs in the program, and the problem can be repaired. Almost all subclasses use Exception as the suffix of the class name.  
If an exception occurs, you can copy the simple class name of the exception to the API for checking.
```
  1:Common Error
```
StackOverflowError : This error is thrown when the application recursion is too deep and memory overflow occurs.
  ```
2:Common Exception
```
1.NullPointerException : Null pointer exception generally means that when an object is null, the method and field of the object are called
2.ArrayIndexOutOfBoundsException : The index of the array is out of bounds (less than 0 or greater than or equal to the array length)
3.NumberFormatException : Abnormal number formatting generally refers to converting strings other than 0~9 into integers
```
If an exception occurs, the program will be terminated immediately, so the exception needs to be handled
1 This method does not handle, but declares throwing, which is handled by the caller of this method
2 Use the statement block of try-catch in the method to handle exceptions
 Use try-catch to catch a single exception with the following syntax
  try{
Write code that may cause exceptions
}catch(ExceptionType e){
Code for handling exceptions
//Log/print exception information/continue to throw exceptions, etc
}
Note: try and catch cannot be used alone and must be used together (try can also be used only with finally)
 ###Get exception information Throwable class method
```
1、String getMessage() : Get the description information and reason of the exception (when prompted to the user, prompt the error reason)
2、String toString() : Get trace stack information of exception (not used)
3、void printStackTrace() : The abnormal trace stack information is printed and output to the console without using System.out.println (); This method includes the type of exception, the cause of the exception, and the location where the exception occurs. In the development and debugging stages, printStackTrace must be used
```
**Note: At present (during development), in the catch statement block, it is necessary to write: e.printStackTrace ()**  
Purpose: To view the specific information of exceptions for convenience of debugging and modification
 Use try-catch to catch multiple exceptions
  try{
Write code that may cause exceptions
}catch(ExceptionTypeA e){
//When a type A exception occurs in try, use this catch to capture the code that handles the exception
//Log/print exception information/continue to throw exceptions, etc
}catch(ExceptionTypeB e){
//When a type B exception occurs in try, use this catch to capture the code that handles the exception
//Log/print exception information/continue to throw exceptions, etc
}
 Note:
```
1.A catch statement can only catch one type of exception. If you need to catch multiple exceptions, you must use multiple catch statements(Enhanced catch after JDK1.7)。
2.Code can only have one type of exception at a moment, only one catch is needed, and it is impossible to have multiple exceptions at the same time.
```
###finally
**Finally statement block: indicates the code that will be executed eventually, with or without exception.**
 When some physical resources (disk files/network connections/database connections, etc.) are opened in the try statement block. Have to be used after the completion of the final closure of open resources.
 ####Two kinds of syntax of finally
```
1:try...finally : At this time, there is no catch to catch exceptions, because at this time, exceptions will be automatically thrown according to the application scenario, and there is no need to handle them by yourself.
2:try...catch...finally : You need to handle exceptions yourself, and eventually you have to shut down resources
Note: finally cannot be used alone
When only the relevant methods of exiting JVM are called out in try or catch, finally will not be executed at this time, otherwise finally will always be executed
```
>System.exit():Exit JVM
 ###Classification of Exception :
```
1、Compilation-time exception: checked exception, which will be checked during compilation. If exception is not handled, compilation fails.  
2、Runtime exception: runtime exception. During runtime, the exception is checked; during compilation, the compiler will not detect the runtime exception (no error is reported).  
Running exception: at compile time, it can be handled or not handled
```
###Exception thrown
```
throw : Used inside the method to return an exception object to the caller, which will end the current method just like return.
  Throws : Used above the method declaration to indicate that the current method does not handle exceptions, but reminds the caller of the method to handle exceptions (throw exceptions).
```
Throw Statement: used inside a method to throw a specific exception
throw new ExceptionClass ("exception information"); //termination method
 ####throw:
Generally, when a method is abnormal, I don't know what the method should return. At this time, I always return an error and continue to throw exceptions upward in the catch statement block.
 Return is to return a value and throw is to return an error to the caller of the method.
 If every method gives up handling exceptions, they are thrown directly through throws declaration, and finally exceptions will run to the main method. If the main method does not handle them at this time, the processing mechanism that continues to be thrown to the bottom layer of JVM is to print the trace stack information of exceptions.
 **Runtime exception, which is handled by default.**
 ###Custom exception class:
There are different exception classes in Java, which represent a specific exception, so there are always some exceptions that SUN has not defined well in the development, and it is necessary to define exception classes according to the exceptions of its own business.
  ####How to define exception classes:
```
Method 1: customize an exception class to be checked: customize the class and inherit from java.lang.Exception
Method 2: customize a runtime exception class: customize the class and inherit from java.lang.RuntimeException
```
 #####Exception translation:
When the subsystem at the top level doesn't need to care about a drama at the bottom, the common way is to capture the original exception, convert it into a new exception of different types, and then throw a new exception.
  #####Abnormal chain:
Packaging the original exception into a new exception class, thus forming an orderly arrangement of multiple exceptions, which is helpful to find the root cause of generating exception classes.
  Unusual new features of Java7 (Android doesn't use Java7 and supports Java5/Java6 syntax)
 ```
1:Enhanced throw
2:Multiple anomaly capture
3:Automatic resource shutdown
```
>It is more accurate to handle thrown Exceptions in Java7, and no longer use exception declaration to throw them in general
 ### Principles for handling exceptions:
```
1:Exceptions can only be used in abnormal situations, and the existence of try-catch will also affect performance
2:It is necessary to provide explanatory documents for exceptions, such as java.doc If an exception is customized or a method throws an exception, it should be recorded in the document comments
3:Avoid anomalies as much as possible
4:The granularity of exceptions is very important. A try-catch block should be defined for a basic operation. Don't put hundreds of lines of code into a try-cathc block for simplicity
5:Exception handling in a loop is not recommended, and exceptions should be captured outside the loop (try-catch is used outside the loop)
6:Use RuntimeException type as much as possible for custom exceptions
```
###Running order of statement blocks that catch exceptions:
  public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println(testMethod());
    }
    static int testMethod() {
        int t = 1;
        try {
            System.out.println("Enter the try statement block----t:" + t);
            t++;
            System.out.println(t / 0);
            System.out.println("Leave the try statement block----t:" + t);
            return t;
        } catch (ArithmeticException e) {
            System.out.println("Enter ArithmeticException----t:" + t);
            t++;
            System.out.println("Exit ArithmeticException----t:" + t);
            return t;
        } catch (Exception e) {
            System.out.println("Enter Exception----t:" + t);
            t++;
            System.out.println("Exit Exception----t:" + t);
            return t;
        } finally {
            System.out.println("Enter the finally statement block----t:" + t);
            t = 10;
            System.out.println("Leave the finally statement block----t:" + t);
            return t;
        }
    }
}
 Output results are:
  Enter the try statement block----t:1
Enter ArithmeticException----t:2
Exit ArithmeticException----t:3
Enter the finally statement block----t:3
Leave the finally statement block----t:10
10
0 notes