Pages

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.


How to Use Operators in Java

Operators in programming are certain symbols that tell the compiler to perform certain operations such as arithmetic, relational, or logical operations.

Although there are six types of operators in Java, I won't talk about bitwise operators here. Discussing bitwise operators in a beginner guide can make it intimidating.

What Are the Arithmetic Operators?

Arithmetic operators are the ones that you can use to perform arithmetic operations. There are five of them:

OPERATOROPERATION
+Addition
-Subtraction
*Multiplication
/Division
%Remainder (Modulo/Modulus)

Addition, subtraction, multiplication, and division operations are pretty self-explanatory. Have a look at the following code example to understand:

public class Main {

	public static void main(String[] args) {
		int number1 = 10;
		int number2 = 5;
		
		System.out.println(number1 + number2); // 15
		System.out.println(number1 - number2); // 5
		System.out.println(number1 * number2); // 50
		System.out.println(number1 / number2); // 2
		System.out.println(number1 % number2); // 0

	}

}

Outputs from the first four operations need no explanation. In the last operation, you've performed a modulo/modulus operation using the % symbol. The result is 0 because if you divide 10 by 2, there'll be nothing left (no remainder).

Addition and multiplication operations are quite simple. But, when performing a subtraction, if the first operand is larger than the second operand, the result will be a negative number, just like in real life.

The type of data you're working with makes a difference in the result of division and modulo operations.

public class Main {

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

}

Although the result of this operation should've been 1.6 it didn't happen because in Java, if you divide an integer by another integer, the result will be an integer. But if you change both or one of them to a float/double, everything will be back to normal.

public class Main {

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

}

This principle applies to the modulo operations as well. If both or one of the operands are a float/double, the result will be a float/double.

What Are the Assignment Operators?

You've already worked with the assignment operator in a previous section.

public class Main {

	public static void main(String[] args) {
		// <type> <name> = <value>
		int age = 27;
        
		// prints the age on the terminal
		System.out.println(age);

	}

}

When you use the = symbol to assign a value to a variable, it works as an assignment operator. But, this is not the only form of this operator.

Combining the regular assignment operator with the arithmetic operators, you can achieve different results.

OPERATOROPERATIONEQUIVALENT TO
+=a += ba = a + b
-=a -= ba = a - b
*=a *= ba = a * b
/=a /= ba = a / b
%=a %= ba = a % b

The following code example should make things clearer:

package operators;

public class Main {

	public static void main(String[] args) {
		double number1 = 10;
		double number2 = 5;
		
		number1 += number2;
		
		System.out.println(number1); // 15
	}

}

The other operators work the same. They operate and then assign the resultant value to the left operand.

I could demonstrate the other ones using code but I think if you try them out yourself, you'll get a better understanding. After all, experimentation and practice are the only ways to solidify your knowledge.

What Are the Relational Operators?

Relational operators are used to check the relation between operands. Such as whether an operand is equal to another operand or not.

These relational operators return either true or false depending on the operation you've performed.

There are six relational operators in Java.

OPERATOREXPLANATIONUSAGE
==Is Equal To5 == 8 returns false
!=Is Not Equal To5 != 8 returns true
>Is Greater Than5 > 8 returns false
<Is Less Than5 < 8 returns true
>=Greater Than or Equal To5 >= 8 returns false
<=Less Than or Equal To5 <= 8 returns true

The following code example demonstrates the usage of these operators:

public class Main {

	public static void main(String[] args) {
		double number1 = 10;
		double number2 = 5;
		
		System.out.println(number1 == number2); // false
		System.out.println(number1 != number2); // true
		System.out.println(number1 > number2); // true
		System.out.println(number1 < number2); // false
		System.out.println(number1 >= number2); // true
		System.out.println(number1 <= number2); // false
	}

}

Practical usage of these operators will become much apparent to you once you've learned about conditional statements in a later section.

You can also use these operators with characters.

public class Main {

	public static void main(String[] args) {
		char smallLetter = 'a';
		char capitalLetter = 'A';
		
		System.out.println(smallLetter > capitalLetter); // ???
	}

}

What do you think the output of this code will be? Find out for yourself. Remember the ASCII values of the characters? They play a role in the output of this program.

What Are the Logical Operators?

Imagine a scenario where a program you've made can only be used by people who are 18 and up but not over 40 years old. So the logic should be as follows:

can run the program if ->
	age >= 18 and age <= 40

Or in another scenario, a user has to be a student of your school or member of the library to borrow books. In this case the logic should be as follows:

can borrow books if ->
	isSchoolStudent or isLibraryMember

These logical decisions can be made using logical operators. There are three such operators in Java.

OPERATORUSAGEEXPLANATION
Logical And (&&)age >= 18 && age <= 40Evaluates to true, only if both conditions are true
Logical Or (||)isSchoolStudent || isLibraryMemberEvaluates to true if one of the two or both conditions are true
Not (!)!isLibraryMemberEvaluates to false if the inner condition evaluates to true and vise versa

Let's see these operators in code. First, the logical and operator:

public class Main {

	public static void main(String[] args) {
		int age = 20;
		
		System.out.println(age >= 18 && age <= 40); // true
	}

}

In this case, there are two conditions on either side of the && operator. If and only if both conditions evaluate to true, the and operation evaluates to true.

If the first condition evaluates to false, the computer will not evaluate the rest of the conditions and return false. Because if the first one evaluates to false, then there is no way for the entire operation to evaluate to true.

The logical or operator works similarly, but in this case, if any of the conditions are true then the entire operation will evaluate to true:

public class Main {

	public static void main(String[] args) {
		boolean isSchoolStudent = true;
		boolean isLibraryMember = false;
		
		System.out.println(isSchoolStudent || isLibraryMember); // true
	}

}

If the first condition of a logical or operation evaluates to true, the computer will not evaluate the rest of the conditions and return true. Because if the first condition evaluates to true the operation will evaluate to true regardless of what the other conditions evaluate to.

Finally the not operator evaluates to the opposite of whatever its condition evaluates to. Take a look at the following code example:

public class Main {

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

}

As you can see, the not operator returns the opposite of the given boolean value. The not operator is a unary operator, meaning it operates on a single operand.

public class Main {

	public static void main(String[] args) {
		boolean isLibraryMember = true;
		boolean isSchoolStudent = false;
		
		System.out.println(!isSchoolStudent || isLibraryMember); // true
	}

}

In this example, the not operator turns isSchoolStudent into true, so the operation evaluates to true. However, if you modify the code as follows:

public class Main {

	public static void main(String[] args) {
		boolean isLibraryMember = true;
		boolean isSchoolStudent = false;
		
		System.out.println(!(isSchoolStudent || isLibraryMember)); // false
	}

}

First, the logical or operation will take place and evaluate to true. The not operator will turn it into false.

Although you've used two operands with each operator, you can use as many as you want. You can also mix and match multiple operators together.

public class Main {

	public static void main(String[] args) {
		boolean isSchoolStudent = true;
		boolean isLibraryMember = false;
		int age = 10;
		
		System.out.println(isSchoolStudent || isLibraryMember && age > 18); // ???
	}

}

What do you think the output of this code will be? I'd recommend you find out by yourself. :)

What Are the Unary Operators?

There are some operators that are used with one operand at a time and these are called the unary operators. Although there are five of them, I'll only discuss two.

OPERATOREXPLANATION
Increment (++)Increments a given value by 1
Decrement (--)Decrements a given value by 1

The following code example will demonstrate them nicely:

public class Main {

	public static void main(String[] args) {
		int score = 95;
		int turns = 11;
		
		score++;
		turns--;
		
		System.out.println(score); // 96
		System.out.println(turns); // 10
	}

}

You can also use the operators as prefixes:

public class Main {

	public static void main(String[] args) {
		int score = 95;
		int turns = 11;
		
		++score;
		--turns;
		
		System.out.println(score); // 96
		System.out.println(turns); // 10
	}

}

So far this is simple. But there are some slight differences between the postfix and prefix syntaxes that you need to understand. Look at the following code:

package operators;

public class Main {

	public static void main(String[] args) {
		int score = 95;
		
		
		System.out.println(++score); // 96
		System.out.println(score); // 96
	}

}

This is expected behavior. The prefix decrement operator will work the same. But look what happens if you switch to the postfix version:

package operators;

public class Main {

	public static void main(String[] args) {
		int score = 95;
		
		
		System.out.println(score++); // 95
		System.out.println(score); // 96
	}

}

Confusing, isn't it? What do you think is the actual value of the variable right now? It's 96. Let me explain.

When using the postfix syntax within a print function, the print function encounters the variable first and then increments it. That's why the second line prints out the newly updated value.

In case of the prefix syntax, the function encounters the increment operator first and performs the operation. Then it goes on to printing the updated value.

This little difference may catch you off guard if you're not careful. Or you try to avoid incrementing or decrementing within function calls.



-----------------------------------------------------------------------------

NOTE: refer below link for more details on datatypes
Datatypes concept related Questions?

1)what is a datatype?

2)what are different types of datatypes?

3)declare a variable b & assign with value false?

4)declare a variable & assign with value 10 ?

5)declare a variable& assign  with value $?

6)declare a variable & & assign value 4.5?

7)what is the memory size of char datatype?

8)what is memory size of byte, short, int and long?

9)what is the memory size of float and double?

10)what is typecasting?

11)when you need to do typecasting?

12)What is a String?

13)How can you join two strings s1=”java” and s2=”selenium”?

14)write below expression output?

(5>4)&&(10>4);

(10>20)||(25>15);
15)String class is available in which package?

16)package datatypes;

public class Test {

public static void main(String[] args) {
int num= 10;
long num1 = 0B1010;
System.out.println(num==num1);

}

}
a)true
b)false
--------------------------------------------------------------------------------------------------
package datatypes;

public class Test2 {

public static void main(String[] args) {
int x = 08;
x= x + 2;
System.out.println(x);

}

}

1)Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The literal 08 of type int is out of range 

ii)10
iii)Exception

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.