#how to convert string to integer 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
terroratorium · 1 month ago
Text
A trivial math question
Question
I have a trivial math question, although things might get tricky in Java. Given two variables, one of type Integer, and the second of type Short. When I add them and cast the result to a String object, then what happens? Does it throw a class cast exception in this particular case?
Answer
Of course, it won't throw a class cast exception. Compilers or a Java course can help to understand that. I recommend testing it out in The Java Shell tool (JShell). It's a tool available in modern Java. As one can see, it wouldn't even compile because no integer can be cast to a String. Those two variables sum to an integer, and therefore can't be cast to a String.
| Welcome to JShell -- Version 17.0.10 | For an introduction type: /help intro jshell> Short one = 1; one ==> 1 jshell> Integer two = 2; two ==> 2 jshell> String three = (String)(one + two); | Error: | incompatible types: int cannot be converted to java.lang.String | String three = (String)(one + two); | ^---------^
The same can be shown with a Java class.
public class TypeTest { public static void main(String []args) { Short one = 1; Integer two = 2; String three = (String)(one + two); } }
Let's try to compile it, and we'll see the compile-time error.
javac TypeTest.java TypeTest.java:6: error: incompatible types: int cannot be converted to String String three = (String)(one + two); ^ 1 error
The expression can be converted from an integer to a string by wrapping using 'String.valueOf()'. Another way is to concatenate the result with an empty string. Here's how it looks in JShell.
| Welcome to JShell -- Version 17.0.10 | For an introduction type: /help intro jshell> Short one = 1; one ==> 1 jshell> Integer two = 2; two ==> 2 jshell> String three = String.valueOf(1 + 2); three ==> "3" jshell> three = one + two + ""; three ==> "3"
1 note · View note
tpointtech · 2 months ago
Text
"Mastering string compareTo: How Strings Really Stack Up in Java"
Comparing two strings might sound like a basic task, but when it comes to programming—especially in Java—there’s more happening under the hood. Whether you’re sorting a list of names, validating user input, or organizing data alphabetically, the method string compareTo is your trusty sidekick.
In this blog, we’ll unpack how the compareTo method works, what it really compares, and when to use it in real-world scenarios. No code required—just a clear and practical understanding of one of Java’s most essential string tools.
Tumblr media
What Is string compareTo All About?
At its core, string compareTo is a method used to compare two strings lexicographically—that means it checks how they stack up in dictionary order. This method belongs to the String class in Java and returns an integer that tells you the result of the comparison.
But here’s where it gets interesting: it doesn’t just say "equal" or "not equal." Instead, it tells you how two strings differ in order, giving you valuable information you can use in sorting, decision-making, and data processing.
Breaking Down the CompareTo Results
When you compare two strings using string compareTo, Java returns one of three possible outcomes:
Zero (0): The strings are exactly the same.
A positive number: The first string is lexicographically greater than the second.
A negative number: The first string is lexicographically less than the second.
So when you see a result like -3 or 4, it’s not about the actual number—it’s about the sign (negative, zero, or positive) that matters most.
Lexicographical Comparison: What Does That Really Mean?
"Lexicographical" might sound fancy, but it’s basically how words are ordered in the dictionary. Java compares strings character by character, based on their Unicode values.
Let’s imagine comparing “Apple” to “Banana”:
“A” comes before “B” in the alphabet.
Therefore, "Apple".compareTo("Banana") will return a negative number.
This rule applies even if the strings are almost identical. For example:
"Code" vs "Coder" → The shorter one comes first if all earlier characters match.
It’s like comparing two paths in a forest: you walk together until one path splits off—whichever turns first determines which one is “greater” or “less.”
When and Why You’d Use string compareTo
You might be wondering: where does this comparison method actually come in handy? Here are a few common use cases:
1. Sorting Strings
Whether you’re building a contact list or sorting categories alphabetically, string compareTo helps establish the order. Most sorting algorithms under the hood rely on such comparisons to figure out which string should come first.
2. Validating Input
Need to check if a user typed the exact phrase you're expecting? Using string compareTo is one way to verify input matches your criteria without relying on basic equality checks alone.
3. Creating Custom Sorting Logic
In more advanced scenarios, you might sort strings based on specific business rules. For example, ignoring case or placing certain words before others. While compareTo gives you a default behavior, it can be extended with custom logic when needed.
Things to Keep in Mind
As helpful as string compareTo is, here are a few nuances to remember:
Case Sensitivity Matters: "apple" and "Apple" will not be considered equal. The method is case-sensitive by default.
Null Safety: Avoid comparing strings that might be null, as calling compareTo on a null reference will throw an exception.
Consistency Counts: Always use a consistent comparison strategy, especially when dealing with sorted data structures or search functions.
If you need to compare strings without case sensitivity, many developers opt to convert both strings to lowercase or uppercase before comparing them.
Alternatives and Enhancements
Sometimes, the basic string compareTo isn’t quite enough. For example, if you want to:
Ignore case: Use a method designed for case-insensitive comparison.
Handle locales and special characters: Use a more advanced comparison mechanism like Collator for culturally aware sorting.
But in most situations, string compareTo provides exactly what you need in a lightweight and reliable way.
Final Thoughts: Comparing the Right Way
String comparison may seem simple on the surface, but understanding how methods like string compareTo work gives you greater control over how your application behaves. It's one of those hidden gems in programming—subtle, powerful, and essential in the right hands.
Next time you find yourself sorting, filtering, or validating text in your Java programs, remember this: knowing how strings stack up can make all the difference.
With a solid grasp of string compareTo, you’re well on your way to writing cleaner, smarter, and more predictable code.
0 notes
leetcode1 · 4 months ago
Video
youtube
leetcode 8 : atoi java solution
LeetCode Problem 8, titled "String to Integer (atoi)," challenges you to implement the `atoi` function, which converts a string to a 32-bit signed integer. The function must handle leading whitespace, optional signs (+/-), and stop converting when it encounters a non-numeric character. It should also manage overflows, returning the maximum or minimum 32-bit signed integer value when the result exceeds these bounds. This problem tests your ability to parse strings while considering various edge cases, such as invalid input formats and boundary conditions. It's an excellent exercise for improving string manipulation skills and understanding how to implement robust error handling in software development.
0 notes
learnwithcadl123 · 8 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 · 9 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
tccicomputercoaching · 2 years ago
Text
Computers store all values ​​using bits (binary numbers). A bit can represent two values, and the value of a bit is usually said to be either 0 or 1.
Tumblr media
To create a variable, you need to tell Java its type and name. Creating a variable is also called variable declaration. When you create a primitive variable, Java reserves enough bits in memory for that primitive type and maps that location to the name you use. We need to tell Java the type of the variable, because Java needs to know how many bits to use and how to represent the value.
All three different basic types are represented by binary numbers (binary numbers consisting of the digits 0 and 1), but in different ways. To practice converting between decimal and binary numbers, see:
When you declare a variable, a memory location (a contiguous number of bits) is reserved for variables of that type and a name is associated with that location. Integers get 32 ​​bits of space, double precision numbers get 64 bits of space, and boolean values ​​can be represented with only 1 bit, but the amount of space is not fixed by the Java standard.
Java Programming Language contains following topics at TCCI:
Basic Introduction to Java, Object Oriented Programming, Basic Data types and Variables, Modifier Types, Operators, Loop controls, Decision Making, Arrays and String, Methods, Inheritance, Interface, Package, Polymorphism, Overriding, Encapsulation, Abstraction, Exception, Inner class, File
Course Duration: Daily/2 Days/3 Days/4 Days
Class Mode: Theory With Practical
Learn Training: At student’s Convenience
TCCI provides the best training in Java through different learning methods/media is located in Bopal Ahmedabad and ISCON Ambli Road in Ahmedabad.
For More Information:                                    
Call us @ +91 9825618292
Visit us @ http://tccicomputercoaching.com
0 notes
sagar-jaybhay · 6 years ago
Text
Know About JavaScript Array
New Post has been published on https://is.gd/MNT2z6
Know About JavaScript Array
Tumblr media
Arrays In JavaScript
An array is a collection and it is zero-indexed.  The meaning of this is the first element is at index zero and the last element is at index of array length -1 position.
The array in JavaScript has length property which returns the size of that array.
Example:
var array = []; console.log("Array Length -- "+ array.length);
Tumblr media
var array = new Array(100); console.log("Array Length -- "+ array.length);
In this example we only initialize the array and we are not adding any element in array. If you see the output you will see we initialize at 100 and length is also 100.
Tumblr media
How to retrieve first and last element in array?
var array = [100,200,300] console.log("First Element -- " +array[0]); console.log("Last Element -- " + array[array.length-1]); document.write("Array Is " + array+"<br/>"); document.write("First Element -- " + array[0] + "<br/>"); document.write("Last Element -- " + array[array.length - 1] + "<br/>");
Tumblr media
Different ways to declare Array in JavaScript
Declaring and populating array at the same time
Var array=[10,20,30]; Console.log(array);
Declaring array with array constructor: in this method we declare array with array constructor and then populate this array with the index. In JavaScript the array are not fixed length array type in other languages like c#,java this will grow dynamically even though they will declared with fixed length.
var constructor_array = new Array(2); constructor_array[0] = 10; constructor_array[1] = 20; constructor_array[3] = 30; console.log(constructor_array); console.log("Second Array Length - "+constructor_array.length);
Tumblr media
Push and Pop methods of JavaScript Array:
There are 2 methods to add element in array below is basic method where we can assign value to array index variable.
document.writeln("<br/>"); for (var i = 0; i < 10; i++) var val = (i + 1) * 2; myarray[i] = val;
In this code, we adding values from 0 to 9 index and always point to remember the array index start with 0.
To print these elements in array again we use an array with index to print like below.
for (var i = 0; i < 10; i++) document.writeln(myarray[i]); document.writeln("<br/>");
Below Is complete code to add elements in array and display on a page
var myarray = []; document.writeln("<H4> Showing Elements In Array Regular way</H4>"); document.writeln("<br/>"); for (var i = 0; i < 10; i++) var val = (i + 1) * 2; myarray[i] = val; document.writeln('myarray[' + i + '] =' + val); document.writeln("<br/>"); document.writeln("<H4> Showing Elements In Array</H4>"); document.writeln("<br/>"); for (var i = 0; i < 10; i++) document.writeln(myarray[i]); document.writeln("<br/>");
The output of code like below
Tumblr media
Now we will see the push and pop method using the same strategy
Push Method:
 This method adds a new item to the end of array and using this length of the array is changed.
for (var i = 0; i < 10; i++) var val = (i + 1) * 2; myarray.push(val);
Pop Method:
It will remove the last element of an array and also this method change the length of an array.
for (var i = 0; i < 10; i++) document.writeln(myarray.pop(i));
Complete code is below
var myarray = []; document.writeln("<H4> Adding Elements In Array Push and Pop</H4>"); document.writeln("<br/>"); for (var i = 0; i < 10; i++) var val = (i + 1) * 2; myarray.push(val); document.writeln('myarray[' + i + '] =' + val); document.writeln("<br/>"); document.writeln("<H4> Showing Elements In Array</H4>"); document.writeln("<br/>"); for (var i = 0; i < 10; i++) document.writeln(myarray.pop(i)); document.writeln("<br/>");
The output of the above code is like below
Tumblr media
Shift and Unshift Method of an array in JavaScript
Unshift method:
This method is like a push method in the array means it adds a new item in array but the difference is that push method adds an element at last of an array and unshift adds elements at the beginning of an array.
var myarray = [4,3]; myarray.unshift(10); document.writeln('myarray[] =' + myarray); // myarray[] =10,4,3
Shift Method:
This method is alike of pop method but it removes the item from the beginning of an array .
var myarray = [10,4,3]; document.writeln(myarray.shift()); // 10
complete code of this
var myarray = [4,3]; document.writeln("<H4> Adding Elements In Array Using Shift and UnShift</H4>"); document.writeln("<br/>"); myarray.unshift(10); document.writeln('myarray[] =' + myarray); document.writeln("<br/>"); document.writeln("<H4> removing Elements In Array</H4>"); document.writeln("<br/>"); document.writeln(myarray.shift()); document.writeln("<br/>");
The output of above code is below
Tumblr media
Mutator Methods in JavaScript:
In JavaScript there are several methods which can be used with array object in JavaScript. In which some methods modify the array object while another method did not modify that array object. The methods which modify the array object is mutator methods and which not modify the object is called non-mutator methods.
Examples of non-mutator methods below:
Contains, indexOf,Length
Examples of mutator methods like
Push
Pop
Unshift
Shift
Reverse
Sort
Splice
Sort Method of Array:
It will sorts elements in array. By default sort method sort the values by converting them into strings and then it will compare these strings.
This will work well for the string but not for numbers.
var array = ["Sagar", "Jaybhay", "Ram", "Lakhan"]; document.writeln("Before sort an array :==> "+array); array.sort(); document.writeln("<br/>"); document.writeln("<br/>"); document.writeln("After sort the array :==> "+array);
Output of above code is looks like below
Tumblr media
For Number see below code and output
var array = [10,1,12,11,3,2]; document.writeln("Before sort an array :==> " + array); array.sort(); document.writeln("<br/>"); document.writeln("<br/>"); document.writeln("After sort the array :==> " + array);
the output of this code
Tumblr media
If you simply try to sort a numeric array using the sort() method it will not work, because the sort() method sorts the array elements alphabetically. But, you can still sort an array of integers correctly through utilizing a compare function, as shown in the following example:
var array = [10,1,12,11,3,2]; document.writeln("Before sort an array :==> " + array); array.sort(function(a, b) ); document.writeln("<br/>"); document.writeln("<br/>"); document.writeln("After sort the array :==> " + array);
the output of the above code is
Tumblr media
Now how compare function works in array sort function
Array.sort(function(a,b)return a-b)
The outcome of this inside function is only 3 types of output
Positive:- it means a is greater than b
Negative:- it means a is smaller than b
Zero:- it means both are equal
This will sort the array in ascending manner but if you want to sort array in descending manner you need to apply reverse function after that.
var array = [10, 1, 12, 11, 3, 2]; document.writeln("Before sort an array :==> " + array); array.sort(function (a, b) return a - b; ).reverse(); document.writeln("<br/>"); document.writeln("After sort the array :==> " + array);
or you can simply make a change in compare function like below change position of a and b in return statement.
Tumblr media
Methods in array elements
Methods Description concat() It returns a new array object that contains two or more merged arrays. copywithin It copies the part of the given array with its own elements and returns the modified array. every() It determines whether all the elements of an array are satisfying the provided function conditions. fill() It fills elements into an array with static values. filter() It returns the new array containing the elements that pass the provided function conditions. find() It returns the value of the first element in the given array that satisfies the specified condition. findIndex It returns the index value of the first element in the given array that satisfies the specified condition. forEach It invokes the provided function once for each element of an array. includes It checks whether the given array contains the specified element. indexOf It searches the specified element in the given array and returns the index of the first match. join() It joins the elements of an array as a string. lastIndexOf It searches the specified element in the given array and returns the index of the last match. map() It calls the specified function for every array element and returns the new array pop() It removes and returns the last element of an array. push() It adds one or more elements to the end of an array. reverse It reverses the elements of given array. shift() It removes and returns the first element of an array. slice() It returns a new array containing the copy of the part of the given array. sort() It returns the element of the given array in a sorted order. splice() It add/remove elements to/from the given array. unshift It adds one or more elements in the beginning of the given array.
Filter Method in JavaScript array:
The filter() method creates a new array and populates that array with all elements which meets the condition which is specified in callback function.
Synatx:
Array.filter(callbackfunction[,arg])
Callback function: It is required in filter function and it gets called for each element of array. If the function returns true, the element is kept else not.
Arg: it is optional and it is object to which this keyword is referred in callback function.
Filter mehod calls the callback function every time for each element in array. Suppose call back function returns false for every element in array then the length of an array is 0;
Callback Function Syntax:
 Function callbackfunction(value,index,array)
Value- is value of array element
Index:- index position of elements in array
Array:- source array object
var array = [10, 20, 21, 11, 9, 122, 23, 31, 13, 221, 22, 321, 412, 123]; document.writeln("orignal array:- " + array); document.writeln("<br/>"); function isOdd(value,index,array) if (value % 2 != 0) return true; else return false; document.writeln("<br/>"); document.writeln("filtered array :-"+array.filter(isOdd));
the output of the above code is below image
Tumblr media
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
pcmiral · 3 years ago
Text
Nodejs print
Tumblr media
#Nodejs print how to
#Nodejs print update
#Nodejs print code
A global console instance configured to write to process.stdout and process.stderr. Many cases this will be in Postscript format. A Console class with methods such as console.log(), console.error(), and console.warn() that can be used to write to any Node.js stream. rverĪ job is a readable stream containing the document to be printed. printer.jobsĪn array of all jobs handled by the printer. groups - An array of IPP attribute groupsĮxplanation of the different operation types.operationId - The id of the IPP operation.reverse is an array method: it takes an array and reverses its content.Var fs = require ( 'fs' ) var Printer = require ( 'ipp-printer' ) var printer = new Printer ( 'My Printer' ) printer. In our first example we will see how much memory is used by a very basic method: reverse(). Could some one please suggest: a) How I could obtain country value from the res. I have looked at the questions on this topic, but none could help.
#Nodejs print code
Testing reverse() memory usage for a small array In the below code (running on Node JS) I am trying to print an object obtained from an external API using JSON.stringify which results in an error: TypeError: Converting circular structure to JSON. stdout is a writable stream to print log or info output. external is, according to the documentation, the memory used by "C++ objects bound to JavaScript objects managed by V8"Īrmed with the knowledge we are ready to see some examples. Creates a new Console with one or two writable stream instances. Notes: duplex is case sensitive, so be careful to write correctly.'paperSize' refers to size of sheet to print on if you want to print on a paper with custom dimensions, pass 'Custom.WidthxHeight' where Width and Height are integer dimensions in hundredths of inch.
heapUsed is the actual memory used during the execution of our process List of supported extensions can be found here.
There are 28 other projects in the npm registry using printer. Start using printer in your project by running npm i printer.
heapTotal is the total size of the allocated heap Latest version: 0.4.0, last published: 3 years ago.
rss stands for Resident Set Size, it is the total memory allocated for the process execution.
MemoryUsage returns an object with various information: rss, heapTotal, heapUsed, external: Process is a global Node.js object which contains information about the current Node.js process, and it provides exactly what we were searching for: the memoryUsage() method.
#Nodejs print update
Get the java versions using this command from cmd:- java -version Or Update java to the latest versions. Download Node.js for macOS by clicking the 'Macintosh Installer' option.
#Nodejs print how to
We know what the Resident Set is and we also know that the Heap is what we're looking for: now we need to find out how much heap is used by a given Node.js process. Backend Web Server apace/tomacat/Node etc. If you dont have Node.js installed, you’ll see something like the following: The following steps will show you how to install Node.js: Go to the Node.js Downloads page. Sounds complicated? We need to focus only on the heap for now, so don't worry if you can't grasp all the terminology right now! Querying the Node.js heap Hopefully the following illustration will clarify the concept: The Resident Set contains also the actual Javascript code (inside the Code segment) and the Stack, where all the variables live. You can think of it as of a big box which contains some more boxes. The heap is part of something bigger though: a running Node.js process store all its memory inside a Resident Set. node js printing how to code print in javascript on print complete function javascript print en javascript how to print in javsacript how to print using node printer using nodejs print dom node nw.js print how do you print in javascript nodejs printing string in js no of ways to print in javascript window print method javascript can you print. A Node.js app run in a single process, without creating a new thread for every request. It allows you to run JavaScript on the server. Node.js is an open source server environment. What is Node.js Node.js is a tool for JavaScript framework, it is used for developing server-based applications. The heap is a memory segment used for storing objects, strings and closures. Before starting node.js one should have a basic knowledge of javascript. How does Node.js organizes the memory?Ī blog post won't be enough to explain all the machinery: you should just be concerned about the heap for now so let's start by breaking down the basics. To follow along you need a basic understanding of Javascript and a Node.js installation.
How to get information about the memory of a Node.js process.
Tumblr media
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
vbdrita · 3 years ago
Text
Totalspaces default number of spaces
Tumblr media
#Totalspaces default number of spaces code
The algorithm for creating a postfix expression is as follows: The program should read the expression into StringBuffer infix, and use one of the stack classes implemented in this chapter to help create the postfix expression in StringBuffer postfix. The postfix version of the preceding infix expression is (note that no parenthesis are needed) Write class InfixToPostfixConverter to convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers such as
#Totalspaces default number of spaces code
In a later exercise, you will discover that code you write in this exercise can help you implement a complete working compiler. In the next exercise, you will write a Java version of the postfix expression evaluation algorithm. In this exercise, you will write a Java version of the infix-to-postfix conversion algorithm. Each algorithm uses a stack object in support of its operation, and in each algorithm the stack is used for a different purpose. Each of these algorithms requires only a single left-to-right pass of the expression. To evaluate a complex infix expression, a compiler would first convert the expression to postfix notation, and then evaluate the postfix version of the expression. The preceding infix expressions would appear in postfix notation as 3 4 + and 7 9 /, respectively. Computers "prefer" postfix notation in which the operator is written to the right of its two operands. Humans generally write expressions like 3 + 4 and 7 / 9 in which the operator ( + or / here) is written between its operands–this is called infix notation. In this and the next exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. The program should ignore spaces and punctuation.Ģ2.12 Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code. The program should calculate the sum of the elements and the floating-point average of the elements.Ģ2.9 Write a program that creates a linked list object of 10 characters, then creates a second list object containing a copy of the first list, but in reverse order.Ģ2.10 Write a program that inputs a line of text and uses a stack object to print the line reversed.Ģ2.11 Write a program that uses a stack to determine if a string is a palindrome (i.e., the string is spelled identically backward and forward). Method merge of class ListMerge should receive references to each of the list objects to be merged, and should return a reference to the merged list object.Ģ2.8 Write a program that inserts 25 random integers from 0 to 100 in order into a linked list object. Class ListConcat should include method concatenate that takes references to both list objects as arguments and concatenates the second list to the first list.Ģ2.7 Write a program that merges two ordered list objects of integers into a single ordered list object of integers. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.Ģ2.6Write a program that concatenates two linked list objects of characters. Answers are provided for those exercises whose exercise number is a hyperlink. Included below are short-answer and programming exercises.
Tumblr media
0 notes
courtgreys · 3 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
inlarn · 4 years ago
Text
Basic hello world program in java
Write a java program to print a number from the user
Java program to add two numbers taking input from user
Leap year or not program in java using if-else
Swapping of two numbers in java with temporary variable
Odd or even program in java using a mod operator
Vowel or consonant in java using if else
Java program to find largest of three numbers using nested if
Write a program to print first ten natural numbers in java
Write a program to find factorial of a number using for loop in java
Palindrome string program in java using scanner
Program to check whether the number is prime or not in java
Java program to find Armstrong number using while loop
Java program for a calculator using switch case
Java program to calculate percentage and average
Write a java program to print multiplication table using for loop
Print the sum of the natural numbers program in java using for loop
Write a java program to convert temperature from Fahrenheit to celsius degree
Write a java program to convert temperature from Celsius to Fahrenheit
Java program to find HCF and LCM of two numbers
Java program to print the area of circumference of a circle
Write a java program to print the length and perimeter of a rectangle
Java program to print ASCII value of all alphabets
Java program to print decimal number to binary
Java program to print decimal to octal conversion
Java program to print hexadecimal to decimal number conversion
Octal to hexadecimal conversion program in java
Java program to conversion hexadecimal to decimal number
Java program to print the upper case to lower case alphabets
Java program to print two multiply binary numbers with solution
Java program to find the sum of digits of a number using recursion function
Java program to swap two numbers using bitwise xor operator
Java program to find product of two numbers using recursive function
Write a java program to find the reverse of a given number using recursion
Write a java program to accept two numbers and check which is same or not
Java program to increment by 1 all the digits of a given integer
Java program to print the number positions in list of digits
Write a java program to convert numbers into years, weeks and days
Write a java program to print the ip address
Java program to check whether entered character is uppercase or lowercase
Write a program illustrate use of various boolean operators in java
Java program to print the number entered by the user using for loop
Write a java program to check whether the given number is divisible by 5
Write a java program to take a number and return list of its digits
Java program to print the two digits of the year
Write a java program for atm machine
Java program to find the second biggest and smallest number in the array
Write a java program to sort the names in ascending order
Write a java program to increment every element of the array by one
Java program for banking ticket system using if-else statement
Java program to find which department has highest placement program
Write a java program to find my lucky number or not
Credit score program in java for shop
Java program to count the number of pencils for student
Java program to find numerology number
Java program to calculate uber cost and discount rate
Java program to calculate land price with land area
Java program to calculation the air conditioner capacity for invertor and non invertor
Java program to kindergarten school kids
Java program to calculate cubic capacity cc in bikes
Java program to find the odd or even in the box challenge
Java program to create a login page with username and password
Java code for car parking management system
Java program to find the middle element of the string
Java program to find the cubes of an n natural numbers
Java program to print weekdays using a switch statement
Java program to solve quadratic equation using if-else
Java program calculation to fill the bucket with the water mug
Method Overloading in Java to Find Arithmetic Sum of 2 or 3 or 4 Variables by Passing Argument
Write a java program to print the nested methods to perform mathematical operations
Write a program to concatenate two string in java
How to print semicolon in java program without using it
Write a java program to find the largest number in an array
Write a program to find second largest number in an array in java
Write a java program to find the odd or even number in the array
Write a java program to add element in user-specified position using array
Write a java program to delete an element from an array list at the specified index
Write a java program to arrange strings in alphabetical order
Write a java program to split an array in a specific position
Write a array program to calculate average and sum in java
Write a program to calculate electricity bill in java
Find out duplicate number between 1 to n numbers in java
Program in java to print the pie value(pi)
Java program to print the element using calling methods in the same class
Java program to change the element position in right direction using single dimension array
Write a single dimension array in a java program to modify the element located in the leftwards direction
Write a java program to delete or erase the element in the array in a exact location
Transpose matrix java program in java in a single matrix
Java program to pay and calculate mortgage, loan and insurance payment
Java program to find the length of the array and string a single program
Fibonacci series program in java using recursion and looping statements
Java program to print reverse right-angled triangle of numbers
Pyramid pattern program in java using asterisk
Java program to print mirrored right triangle star pattern
Java program to print the pascal triangle using star
Left triangle using star pattern program in java
Java program to print pyramid pattern of numbers
Program to print the diamond pattern program using numbers in java
Java program to print pascal’s number of rows
Java program to print the triangle pattern program using numbers
Java program to print triangle pattern program using a symbol
Java program to print diamond pattern of numbers
Java program to print a right angle triangle pattern program using for loop
Java program pattern program to triangle using 100 numbers
Write a program to print the down arrow pattern in java
Java pattern programs to print the star in between of the numbers
Java program to print stars and number pyramid in a single pattern program
Java program to print the bubble sort using for loop
Merge sort program in java with output
Quick sort program in java taking first element as pivot
Insertion sort program in java using while loop
Java program to print the heap sort algorithm using for loop
Java program to print the radix sort using while loop
Write a java program to print binary search program using while loop
Java program to print the ascending order using for loop
Descending order program in java using for loop
Java program to print the selection sort using array elements
Write a java program to create a singly linked list and display the element
Write a java program to merge three singly linked list elements
Java program to delete the linked list elements from a singly
Write a java program to count the linked list element in the nodes
0 notes
globalmediacampaign · 4 years ago
Text
MySQL and UUIDs
In ALTER TABLE for UUID we discuss currently proper way to store and handle UUID in MySQL. Currently it works, even in a performant way, but it still hurts. It should not. Definition of UUID The RFC 4122 defines various types of UUID, and how they are being formatted for presentation and as a bit field on the wire. As this document was written bei Leach and Salz, among others, RFC 4122 UUIDs are also called “Leach-Salz UUIDs” (for example in the Java Documentation). There are other UUID variants, used in other systems (NCS, and Microsoft “backwards compatibility”). A RFC 4122 UUID is a special 128 bit long value (“16 octets”). It is supposed to be laid out like this: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | time_low | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | time_mid | time_hi_and_version | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |clk_seq_hi_res | clk_seq_low | node (0-1) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | node (2-5) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+The high bits in clk_seq_hi_res define the variant, and anything starting with the bit sequence 10 is a RFC 4122 compliant UUID. The high nibble in time_hi_and_version defines the RFC 4122 Type (or version), the algorithm used. RFC 4122 itself defines versions 1 to 5 (version 0 is unused). There is an expired draft that defines a version 6, which is specifically designed to use a primary key for databases. It uses the same timestamp value as Type 1, but stores the bytes so that ordering by creation time is preserved. It also relaxes the requirements on the node field, officially allowing different sources for bits than the MAC address. Sample implementations are available in various languages. UUIDs are all over the place in Windows and also in Java. Databases have to handle them as “application generated primary keys”. That’s why they are important and should be treated with some attention. Handling UUID in MySQL 8 MySQL provides functions to generate UUIDs, to check if a thing is a validly formatted string that looks like a UUID, and to convert UUIDs to 128 bit bitstrings and back. The latter two functions have a special flag to improve performance with InnoDB. This flag is by default off. No attempt is made to automatically do the right thing dependent on the UUID type. UUID function The MySQL function UUID() returns a RFC 4122 Type 1 UUID. mysql> select uuid_to_bin(uuid()) as uuid; +------------------------------------+ | uuid | +------------------------------------+ | 0x80462D3C96AB11EB94BBBA2278F258E1 | +------------------------------------+ 1 row in set (0.00 sec)Formatted like in the RFC, we get the following values: 80462D3C 96AB 1 1EB 9 4 BB B A22 78F258E1Specifically, the clk_seq_hi_res contains the variant value, 9, and the time_hi_and_version contains the version, 1. According to the RFC, the variant 9 = 1001 = 10x (a RFC 4122 compliant UUID). Of the Versions defined in RFC 4122, it is Version 1 or Type 1, “The time-based version in this document”. The generation algorithm is defined in section 4.2 of that RFC. So a MySQL generated UUID is always a RFC 4122 Type 1 (time based) UUID. Java generated UUID values Compare with the Java UUID Class: We have randomUUID(), returning a Type 4 UUID and nameUUIDFromBytes() for Type 3 and a generic Constructor that takes any 128 bit value. So what we get from Java is likely name based or random UUIDs generated by the application. Name based UUIDs are fixed for a fixed name, so they pose no problem when used with MySQL as a primary key. Random UUIDs are completely random. There is nothing to optimize for MySQL here. Neither is a good choice to use as a kind of application controlled distribiuted primary key. Based on the reasoning in ALTER TABLE for UUID, Java developers that are using UUID for this purpose would be well advised to implement and use a Type 1 UUID. It seems that such an implementation is not available by default as part of java.lang.util, but other implementations exist. IS_UUID() function The IS_UUID() predicate returns 1 for all strings that can be parsed as a UUID. That is, it checks for one of three ways to write the UUID, and that it contains only valid hex digits in the places that actually contain data. No attempt is made to validate any of the bits. Code is here, and the actual parsing happens here. UUID_TO_BIN() function MySQL allows three ways to write UUIDs, as a 128 bit hex string (6ccd780cbaba102695645b8c656024db), as a 128 bit hex string with dashes in the right places (6CCD780C-BABA-1026-9564-5B8C656024DB) and as a 128 bit hex string with dashes in the right places and enclosed in curly braces ({6CCD780C-BABA-1026-9564-5B8C656024DB}). This is not a particular dense packing of data for storage. The UUID_TO_BIN() function takes any of these strings and returns a VARBINARY(16) for storage. The function has an optional second parameter, the swap_flag. When applied to a Type 1 UUID, the time bytes are being swapped around so that chronological ascending UUIDs from the same node are also having numerically ascending values. This optimizes storage with InnoDB. Type 1 UUID: It is recommended you define UUID columns as VARBINARY(16) and use theUUID_TO_BIN(uuid_string, 1) function to store data. Type 6 UUID: You should use UUID_TO_BIN(uuid_string, 0) to store Type 6 UUIDs, because Type 6 has been specifically created to avoid the swapping of time bytes around. Other types: These do not profit from swapping, so also use UUID_TO_BIN(uuid_string, 0). BIN_TO_UUID function The inverse function to UUID_TO_BIN is BIN_TO_UUID(). It needs the same swap_flag value as has been used at write time in order to unpack the data correctly. It should hurt less This all should hurt less. MySQL should have a native UUID column type, which stores data internally in a VARBINARY(16) (or BINARY(16)). It should accept all three notations as input (hex string, with dashes, with curly braces and dashes). It should return a hex string without dashes or curlies. It should validate variant and type (version), allowing Types 1 to 6. It should auto-convert (swap) data for Type 1, but not for any other type. There should be a formatting function that turns a hex string without dashes into a UUID string with dashes, or a UUID string with dashes and curlies. That is, I want to be able to mysql> create table u ( u uuid not null primary key, dummy integer ); mysql> insert into u values (uuid(), 1); mysql> select u from uG u: 6ccd780cbaba102695645b8c656024db mysql> select format_uuid(u, 0) as u from uG u: 6CCD780C-BABA-1026-9564-5B8C656024DB mysql> select format_uuid(u) as u from uG u: 6CCD780C-BABA-1026-9564-5B8C656024DB mysql> select format_uuid(u, 1) as u from uG u: {6CCD780C-BABA-1026-9564-5B8C656024DB}and internally, this is stored as 0x1026BABA6CCD780C95645B8C656024DB, because variant is RFC 4122 and Type is 1. For any other Type of the RFC 4122 the internal swapping does not happen. Trying to store anything that is not a RFC 4122 variant is an error. Trying to store anything that is a RFC 4122 variant but not a Type 1 to 6 is an error. https://isotopp.github.io/2021/04/06/mysql-and-uuids.html
0 notes
simplexianpo · 5 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