Showing posts with label int. Show all posts
Showing posts with label int. Show all posts

Monday, 29 May 2023

Convert a string to integer in Python

Using int() function, you can convert a string to an integer in Python.

 

Example

int_var = int(input_str)

 

string_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

int_var = int(input_str)
print('int_var : ', int_var, " type : ", type(int_var))

Output

Enter a string 12345
input_str :  12345  type :  <class 'str'>
int_var :  12345  type :  <class 'int'>

If the input_str contains any non-numeric characters, you will endup in ValueError like below.

Enter a string hello
input_str :  hello  type :  <class 'str'>
Traceback (most recent call last):
  File "/Users/Shared/PycharmProjects/python/python-core/1.introduction/string_to_int.py", line 4, in <module>
    int_var = int(input_str)
ValueError: invalid literal for int() with base 10: 'hello'

We can handle above error situations using try-except block.

 


string_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

try:
    int_var = int(input_str)
    print('int_var : ', int_var, " type : ", type(int_var))
except ValueError as ve:
    print("input string contain non numeric characters. error : ", ve)

Output

Enter a string hello
input_str :  hello  type :  <class 'str'>
input string contain non numeric characters. error :  invalid literal for int() with base 10: 'hello'




Previous                                                 Next                                                 Home

Tuesday, 31 March 2020

Java: Convert int to Long

Approach 1: By explicit casting.
Long result1 = (long) i;

Approach 2: Using 'Long.valueOf' method.
Long result2 = Long.valueOf(i);

Approach 3: Using Integer.longValue().
Integer intObj = i;
Long result3 = intObj.longValue();

Approach 4: Using Long constructor.
Long result4 = new Long(i);

App.java
package com.sample.app;

public class App {

  public static void main(String args[]) {
    int i = 10;

    Long result1 = (long) i;

    Long result2 = Long.valueOf(i);

    Integer intObj = i;
    Long result3 = intObj.longValue();

    Long result4 = new Long(i);

    System.out.println("result1 : " + result1);
    System.out.println("result2 : " + result2);
    System.out.println("result3 : " + result3);
    System.out.println("result4 : " + result4);

  }

}

Output

result1 : 10
result2 : 10
result3 : 10
result4 : 10


You may like

Convert Object to int

Approach 1: Using explicit casting.
int i = (int) obj;

Approach 2: Using intValue() method.
i = ((Integer) obj).intValue();

Approach 3: Using parseInt() method.
i = Integer.parseInt(obj.toString());

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {

  Object obj = 10;

  int i = (int) obj;
  System.out.println("i = " + i);

  i = ((Integer) obj).intValue();
  System.out.println("i = " + i);
  
  i = Integer.parseInt(obj.toString());
  System.out.println("i = " + i);
 }

}

Output

i = 10
i = 10
i = 10



You may like

Wednesday, 11 March 2020

Integer vs int

a. int is a primitive type, whereas Integer is a reference type. More specifically Integer is a wrapper type of int type. Every primitive type in Java has corresponding wrapper type.
         byte has Byte
         short has Short
         int has Integer
         long has Long
         float has Float
         double has Double
         boolean has Boolean
         char has Character

b. Default value of int field is 0, whereas default value of Integer is null.

DemoClass.java
package com.sample.app;

public class DemoClass {
 int primitiveField;
 Integer objField;
}

App.java
package com.sample.app;

public class App {

 public static void main(String[] args) {
  DemoClass demoClass = new DemoClass();

  System.out.println("primitiveVariable : " + demoClass.primitiveField);
  System.out.println("objVariable : " + demoClass.objField);
 }

}

Output
primitiveVariable : 0
objVariable : null

c. By default int variables are mutable (unless you define it with via final modifier), whereas Integer variables are immutable.

d. Since Integer is a reference type, you can use it as a type in collections, but you can’t use int as a type in collecitons.

Example
List<Integer> list = new ArrayList<> ();
Map<Integer, String> map = new HashMap<> ();

e. Integer can allow null values, but int do not allow.

f. Performing Arithmetic operations on ‘int’ are always faster than ‘Integer’.

g. == operator is used to check equality of two ‘int’ variables, where as ‘equals’ method is used to check whether two integer objects has same int value or not.

h. Since ‘int’ is a primitive type, no methods are associated with it. Whereas Integer is a class, methods are associated with it.

Example
Integer i1 = new Integer(10);
i1.intValue();
i1.toString();

You may like

Friday, 31 January 2014

More About primitive types

1. sizes Of primitive data types

Data Type Size (in bytes)
byte 1
short 2
int 4
long 8
float 4
double 8
char 2

boolean: The boolean data type has only two possible values: true and false. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

2. If you are using primitive data types as local variables, then you must initialize the variable before using. Other wise compiler will throw error.

Example
class PrimitiveDeclaration{
 public static void main(String args[]){
  int var1;
  System.out.println(var1);
 }
}

When you tries to compile the above program below error thrown

PrimitiveDeclaration.java:5: error: variable var1 might not have been initialized
 System.out.println(var1);
 ^
1 error

3. Assigning data to compatibility types
Java permits to assign a value of one data type to the value of other if types are compatible. I.e, we can assign a data of float to double, byte to int, char to int etc.,

When you assign a character variable to int variable, then int variables store the Uni code of the variable.

Example
class Compatible{
 public static void main(String args[]){
  char charVar = 'a';
  int intCharVar = charVar;
  byte byteVar = 100;
  short shortVar = byteVar;
  int intVar = shortVar;
  long longVar = intVar;
  float floatVar = longVar;
  double doubleVar = floatVar;
  
  System.out.println(charVar);
  System.out.println(intCharVar);
  System.out.println(byteVar);
  System.out.println(shortVar);
  System.out.println(intVar);
  System.out.println(longVar);
  System.out.println(floatVar);
  System.out.println(doubleVar);
 }
}

Output
a
97
100
100
100
100
100.0
100.0

4. If you are trying to assign data of one type to the other incompatible type compiler will throw error.

Example
class Compatible{
 public static void main(String args[]){
  int intVar = 10;
  boolean a = intVar;
 }
}
While compiling you will get the below error

Compatible.java:6: error: incompatible types
 boolean a = floatVar;
 ^
 required: boolean
 found: float
1 error

5. If you want to assign a higher data type value to compatible lower data type, then you should externally cast it, otherwise compiler will throw an error by saying “possible loss of precision”.

Syntax:  
   dataType value1 = (dataType) value2;

class Compatible{
 public static void main(String args[]){
  double doubleVar = 109.05;
  char ch = doubleVar;
  
  System.out.println(doubleVar);
  System.out.println(ch);
 }
}

while compiling you will get the below error.

Compatible.java:5: error: possible loss of precision
 char ch = doubleVar;
 ^
 required: char 
 found: double
1 error

To solve the above error, we need to cast explicitly like below

class Compatible{ 
 public static void main(String args[]){
  double doubleVar = 109.05;
  char ch = (char)doubleVar;
  
  System.out.println(doubleVar);
  System.out.println(ch);
 } 
}

6. Always assign a value to a float variable by appending “f” to it like below
float floatVar = 10.09f

other wise compiler will throw error.

class Compatible{
 public static void main(String args[]){
  float floatVar = 10.09;
  System.out.println(floatVar);
 }
}

While compiling you will get the below error

Compatible.java:3: error: possible loss of precision
 float floatVar = 10.09;
 ^
 required: float
 found: double
1 error

To solve the above error define the float variable like below
    float floatVar = 10.09f;

Data Types in Java                                                 Operators in Java                                                 Home