Automation QA Testing Course Content

Showing posts with label DataTypes. Show all posts
Showing posts with label DataTypes. Show all posts

Java DataTypes

 DataTypes:


Datatype specifies the size and type of values that can be stored in an identifier.


 Primitive datatype                                             NonPrimitive datatype                             


 boolean                                                   String  
 char array
 byte enum
 short interface,
                                                                         class
 int
 long
 float
 double
 we can store single value.                                                      you can store multiple values.

What are the Primitive Data Types in Java?

At a high level, there are two types of data in Java. There are the "primitives types" and the "non-primitive" or "reference types".

Primitive types store values. For example, int is a primitive type and it stores an integer value.

A reference type, on the other hand, stores the reference to a memory location where a dynamic object is being stored.

There are eight primitive data types in Java.

TYPEEXPLANATION
byte8-bit signed integer within the range of -128 to 127
short16-bit signed integer within the range of -32,768 to 32,767
int32-bit signed integer within the range of -2147483648 to 2147483647
long64-bit signed integer within the range of -9223372036854775808 to 9223372036854775807
floatsingle-precision 32-bit floating point within the range of 1.4E-45 to 3.4028235E38
doubledouble-precision 64-bit floating point within the range of 4.9E-324 to 1.7976931348623157E308
booleanIt can be either true or false
charsingle 16-bit Unicode character within the range of \u0000 (or 0) to \uffff (or 65,535 inclusive)

Yeah yeah I know the table looks scary but don't stress yourself. You don't have to memorize them.

You will not need to think about these ranges very frequently, and even if you do, there are ways to print them out within your Java code.

However, if you do not understand what a bit is, I would recommend this short article to learn about binary.

You've already learned about declaring an integer in the previous section. You can declare a byteshort, and long in the same way.

Declaring a double also works the same way, except you can assign a number with a decimal point instead of an integer:

public class Main {

	public static void main(String[] args) {
		double gpa = 4.8;
		
		System.out.println("My GPA is " + gpa + ".");

	}
}

If you assign an int to the double, such as 4 instead of 4.8, the output will be 4.0 instead of 4, because double will always have a decimal point.

Since double and float are similar, you may think that replacing the double keyword with float will convert this variable to a floating point number – but that's not correct. You'll have to append a f or F after the value:

public class Main {

	public static void main(String[] args) {
		float gpa = 4.8f;
		
		System.out.println("My GPA is " + gpa + ".");

	}
}

This happens because, by default, every number with a decimal point is treated as a double in Java. If you do not append the f, the compiler will think you're trying to assign a double value to a float variable.

boolean data can hold either true or false values.

public class Main {

	public static void main(String[] args) {
		boolean isWeekend = false;
		
		System.out.println(isWeekend); // false

	}
}

As you can imagine, false can be treated as a no and true can be treated as a yes.

Booleans will become much more useful once you've learned about conditional statements. So for now, just remember what they are and what they can hold.

The char type can hold any Unicode character within a certain range.

public class Main {

	public static void main(String[] args) {
		char percentSign = '%';
		
		System.out.println(percentSign); // %

	}
}

In this example, you've saved the percent sign within a char variable and printed it out on the terminal.

You can also use Unicode escape sequences to print out certain symbols.

public class Main {

	public static void main(String[] args) {
		char copyrightSymbol = '\u00A9';
		
		System.out.println(copyrightSymbol); // ©

	}
}

The Unicode escape sequence for the copyright symbol, for example, is \u00A9 and you can find more Unicode escape sequences on this website.

Among these 8 types of data, you'll be working with intdoubleboolean, and char majority of the time.

What is Type Conversion or Casting?

Type conversion in Java can be either "implicit" or "explicit". When the compiler converts a smaller type of data to a larger one automatically, it's known as an implicit or narrowing type conversion.

public class Main {

	public static void main(String[] args) {
		int number1 = 8;
		double number2 = number1;
		
		System.out.println(number2); // 8.0
	}

}

Since a double is larger than an integer, the compiler could easily perform the conversion. If you try to do the reverse however, you'll face the following error from the compiler:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from double to int

	at operators.Main.main(Main.java:7)

When performing an implicit conversion, the flow of conversion should be as follows:

widening-conversion

You can of course go from a short to a double, for example, skipping the others in between.

You can also go from smaller data types to larger ones. That's called an explicit or widening type conversion.

package datatypes;

public class Main {

	public static void main(String[] args) {
		double number1 = 8.5;
		int number2 = (int) number1;
		
		System.out.println(number2); // 8
	}

}

Previously you've seen that if you try to convert a larger data type to a smaller one, the compiler complains. But when you add the (int) cast operator explicitly, you show the compiler who's boss.

In doing so, you lose a part of your data. If you change the initial double number from 8.5 to just 8.0, you'll not lose any information. So whenever you're performing an explicit conversion, be careful.

You can also convert a char to an int as follows:

public class Main {

	public static void main(String[] args) {
		char character = 'F';
		int number = character;
		
		System.out.println(number); // 70
	}

}

70 is the ASCII code for the character F – that's why the output was like this. If you'd like to learn more about ASCII codes, my colleague Kris Koishigawa has written an excellent article on the topic.

The flow of conversion in this case will be the opposite of what you've seen already.

narrowing-conversion

I'd suggest you to experiment by converting various values from one type to another and see what happens. This will deepen your understanding and make you confident.

 boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
 boolean b=true;
 boolean b1=false;
 boolean bn;
 default value for boolean:false;
 int x=20;
 int y=10;
 = assignment operator
 == comparision operator
 conditional operators:>(greater than),<(less than),>=(greater than or equal to),<=(less than or equalto),==(equal)
NOTE: if we use conditional operators between numbers, the result will be boolean value[true or false];
  boolean b2=x>y;20>10-->
  boolean b3=x<y;//20<10-->
  boolean b4=x==y; //20==10-->
   int i=x+y;//20+10-->30
   LOGICAL OPERATORS: AND(&&) OR(||) !=(NOTEQUAL)
   boolean b5=b&&b1;
   boolean b6=b||b1;
   boolean b7=b!=b1;



char:it is used to store single char in a memory location.The value should be enclosed within
   single quotes.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

   char c='D';
   char c1='a';
   char c2='$';
   char c3=' ';
   char c5='5';
   char c4='a3'; -->this is wrong because two characters are included.
   default value for char is:'\u0000' (unicode)
   char occupies 16 bit of memory(2 bytes) 1 byte=8 bits
 Integers:   to store integer type of data use byte,short,int and long
   
  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

  • byte b4=5;

  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

  •   short s=1;

  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigneddivideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

  •  int i=10;  //32 bit of memory

  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigneddivideUnsigned etc to support arithmetic operations for unsigned long.

     long l=324242343453454L; //64 bit of memory


Decimal Values:
   
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

  •   float f=3.6F;

  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

    double d=23423423.234234242;

 Why we will get Typemismatch error?
 1)lefthandside and right hand side datatype is not same
2)lefthndside variable memory size  is smaller than right hand side variable memory size 
How to solve the typemismatch error?
by using typecasting

  Typecasting:when you are assigning bigger memory variable value to lower memory variable, you will loose the data,
   without loosing the data typecast to the right side variable by inserting left side datatype inside the paranthesis()

  Type casting:

It is just a process of converting the value of one data type,  classs or interface into another data type, class or interface
   Syntax: 
   i)datatype variablename=(leftside datatype)biggermemoryvariablename/value;

  ii) interface1 variable1=interface2variable; //typemismatcherror;

   to avoid typemismatch error--apply typecasting.
    interface1 variable=(leftsideinterface)interface2;
interface1 variable=(interface1)interface2;

Example::

int i=50;
short s1=i; //without type cast you will get an error(memory sizes are different,so convert int into short format)

//now apply the typecasting

short s1=(short)i;

float f=3.5F;

int i3=f; //typemismatch error.
int i3=(int)f;(memory sizes are same but datatype is different thats why need to apply typecasting, converting float value into int datatype value)
 i3=3

When we don't need typecasting

short s3=5;
int i2=s3;

char c='A';


int i=c;
(A ascii value=65)
-----------------------------------------------------------------------------------

String:a group of characters is called string.

The String type lets you store lines of text, also known as 'strings'."
Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";String objects are immutable, which means that once created, their values cannot be changed
Examples:

String s="selenium";
String s1="webdriver";

how to join two strings??

You can join strings together with a plus sign (+). Look at these examples."
1)When we use '+' operator between strings, + operator will act as concatination(Joining) operator.
remember that when you add strings and numbers, the result is always a string."
string+string=string
string+number=string
number+string=string
2)When we use '+' operator between numbers, the + operator will act as addition operator[sum up]
2+4=6


    String s3=s+s1;

          ="selenium"+"webdriver"; ="seleniumwebdriver";
String st ="selenium"+" "+"webdriver"
(or)
s+" "+s1;
String st="selenium webdriver";

String s4=s+23;

         ="selenium23";
String s5=s+2+3;-->selenium2+3
="selenium23";
Note:after/before string all + operator act as concatination operator
String s6=s+(2+3);-->s+5
="selenium5";

String s7=2+3+s;-->5+s
         ="5selenium";
String s8="2"+"3"+s;-->"23"+s==>
="23selenium";
System.out.println("s8 value is:"+s8);--s8 value is:23selenium
System.out.println("s8 value is:"+"s8");-->s8 value is:s8
System.out.println("s8");--s8
System.out.println(s8); -->23selenium
String s9=s+(4+"3");-->s+"43"-->"selenium43";
String s10=s+("2"+(5+4))-->s+("2"+9)-->s+"29"-->"selenium29";
-------------------------------------------------------------------------

What are Wrapper Classes in Java?

Wrapper classes can wrap around primitive datatypes and turn them into reference types. Wrapper classes are available for all eight primitive data types.

PRIMITIVE TYPEWRAPPER CLASS
intInteger
longLong
shortShort
byteByte
booleanBoolean
charCharacter
floatFloat
doubleDouble

You can use these wrapper classes as follows:

public class Main {
    public static void main (String[] args) {
        Integer age = 27;
        Double gpa = 4.8;

        System.out.println(age); // 27
        System.out.println(gpa); // 4.8
    }
}

All you have to do is replace the primitive data type with the equivalent wrapper class. These reference types also have methods for extracting the primitive type from them.

For example, age.intValue() will return the age as a primitive integer and the gpa.doubleValue() will return the GPA in a primitive double type.

There are such methods for all eight datatypes. Although you'll use the primitive types most of the time, these wrapper classes will be handy in some scenarios we'll discuss in a later section.