Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Unit1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Java Comments

The Java comments are the statements in a program that are not executed by the
compiler and interpreter.

Why do we use comments in a code?


o Comments are used to make the program more readable by adding the details of the
code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the
alternative code.

Types of Java Comments


There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the
widely used and easiest way of commenting the statements.

Single line comments starts with two forward slashes (//). Any text in front of // is
not executed by Java.

Syntax:

1. //This is single line comment  

Let's use single line comment in a Java program.

CommentExample1.java

1. public class CommentExample1 {    
2. public static void main(String[] args) {    
3. int i=10; // i is a variable with value 10  
4. System.out.println(i);  //printing the variable i  
5. }    
6. }    

Output:

10

2) Java Multi Line Comment


The multi-line comment is used to comment multiple lines of code. It can be used to
explain a complex code snippet or to comment multiple lines of code at a time (as it
will be difficult to use single-line comments there).

Multi-line comments are placed between /* and */. Any text between /* and */ is not
executed by Java.

Syntax:

1. /*  
2. This   
3. is   
4. multi line   
5. comment  
6. */    

Let's use multi-line comment in a Java program.

CommentExample2.java

1. public class CommentExample2 {    
2. public static void main(String[] args) {    
3. /* Let's declare and  
4.  print variable in java. */    
5.   int i=10;    
6.     System.out.println(i);    
7. /* float j = 5.9; 
8.     float k = 4.4; 
9.     System.out.println( j + k ); */    
10. }    
11. }    

Output:

10

3) Java Documentation Comment


Documentation comments are usually used to write large programs for a project or
software application as it helps to create documentation API. These APIs are needed
for reference, i.e., which classes, methods, arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The documentation


comments are placed between /** and */.

Syntax:

1. /**  
2. * 
3. *We can use various tags to depict the parameter 
4. *or heading or author name 
5. *We can also use HTML tags   
6. * 
7. */    
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

1. Boolean one = false  

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.

Example:

1. byte a = 10, byte b = -20  

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000  

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:

1. int a = 100000, int b = -200000  
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L  

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f  
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

Example:

1. double d1 = 12.3  

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

Example:

1. char letterA = 'A'  
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a
name of the memory location. It is a combination of "vary + able" which means its
value can be changed.

1. int data=50;//Here data is variable  
Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable
1) Local Variable

A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.

Example to understand the types of variables in java


1. public class A  
2. {  
3.     static int m=100;//static variable  
4.     void method()  
5.     {    
6.         int n=90;//local variable    
7.     }  
8.     public static void main(String args[])  
9.     {  
10.         int data=50;//instance variable    
11.     }  
12. }//end of class   

Java Variable Example: Add Two Numbers


1. public class Simple{    
2. public static void main(String[] args){    
3. int a=10;    
4. int b=10;    
5. int c=a+b;    
6. System.out.println(c);    
7. }  
8. }    

Output:

20

Java Variable Example: Widening


1. public class Simple{  
2. public static void main(String[] args){  
3. int a=10;  
4. float f=a;  
5. System.out.println(a);  
6. System.out.println(f);  
7. }}  

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


1. public class Simple{  
2. public static void main(String[] args){  
3. float f=10.5f;  
4. //int a=f;//Compile time error  
5. int a=(int)f;  
6. System.out.println(f);  
7. System.out.println(a);  
8. }}  

Output:

10.5
10

Java Variable Example: Overflow


1. class Simple{  
2. public static void main(String[] args){  
3. //Overflow  
4. int a=130;  
5. byte b=(byte)a;  
6. System.out.println(a);  
7. System.out.println(b);  
8. }}  

Output:

130
-126

Java Variable Example: Adding Lower Type


1. class Simple{  
2. public static void main(String[] args){  
3. byte a=10;  
4. byte b=10;  
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int  
6. byte c=(byte)(a+b);  
7. System.out.println(c);  
8. }}  

Output:

20

Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -,
*, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -
Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int x=10;  
4. System.out.println(x++);//10 (11)  
5. System.out.println(++x);//12  
6. System.out.println(x--);//12 (11)  
7. System.out.println(--x);//10  
8. }}  

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=10;  
5. System.out.println(a++ + ++a);//10+12=22  
6. System.out.println(b++ + b++);//10+11=21  
7.   
8. }}  

Output:

22
21

Java Unary Operator Example: ~ and !


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=-10;  
5. boolean c=true;  
6. boolean d=false;  
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
9. System.out.println(!c);//false (opposite of boolean value)  
10. System.out.println(!d);//true  
11. }}  

Output:

-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication,
and division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. System.out.println(a+b);//15  
6. System.out.println(a-b);//5  
7. System.out.println(a*b);//50  
8. System.out.println(a/b);//2  
9. System.out.println(a%b);//0  
10. }}  

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10*10/5+3-1*4/2);  
4. }}  

Output:

21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.

Java Left Shift Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10<<2);//10*2^2=10*4=40  
4. System.out.println(10<<3);//10*2^3=10*8=80  
5. System.out.println(20<<2);//20*2^2=20*4=80  
6. System.out.println(15<<4);//15*2^4=15*16=240  
7. }}  

Output:

40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.

Java Right Shift Operator Example


1. public OperatorExample{  
2. public static void main(String args[]){  
3. System.out.println(10>>2);//10/2^2=10/4=2  
4. System.out.println(20>>2);//20/2^2=20/4=5  
5. System.out.println(20>>3);//20/2^3=20/8=2  
6. }}  

Output:

2
5
2

Java Shift Operator Example: >> vs >>>


1. public class OperatorExample{  
2. public static void main(String args[]){  
3.     //For positive number, >> and >>> works same  
4.     System.out.println(20>>2);  
5.     System.out.println(20>>>2);  
6.     //For negative number, >>> changes parity bit (MSB) to 0  
7.     System.out.println(-20>>2);  
8.     System.out.println(-20>>>2);  
9. }}  

Output:
5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true
or false.

1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int c=20;  
6. System.out.println(a<b&&a<c);//false && true = false  
7. System.out.println(a<b&a<c);//false & true = false  
8. }}  

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int c=20;  
6. System.out.println(a<b&&a++<c);//false && true = false  
7. System.out.println(a);//10 because second condition is not checked  
8. System.out.println(a<b&a++<c);//false && true = false  
9. System.out.println(a);//11 because second condition is checked  
10. }}  

Output:

false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true
or false.

1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int c=20;  
6. System.out.println(a>b||a<c);//true || true = true  
7. System.out.println(a>b|a<c);//true | true = true  
8. //|| vs |  
9. System.out.println(a>b||a++<c);//true || true = true  
10. System.out.println(a);//10 because second condition is not checked  
11. System.out.println(a>b|a++<c);//true | true = true  
12. System.out.println(a);//11 because second condition is checked  
13. }}  

Output:

true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and
used a lot in Java programming. It is the only conditional operator which takes three
operands.

Java Ternary Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=2;  
4. int b=5;  
5. int min=(a<b)?a:b;  
6. System.out.println(min);  
7. }}  

Output:

Another Example:

1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=5;  
5. int min=(a<b)?a:b;  
6. System.out.println(min);  
7. }}  

Output:

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign
the value on its right to the operand on its left.

Java Assignment Operator Example


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. int a=10;  
4. int b=20;  
5. a+=4;//a=a+4 (a=10+4)  
6. b-=4;//b=b-4 (b=20-4)  
7. System.out.println(a);  
8. System.out.println(b);  
9. }}  

Output:

14
16

Java Assignment Operator Example


1. public class OperatorExample{  
2. public static void main(String[] args){  
3. int a=10;  
4. a+=3;//10+3  
5. System.out.println(a);  
6. a-=4;//13-4  
7. System.out.println(a);  
8. a*=2;//9*2  
9. System.out.println(a);  
10. a/=2;//18/2  
11. System.out.println(a);  
12. }}  

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. public class OperatorExample{  
2. public static void main(String args[]){  
3. short a=10;  
4. short b=10;  
5. //a+=b;//a=a+b internally so fine  
6. a=a+b;//Compile time error because 10+10=20 now int  
7. System.out.println(a);  
8. }}  

Output:

Compile time error

After type cast:

1. public class OperatorExample{  
2. public static void main(String args[]){  
3. short a=10;  
4. short b=10;  
5. a=(short)(a+b);//20 which is int now converted to short  
6. System.out.println(a);  
7. }}  
Output:

20

Type Casting and Type Conversion:

The two terms type casting and the type conversion are used in a program to


convert one data type to another data type. The conversion of data type is possible
only by the compiler when they are compatible with each other. Let's discuss the
difference between type casting and type conversion in any programming language.

What is a type casting?


When a data type is converted into another data type by a programmer or user while
writing a program code of any programming language, the mechanism is known
as type casting. The programmer manually uses it to convert one data type into
another. It is used if we want to change the target data type to another data type.
Remember that the destination data type must be smaller than the source data type.
Hence it is also called a narrowing conversion.

Syntax:

1. Destination_datatype = (target_datatype) variable;  
2. (data_type) it is known as casting operator  

Target_datatype: It is the data type in which we want to convert the destination


data type. The variable defines a value that is to be converted in the target_data type.
Let's understand the concept of type casting with an example.

Suppose, we want to convert the float data type into int data type. Here, the target
data type is smaller than the source data because the size of int is 2 bytes, and the
size of the float data type is 4 bytes. And when we change it, the value of the float
variable is truncated and convert into an integer variable. Casting can be done with a
compatible and non-compatible data type.
1. float b = 3.0;  
2. int a = (int) b; // converting a float value into integer  

Let's understand the type casting through a C program.

AreaOfRectangle.c

1. #include<stdio.h>  
2. #include<conio.h>  
3. void main()  
4. {  
5.     printf("\n Welcome to Javatpoint tutorials ");  
6.     float x = 3.5, y = 4.5;  // the size of float variable is 4 byte.  
7.     int area; // the size of the int variable is 2 bytes.  
8.     area = (int) x * y; // after conversion the product converts into integer  
9.     printf("\n Area of a Rectangle is : %d", area);  
10.     printf("\n Here, we convert float data type into the Int data type");  
11.     getch();  
12. }  

Output:

What is type conversion?


If a data type is automatically converted into another data type at compile time is
known as type conversion. The conversion is performed by the compiler if both data
types are compatible with each other. Remember that the destination data type
should not be smaller than the source type. It is also known as widening conversion
of the data type.
Let's understand the type conversion with an example.

Suppose, we have an int data type and want to convert it into a float data type.
These are data types compatible with each other because their types are numeric,
and the size of int is 2 bytes which is smaller than float data type. Hence, the
compiler automatically converts the data types without losing or truncating the
values.

1. int a = 20;  
2. Float b;      
3. b = a; // Now the value of variable b is 20.000   /* It defines the conversion of int data type to 
float data type without losing the information. */   

In the above example, the int data type is converted into the float, which has a larger
size than int, and hence it widens the source data type.

Let's understand type conversion through a C program.

1. #include<stdio.h>  
2. #include<conio.h>  
3. void main()  
4. {  
5.     printf("\n Welcome to Javatpoint tutorials ");  
6.     int x = 3, y = 4;  // the size of int variable is 2 byte.  
7.     float area; // the size of float variable is 4 bytes.  
8.     area =  x * y; /* It is a type conversion that automatically converted by the compiler at the 
compile time of a program. */  
9.     printf("\n Area of a Rectangle is : %f", area);  
10.     printf("\n Here, we convert int data type to the float data type");  
11.     getch();  
12. }  
Output:

Difference Between Type Casting and Type Conversion


S.N. Type Casting Type Conversion

1 Type casting is a mechanism in which Type conversion allows a compiler to convert


one data type is converted to another one data type to another data type at the
data type using a casting () operator by a compile time of a program or code.
programmer.

2 It can be used both compatible data type Type conversion is only used with compatible
and incompatible data type. data types, and hence it does not require any
casting operator.

3 It requires a programmer to manually It does not require any programmer intervention


casting one data into another type. to convert one data type to another because the
compiler automatically compiles it at the run
time of a program.

4 It is used while designing a program by It is used or take place at the compile time of a
the programmer. program.

5 When casting one data type to another, When converting one data type to another, the
the destination data type must be destination type should be greater than the
smaller than the source data. source data type.

6 It is also known as narrowing conversion It is also known as widening conversion because


because one larger data type converts to one smaller data type converts to a larger data
a smaller data type. type.

7 It is more reliable and efficient. It is less efficient and less reliable.


8 There is a possibility of data or In type conversion, data is unlikely to be lost
information being lost in type casting. when converting from a small to a large data
type.

9 float b = 3.0; int x = 5, y = 2, c;


int a = (int) b float q = 12.5, p;
p = q/x;

You might also like