You are on page 1of 25

Chapter 2

Basics in Java Programming


Statements and Expressions
A statement is the simplest thing you can do in Java; a statement forms a single
Java operation.

All the following are simple Java statements:

int i = 1;

import java.awt.Font;

System.out.println(―This motorcycle is a ―+ color + ― ― + make);

m.engineState = true;

Statements sometimes return values—for example, when you add two numbers
together or test to see whether one value is equal to another. These kind of
statements are called expressions.

The most important thing to remember about Java statements is that each one
ends with a semicolon. Forget the semicolon and your Java program won‘t
compile.

Java also has compound statements, or blocks, which can be placed wherever a
single statement can. Block statements are surrounded by braces ({}).

Variables and Data Types


Variables are locations in memory in which values can be stored. They have a
name, a type, and a value. Before you can use a variable, you have to declare it.
After it is declared, you can then assign values to it.

Java actually has three kinds of variables: instance variables, class variables, and
local variables.

Instance variables, are used to define attributes or the state for a particular
object. Class variables are similar to instance variables, except their values apply

Page 1 of 25
to all that class’s instances (and to the class itself) rather than having different
values for each object.

Local variables are declared and used inside method definitions, for example,
for index counters in loops, as temporary variables, or to hold values that you need
only inside the method definition itself. They can also be used inside blocks ({}).

Once the method (or block) finishes executing, the variable definition and its value
cease to exist. Use local variables to store information needed by a single method
and instance variables to store information needed by multiple methods in the
object.

Although all three kinds of variables are declared in much the same ways, class
and instance variables are accessed and assigned in slightly different ways from
local variables.

Note: Unlike other languages, Java does not have global variables—that is,
variables that are global to all parts of a program. Instance and class variables can
be used to communicate global information between and among objects.
Remember, Java is an object-oriented language, so you should think in terms of
objects and how they interact, rather than in terms of programs.

Declaring Variables
To use any variable in a Java program, you must first declare it. Variable
declarations consist of a type and a variable name:

int myAge;

String myName;

boolean isTired;

Variable definitions can go anywhere in a method definition (that is, anywhere a


regular Java statement can go), although they are most commonly declared at the
beginning of the definition before they are used:

public static void main (String args[]) {

int count;

String title;
Page 2 of 25
boolean isAsleep;

...

You can string together variable names with the same type:

int x, y, z;

String firstName, LastName;

You can also give each variable an initial value when you declare it:

int myAge, mySize, numShoes = 28;

String myName = ―Laura‖;

boolean isTired = true;

int a = 4, b = 5, c = 6;

If there are multiple variables on the same line with only one initializer (as in the
first of the previous examples), the initial value applies to only the last variable in a
declaration. You can also group individual variables and initializers on the same
line using commas, as with the last example, above.

Local variables must be given values before they can be used (your Java
program will not compile if you try to use an unassigned local variable). For this
reason, it‘s a good idea always to give local variables initial values. Instance and
class variable definitions do not have this restriction (their initial value depends on
the type of the variable: null for instances of classes, 0 for numeric variables, ‗\0‘
for characters, and false for booleans).

Local variables:
 Local variables are declared in methods, constructors, or blocks.

Page 3 of 25
 Local variables are created when the method, constructor or block is entered and
the variable will be destroyed once it exits the method, constructor or block.

 Access modifiers cannot be used for local variables.

 Local variables are visible only within the declared method, constructor or block.

 Local variables are implemented at stack level internally.


 There is no default value for local variables so local variables should be declared
and an initial value should be assigned before the first use.

Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope
is limited to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}

This would produce the following result:

Puppy age is: 7


Example:
Following example uses age without initializing it, so it would give an error at the
time of compilation.
public class Test{
public void pupAge(){
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
Page 4 of 25
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}

This would produce the following error while compiling it:

Test.java: 4: variable number might not have been initialized


age = age + 7;
^
1 error

Instance variables
 Instance variables are declared in a class, but outside a method, constructor or any
block.
 When a space is allocated for an object in the heap, a slot for each instance variable
value is created.

 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.

 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
 Instance variables can be declared in class level before or after use.

 Access modifiers can be given for instance variables.

 The instance variables are visible for all methods, constructors and block in the
class. Normally, it is recommended to make these variables private (access level).
However visibility for subclasses can be given for these variables with the use of
access modifiers.
 Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned
during the declaration or within the constructor.

Page 5 of 25
 Instance variables can be accessed directly by calling the variable name inside the
class. However within static methods and different class (when instance variables
are given accessibility) should be called using the fully qualified name
. ObjectReference.VariableName.
Example:
import java.io.*;

public class Employee{


// this instance variable is visible for any child class.
public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName){
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal){
salary = empSal;
}

// This method prints the employee details.


public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]){


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This would produce the following result:

name : Ransika
Page 6 of 25
salary :1000.0
Class/static variables:
 Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.

 Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final and static. Constant variables
never change from their initial value.

 Static variables are stored in static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.

 Default values are same as instance variables. For numbers, the default value is 0;
for Booleans, it is false; and for object references, it is null. Values can be assigned
during the declaration or within the constructor. Additionally values can be
assigned in special static initializer blocks.

 Static variables can be accessed by calling with the class name


. ClassName.VariableName.
 When declaring class variables as public static final, then variables names
(constants) are all in upper case. If the static variables are not public and final the
naming syntax is the same as instance and local variables.

Example:
import java.io.*;

public class Employee{


// salary variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
Page 7 of 25
public static final String DEPARTMENT = "Development ";

public static void main(String args[]){


salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}

This would produce the following result:

Development average salary:1000


Note: If the variables are accessed from an outside class the constant should be
accessed as Employee.DEPARTMENT

Notes on Variable Names

Variable names in Java can start with a letter, an underscore (_), or a dollar sign
($). They cannot start with a number. After the first character, your variable names
can include any letter or number. Symbols, such as %, *, @, and so on, are often
reserved for operators in Java, so be careful when using symbols in variable names.

In addition, the Java language uses the Unicode character set. Unicode is a
character set definition that not only offers characters in the standard ASCII
character set, but also several million other characters for representing most
international alphabets. This means that you can use accented characters and other
glyphs as legal characters in variable names, as long as they have a Unicode
character number above 00C0.

Finally, note that the Java language is case-sensitive, which means that uppercase
letters are different from lowercase letters. This means that the variable X is
different from the variable x, and a roseis not a Roseis not a ROSE. Keep this in
mind as you write your own Java programs and as you read Java code other people
have written.
Page 8 of 25
By convention, Java variables have meaningful names, often made up of several
words combined. The first word is lowercase, but all following words have an
initial uppercase letter:

Button theButton;

long reallyBigNumber;

boolean currentWeatherStateOfPlanetXShortVersion;

Variable Types
In addition to the variable name, each variable declaration must have a type, which
defines what values that variable can hold. The variable type can be one of three
things:

 One of the eight basic primitive data types


 The name of a class
 An array
The eight primitive data types handle common types for integers, floating-point
numbers, characters, and boolean values (true or false). They‘re called primitive
because they‘re built into the system and are not actual objects, which makes them
more efficient to use. Note that these data types are machine-independent, which
means that you can rely on their sizes and characteristics to be consistent across
your Java programs.

There are four Java integer types, each with different ranges of values (as listed in
Table 2.1). All are signed, which means they can hold either positive or negative
numbers. Which type you choose for your variables depends on the range of values
you expect that variable to hold; if a value becomes too big for the variable type, it
is truncated.

Table 2.1 Integer types.

Type Size Range


Byte 8 bits –128 to 127
Short 16 bits –-32,768 to 32,767

Int 32 bits –2,147,483,648 to


2,147,483,647
Page 9 of 25
Long 64 bits –9223372036854775808 to
9223372036854775807

Floating-point numbers are used for numbers with a decimal part. Java floating-
point numbers are compliant with IEEE 754 (an international standard for defining
floating-point numbers and arithmetic). There are two floating-point types:
float(32 bits, single-precision) and double(64 bits, double-precision).

The char type is used for individual characters. Because Java uses the Unicode
character set, the char type has 16 bits of precision, unsigned.

Finally, the boolean type can have one of two values, true or false. Note that
unlike in other C-like languages, boolean is not a number, nor can it be treated as
one. All tests of boolean variables should test for true or false.

In addition to the eight basic data types, variables in Java can also be declared to
hold an instance of a particular class:

String LastName;

Font basicFont;

OvalShape myOval;

Each of these variables can then hold only instances of the given class. As you
create new classes, you can declare variables to hold instances of those classes
(and their subclasses) as well.

Technical Note: Java does not have a typedef statement (as in C and C++). To
declare new types in Java, you declare a new class; then variables can be declared
to be of that class‘s type.

Assigning Values to Variables


Once a variable has been declared, you can assign a value to that variable by using
the assignment operator =:

size = 14;

tooMuchCaffiene = true;

Page 10 of 25
Java Identifiers
All Java components require names. Names used for classes, variables and
methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).

 After the first character identifiers can have any combination of characters.

 A key word cannot be used as an identifier.


 Most importantly identifiers are case sensitive.

 Examples of legal identifiers: age, $salary, _value, __1_value


Examples of illegal identifiers: 123abc, -salary

Java Keywords
The following list shows the reserved words in Java. These reserved words may
not be used as constant or variable or any other identifier names.

Abstract Assert Boolean break


Byte Case Catch char
Class Const Continue default
Do Double Else enum
Extends Final Finally float
For Goto If implements
Import Instanceof Int interface
Long Native New package
Private Protected Public return
Short Static Strictfp super
Switch Synchronized This throw
Throws Transient Try void
Page 11 of 25
Volatile While

Constants
 A constant is an identifier that is similar to a variable except that it holds the
same value during its entire existence

 As the name implies, it is constant, not variable

 The compiler will issue an error if you try to change the value of a constant

 In Java, we use the final modifier to declare a constant

final int MIN_HEIGHT = 69;

 Constants are useful for three important reasons

 First, they give meaning to otherwise unclear literal values

 For example, MAX_LOAD means more than the literal 250

 Second, they facilitate program maintenance

 If a constant is used in multiple places, its value need only be updated


in one place

 Third, they formally establish that a value should not change, avoiding
inadvertent errors by other programmers

Strings

Strings, which are widely used in Java programming, are a sequence of characters.
In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

Page 12 of 25
In this case, "Hello world!" is a string literal—a series of characters in your code
that is enclosed in double quotes. Whenever it encounters a string literal in your
code, the compiler creates aString object with its value—in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword
and a constructor. The String class has thirteen constructors that allow you to
provide the initial value of the string using different sources, such as an array of
characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };


String helloString = new String(helloArray);
System.out.println(helloString);

The last line of this code snippet displays hello.

Note: The String class is immutable, so that once it is created a String object
cannot be changed. The String class has a number of methods, some of which will
be discussed below, that appear to modify strings. Since strings are immutable,
what these methods really do is create and return a new string that contains the
result of the operation.

String Length

Methods used to obtain information about an object are known as accessor


methods. One accessor method that you can use with strings is the length() method,
which returns the number of characters contained in the string object. After the
following two lines of code have been executed, len equals 17:

String palindrome = "Dot saw I was Tod";


int len = palindrome.length();

A palindrome is a word or sentence that is symmetric—it is spelled the same


forward and backward, ignoring case and punctuation. Here is a short and
inefficient program to reverse a palindrome string. It invokes
the String method charAt(i), which returns the ith character in the string, counting
from 0.

public class StringDemo {


Page 13 of 25
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];

// put original string in an


// array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}

// reverse array of chars


for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}

String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}

Running the program produces this output:

doT saw I was toD

To accomplish the string reversal, the program had to convert the string to an array
of characters (first for loop), reverse the array into a second array
(second for loop), and then convert back to a string. The String class includes a
method, getChars(), to convert a string, or a portion of a string, into an array of
characters so we could replace the first for loop in the program above with

palindrome.getChars(0, len, tempCharArray, 0);


Concatenating Strings

The String class includes a method for concatenating two strings:

Page 14 of 25
string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in

"Hello," + " world" + "!"

which results in

"Hello, world!"

The + operator is widely used in print statements. For example:

String string1 = "saw I was ";


System.out.println("Dot " + string1 + "Tod");

which prints

Dot saw I was Tod

Such a concatenation can be a mixture of any objects. For each object that is not
a String, its toString() method is called to convert it to a String.

Note: The Java programming language does not permit literal strings to span lines
in source files, so you must use the + concatenation operator at the end of each line
in a multi-line string. For example:
String quote =
"Now is the time for all good " +
"men to come to the aid of their country.";

Breaking strings between lines using the + concatenation operator is, once again,
very common in print statements.

Page 15 of 25
Creating Format Strings

You have seen the use of the printf() and format() methods to print output with
formatted numbers. The String class has an equivalent class method, format(), that
returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that
you can reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " +


"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar, intVar, stringVar);

you can write

String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);

Comments in Java
Java supports single-line and multi-line comments very similar to c and c++. All
characters available inside any comment are ignored by Java compiler.

public class MyFirstJavaProgram{

/* This is my first java program.


* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args){


Page 16 of 25
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

Java Literals
A literal is a source code representation of a fixed value. They are represented
directly in the code without any computation.

Literals can be assigned to any primitive type variable.

For example:

byte a = 68;
char a = 'A'

byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base
16) or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using
these number systems for literals. For example:

int decimal = 100;


int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes. Examples of
string literals are:

"Hello World"
"two\nlines"
"\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example:

char a = '\u0001';
String a = "\u0001";

Page 17 of 25
Java language supports few special escape sequences for String and char literals as
well. They are:

Notation Character represented


\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t Tab
\" Double quote
\' Single quote
\\ Backslash
\ddd Octal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxxx)

Numeric Operations
The operations that can be done on numeric data include the standard algebraic
operations: addition (+), subtraction (-), multiplication (*), division (/), as well as
the modulus (%) operator. Note that in Java, the multiplication symbol is * and not
x. The arithmetic operators are binary operators, meaning that they each take two
operands.

Table 2.2 The standard arithmetic operators in Java


Operation Operator Java Algebra
Addition + x+2 x+2
Subtraction - m–2 m–2
Multiplication * m *2 2m or 2 x m
Division / x/y x ÷ y or
Modulus % x%y x modulo y (for integers x and y)

Page 18 of 25
Although these operations should seem familiar, there are some important
differences between their use in algebra and their use in a Java program. Consider
the following list of expressions:

3 / 2 ==> value 1 An integer result


3.0 / 2.0 ==> value 1.5 A floating-point result
3 / 2.0 ==> value 1.5 A floating-point result
3.0 / 2 ==> value 1.5 A floating-point result

In each of these cases we are dividing the quantity 3 by the quantity 2. However,
different results are obtained depending on the type of the operands involved.
When both operands are integers, as in (3/2), the result must also be an integer.
Hence, (3/2) has the value 1, an integer. Because integers cannot have a fractional
part, the 0.5 is simply discarded. Integer division (/) always gives an integer result.
Thus, the value of (6/2) is 3 and the value of (7/2) is also 3. Because 3.5 is not an
integer, the result of dividing 7 by 2 cannot be 3.5.

Integer division gives an integer result

Operator Precedence

The built-in precedence order for arithmetic operators is shown in Table 2.3.
Parenthesized expressions have highest precedence and are evaluated first. Next
come the multiplication, division, and modulus operators, followed by addition and
subtraction. When we have an unparenthesized expression that involves both
multiplication and addition, the multiplication would be done first, even if it occurs
to the right of the plus sign. Operators at the same level in the precedence
hierarchy are evaluated from left to right. For example, consider the following
expression:

Table 2.3 Precedence order of the arithmetic operators


Precedence Order Operator Operation
1 () Parentheses
2 ++ -- Increment, decrement

Page 19 of 25
3 */% Multiplication, division, modulus
4 +- Addition, subtraction
5 <><=>= Relational operators
6 = = != Equality operators

Example:
9+6-3*6/2

In this case, the first operation to be applied will be the multiplication (*), followed
by division (/), followed by addition (+), and then finally the subtraction (-). We
can use parentheses to clarify the order of evaluation. A parenthesized expression
is evaluated outward from the innermost set of parentheses:

Step 1. ( (9 + 6) - ((3 * 6) / 2 ) )
Step 2. ( (9 + 6) - (18 / 2 ) )
Step 3. ( (9 + 6) - 9 )
Step 4. ( 15 - 9 )
Step 5. 6

Parentheses can (and should) always be used to clarify the order of operations in an
expression.

Increment and Decrement Operators

Java provides a number of unary operators that are used to increment or


decrement an integer variable. For example, the expression k++ uses the
increment operator ++ to increment the value of the integer variable k. The
expression k++ is equivalent to the following Java statements:

int k;
k = k + 1;// Add 1 to k and assign the result back to k

The unary ++ operator applies to a single-integer operand, in this case to the


variable k. It increments k's value by 1 and assigns the result back to k. It may be
used either as a preincrement or a postincrement operator. In the expression k++,
Page 20 of 25
the operator follows the operand, indicating that it is being used as a postincrement
operator. This means that the increment operation is done after the operand's value
is used.

Preincrement and postincrement

Contrast that with the expression ++k in which the ++ operator precedes its
operand. In this case, it is used as a preincrement operator, which means that the
increment operation is done before the operand's value is used.

When they are used in isolation, there is no practical difference between k++ and
++k. Both are equivalent to k = k + 1. However, when used in conjunction with
other operators, there is a significant difference between preincrement and
postincrement. For example, in the following code segment,

int j = 0, k = 0; // Initially both j and k are 0


j = ++k; // Final values of both j and k are 1

the variable k is incremented before its value is assigned to j. After execution of


the assignment statement, j will equal 1 and k will equal 1. The sequence is
equivalent to

Precedence order

int j = 0, k = 0; // Initially both j and k are 0


k = k + 1;
j = k; // Final values of both j and k are 1

However, in the following example,

int i = 0, k = 0; // Initially both i and k are 0


i = k++; // Final value of i is 0 and k is 1

the variable k is incremented after its value is assigned to i. After execution of the
assignment statement, i will have the value 0 and k will have the value 1. The
preceding sequence is equivalent to

int i = 0, k = 0; // Initially both i and k are 0


Page 21 of 25
i = k;
k = k + 1; // Final value of i is 0 and k is 1

In addition to the increment operator, Java also supplies the decrement operator --,
which can also be used in the predecrement and postdecrement forms. The
expression -- k will first decrement k's value by 1 and then use k in any expression
in which it is embedded. The expression k-- will use the current value of k in the
expression in which k is contained and then it will decrement k's value by 1. Table
2.4 summarizes the increment and decrement operators. The unary increment and
decrement operators have higher precedence than any of the binary arithmetic
operators.

Table 2.4. Java's increment and decrement operators


Expression Operation Interpretation
j = ++ k Preincrement k = k + 1;j = k;
j = k ++ Postincrement j = k; k = k + 1;
j = --k Predecrement k = k - 1; j = k;
j = k -- Postdecrement j = k; k = k - 1;

Example: Test of prefix and postfix increment operators:

class PrePostFixTest {
public static void main (String args[]) {
int x = 0;
int y = 0;
System.out.println(―x and y are ― + x + ― and ― + y );
x++;
System.out.println(―x++ results in ― + x);
++x;
System.out.println(―++x results in ― + x);
System.out.println(―Resetting x back to 0.‖);
x = 0;
System.out.println(―——————‖);
y = x++;
System.out.println(―y = x++ (postfix) results in:‖);
System.out.println(―x is ― + x);
System.out.println(―y is ― + y);
Page 22 of 25
System.out.println(―——————‖);
y = ++x;
System.out.println(―y = ++x (prefix) results in:‖);
System.out.println(―x is ― + x);
System.out.println(―y is ― + y);
System.out.println(―——————‖);
}
}
Output
x and y are 0 and 0
x++ results in 1
++x results in 2
Resetting x back to 0.
——————
y = x++ (postfix) results in:
x is 1
y is 0
——————
y = ++x (prefix) results in:
x is 2
y is 2
——————

Type Conversion (Casting)


Type conversion, and typecasting, are different ways of, implicitly or explicitly,
changing an entity of one data type into another.

Type casting is treating a value (block of memory) referenced by a variable as


being of a different type than the type the variable is declared as.
Type conversion is actually performing a conversion of that value.

Java supports two types of castings – primitive data type casting and reference
type casting. Reference type casting is nothing but assigning one Java object to
another object. It comes with very strict rules and is explained clearly in Object
Casting. Now let us go for data type casting.
Java data type casting comes with 3 flavors.

1. Implicit casting
2. Explicit casting
Page 23 of 25
3. Boolean casting.
1. Implicit casting (widening conversion)
A data type of lower size (occupying less memory) is assigned to a data type of
higher size. This is done implicitly by the JVM. The lower size is widened to
higher size. This is also named as automatic type conversion.
Examples:

int x = 10; // occupies 4 bytes


double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
In the above code 4 bytes integer value is assigned to 8 bytes double value.

2. Explicit casting (narrowing conversion)


A data type of higher size (occupying more memory) cannot be assigned to a data
type of lower size. This is not done implicitly by the JVM and requires explicit
casting; a casting operation to be performed by the programmer. The higher size is
narrowed to lower size.
double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error
In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises
error. Let us explicitly type cast it.

double x = 10.5;
int y = (int) x;
The double x is explicitly converted to int y. The thumb rule is, on both sides, the
same data type should exist.

3. Boolean casting
A boolean value cannot be assigned to any other data type. Except boolean, all the
remaining 7 data types can be assigned to one another either implicitly or
explicitly; but boolean cannot. We say, boolean is incompatible for conversion.
Maximum we can assign a boolean value to another boolean.
Following raises error.

boolean x = true;
Page 24 of 25
int y = x; // error
boolean x = true;
int y = (int) x; // error
byte –> short –> int –> long –> float –> double

In the above statement, left to right can be assigned implicitly and right to left
requires explicit casting. That is, byte can be assigned to short implicitly but short
to byte requires explicit casting.
Following char operations are possible.

1 public class Demo


2 {
3 public static void main(String args[])
4 {
5 char ch1 = 'A';
6 double d1 = ch1;
7
8 System.out.println(d1); // prints 65.0
9 System.out.println(ch1 * ch1); // prints 4225 , 65 * 65
10
11 double d2 = 66.0;
12 char ch2 = (char) d2;
13 System.out.println(ch2); // prints B
14 }
15 }

Page 25 of 25

You might also like