JAVA NOTES Chapter 1
JAVA NOTES Chapter 1
Basic syntactical
Constructs in Java
Features of Java:
Simple, Small and Familiar:
Java
Java Compiler Virtual Machine
Program
• No explicit pointer
• Exception handling
• There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java.
• Java and the JVM has been designed to overcome this situation, which would enable the
programs to run in spite of severe environmental changes.
• For example, size of primitive types is fixed , in C programming, int data type occupies
2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture.
However, in java occupies 4 bytes of memory for both 32 and 64-bit architectures in
Java.
• Also, up gradation of OS, processor and changes in the core system resources can all be
the factors which may cause malfunction of program is handled by java.
Multi-threaded:
• Java runtime system contains tools to handles multiple tasks simultaneously.
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once by defining
multiple threads.
• The main advantage of multi-threading is that it doesn't occupy memory for each
thread.
• It shares a common memory area. Threads are important for multi-media, Web
applications, etc.
Portable:
• Java is portable because it facilitates you to carry the Java bytecode to any
platform.
• It doesn't require any implementation.
High-performance:
• Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
• It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed:
• This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Dynamic:
• Using the new keyword is the most popular way to create an object or instance of
the class.
• Syntax :
• Example:
• Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called.
• If the method has no parameters, then the parameter list will be empty.
return value;
Adding a Method to Class Returning a Value:
class Box
class Box
{
{
double width;
double width;
double height;
double height;
double depth;
double depth;
void volume()
double volume()
{
{
System.out.print("Volume is: ");
return width * height * depth;
System.out.println(width * height * depth); }
} }
}
Basic Structure of Java Programs:
• Documentation Section
• Package Statement
• Import Statements
• Interface Statement
• Class Definition
Braces • Two curly brackets {...} are used to group all the commands or
statements, so it is known that the commands belong to that class or
method.
public static void • When main method is declared public, it means that it can also
main be used by code outside of its class.
• The word static used when we want to access a method without
creating its object, so we call the main method, before creating
any class objects.
• The word void indicates that main method does not return a
value.
• main method is starting point for execution of Java program.
String[] args • It is an array where each element of it is a string, which
has been named as "args".
• If your Java program is run through the console, you can
pass input parameter, and main() method takes it as input.
• Then, JVM translates bytecode into native machine code (instructions that a computer's
CPU executes directly).
• Java is a platform-independent language because when you write Java code, it's
ultimately written for JVM but not your physical machine.
• JVM executes the Java bytecode which is platform-independent, so Java is platform-
independent.
Java Environment:
Primary
Memory
Phase 3 Class Loader Class loader
reads .class files
containing bytecodes
from disk and puts
those bytecodes in
Disk memory.
. ..
. .
.
Primary
Memory
Phase 4 Bytecode Verifier Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
restrictions.
. ..
. .
.
Primary
Memory Interpreter reads
Phase 5 Interpreter bytecodes and translates
them into a language that
the computer can
understand, possibly
storing data values as the
program executes.
. ..
. .
.
29
Java Tokens:
• A token is the smallest element of a program that is meaningful to the compiler. Tokens
can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Separators
5. Operators
Keywords:
• These are the pre-defined reserved words in java.
• Each keyword has a special meaning.
• They are always written in lower case.
• Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements
21. import 22. instanceof 23. Int 24. interface 25. long
26. native 27. new 28. Package 29. private 30. protected
31. public 32. return 33. Short 34. static 35. super
36. switch 37. synchronized 38. This 39. throw 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier:
• Java Identifiers are the user-defined names of variables, methods, classes, arrays,
packages, and interfaces.
• Rules while naming the identifiers such as:
✔ Identifiers must begin with a letter, dollar sign or underscore(no digits)
✔ Identifiers in Java are case sensitive.
✔ Java Identifiers can be of any length.
✔ Identifier name cannot contain white spaces.
✔ Most importantly, keywords can’t be used as identifiers in Java.
Valid Identifiers: $myvariable , _variable , variable , edu2019var
Invalid Identifiers: edu variable , Edu_identifier , &variable , 23identifier , switch
, var/edu , edureka's
Variables in Java:
• Here num is a variable and int is a data type, which allows this num variable to hold integer values.
Types of variables:
1) Local variable 2) Static (or class) variable 3) Instance variable
The Scope and Lifetime of Variables:
• Scope of a variable refers to in which areas or sections of a program can the variable
be accessed.
• Lifetime of a variable refers to how long the variable stays alive in memory.
• General convention for a variable’s scope is, it is accessible only within the block in
which it is declared. A block begins with { and ends with }.
1.Instance variables
3.Local variables
Instance variables and Class variables are declared inside class.
Instance variables are created when object is instantiated and
therefore they are associated with object. They take
different values for each object.
Class variables are global to class and belongs to entire set of
objects that class creates.
Only one memory location is created for each class variable.
Variables declared and used inside method are called local
variables.
They are not available outside the method definition.
Local variables can also be declared inside program blocks.
Program a block is begun with an opening curly brace and
ended by a closing curly brace.
A block defines a scope, which determines the lifetime of those
objects.
Instance Variables:
• A variable which is declared inside a class and outside all the methods and blocks
is an instance variable.
• Scope of an instance variable is throughout the class except in static methods.
• Lifetime of an instance variable is until the object stays in memory.
Class (static) Variables:
• A variable which is declared inside a class, outside all the blocks and is
marked static is known as a class variable.
• General scope of a class variable is throughout the class.
• Lifetime of a class variable is until the end of the program.
Local Variables:
• All other variables which are not instance and class variables are treated as local
variables including the parameters in a method.
• Scope of a local variable is within the block in which it is declared.
• Lifetime of a local variable is until the control leaves the block in which it is
declared.
// Example to Demonstrate Life Time. // Example to Demonstrate scope.
class LifeTime class Scope
{ {
public static void main(String args[]) public static void main(String args[])
{ { int x=10;
int x; if(x == 10)
for(x = 0; x < 3; x++) {
{ int y = 20;
int y = -1; System.out.println("x and y: " + x + " " + y);
System.out.println("y is: " + y); x = y * 2;
y = 100; }
System.out.println("y is now: " + y); // y = 100; // Error!
} System.out.println("x is " + x);
}
}
}
}
• Variables are created when their scope/block is entered, and destroyed when their
• Therefore, variables declared within a method will not hold their values between
1. Integer-literal
2. Floating-literal
3. Boolean-literal
4. Character-literal
5. String-literal
Integer Literals:These are the whole numbers without any fractional part.
Rules of writing integer constants are:
1. It must have at least one digit and must not contain any decimal points.
2. Commas cannot appear in an integer constant.
3. It may contain either + or – sign.
4. Valid integer literals are: 56 , +8902 , -235 , 090 etc.
Types of integer literals:
5. Decimal (base 10) : eg. int decNumber = 34;
• For example,
• boolean flag1 = false;
• boolean flag2 = true;
-Here, false and true are two boolean literals.
String literals
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);
Bitwise &,|,^,~
Shift << , >> , >>>
public class IncDecOperators
public class ArithmeticOperators
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
int a = 20, b = 10, c = 0, d = 20;
int a = 20, b = 10;
String x = "Thank", y = "You"; boolean condition = true;
System.out.println("a + b = "+(a + b)); c = ++a;
System.out.println("a - b = "+(a - b)); System.out.println("Value of c (++a) = " + c);
System.out.println("x + y = "+x + y); c = b++;
System.out.println("a * b = "+(a * b)); System.out.println("Value of c (b++) = " +
c);
System.out.println("a / b = "+(a / b));
c = --d;
System.out.println("a % b = "+(a % b));
System.out.println("Value of c (--d) = " + c);
}
}
}
}
Assignment Operator : public class ArithmeticShortHandOperators
{
• ‘=’ Assignment operator is used to public static void main(String[] args)
assign RHS value to LHS variable. {
int a = 20, b = 10, e = 10, f = 4;
• It has a right to left associativity.
a-=1; //a = a - 1;
Syntax: b+=1; //b = b + 1;
data_type variable = value; e/=2; //e = e / 2;
Example: f*=2; //f = f * 2;
int age= 5; System.out.println("a,b,e,f= " + a + "," +
b + "," + e + "," + f);
• For example, instead of a = a+5 , we can
}
write a += 5. }
• Likewise : += , -= , *= , /= , %=
Logical operators: class Main
{
Operator Example Meaning public static void main(String[] args)
true only if both {
&&
(Logical exp1 && exp2
expression1 and System.out.println((5 > 3) && (8 > 5));
expression2 are
AND) System.out.println((5 > 3) && (8 < 5));
true
System.out.println((5 < 3) || (8 > 5));
true if either
|| (Logical
OR)
exp1 || exp2 expression1 or System.out.println((5 > 3) || (8 < 5));
expression2 is true
System.out.println((5 < 3) || (8 < 5));
! (Logical true if expression is System.out.println(!(5 == 3));
!exp
NOT) false and vice versa
System.out.println(!(5 > 3));
}
}
public class RelationalOperators
Relational Operators : {
1.!= , Not Equal to public static void main(String[] args)
2.< , less than { int a = 20, b = 10;
3.== , Equal to String x = "Thank", y = "Thank";
4.<= , less than or equal to int ar[] = { 1, 2, 3 }; int br[] = { 1, 2, 3 };
5.> , Greater than boolean condition = true;
6.>= , System.out.println("a == b :" + (a == b));
Greater than or equal to System.out.println("a < b :" + (a < b));
System.out.println("a <= b :" + (a <= b));
System.out.println("a > b :" + (a > b));
System.out.println("a >= b :" + (a >= b));
System.out.println("a != b :" + (a != b));
System.out.println("x == y : " + (x == y));
System.out.println("ar == br : " + (ar == br));
System.out.println("condition==true :" + (condition == true));
}
}
Ternary operator :
• Ternary operator is a shorthand public class operators
version of if-else statement. It has {
three operands and hence the name public static void main(String[] args)
ternary. {
int a = 20, b = 10, c = 30, result;
• General form- result = ((a > b) ? (a > c) ? a :c : (b > c) ? b : c);
System.out.println("Max of three numbers =
condition ? if true : if false
"+result);
}
• The above statement means that if }
the condition evaluates to true,
then execute the statements after
the ‘?’ else execute the statements
after the ‘:’.
Bitwise operators in Java: 2. Bitwise AND (&) :
• Used to perform manipulation on • It returns bit by bit AND of input values.
bits of a number. • For example: a=5= 0101, b = 7= 0111
1. Bitwise OR (|): • Bitwise AND Operation of 5 and 7
• It returns bit by bit OR of inputs. 0101
• If either of the bits is 1, it gives 1, & 0111
else it gives 0.
___________
• For example,
0101 = 5 (In decimal)
a = 5 = 0101, b = 7 = 00011001
Bitwise OR Operation of 5 and 7
0101
| 0111
________________________________________________________________________________
• For example, multiplication and division have a higher precedence than addition and
subtraction.
1 * 2 + 3 is treated as (1 * 2) + 3
Associativity:
• When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity.
For example:
• x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value
17, since the = operator has right-to-left associativity (and an assignment statement
evaluates to the value on the right hand side).
• On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right
associativity.
• for example, the expressions (x <= y <= z) and x++-- are invalid.
Level Operator Description Associativity
[] access array element
16 . access object member left to right
() parentheses
++ unary post-increment
15 not associative
-- unary post-decrement
++ unary pre-increment
-- unary pre-decrement
+ unary plus
14 right to left
- unary minus
! unary logical NOT
~ unary bitwise NOT
() cast
13 right to left
new object creation
12 */% multiplicative left to right
+- additive
11 left to right
+ string concatenation
Level Operator Description Associativity
<< >>
10 shift left to right
>>>
< <=
9 > >= relational not associative
instanceof
==
8 equality left to right
!=
7 & bitwise AND left to right
6 ^ bitwise XOR left to right
5 | bitwise OR left to right
4 && logical AND left to right
3 || logical OR left to right
2 ?: ternary right to left
= += -=
*= /= %=
1 assignment right to left
&= ^= |=
<<= >>= >>>=
Data Types in Java:
byte:
• Smallest integer type.
• This is an 8-bit (1 byte) signed integer.
• Its range is from -128 to 127.
• Default value is 0.
• Declared using the byte
• For example: byte b, c;
short:
• short data type is a 16-bit signed integer.
• Its range is from -32,768 to 32,767.
• Default value is 0.
• Declared using the short
• For example: short s;
int:
• int is generally used as the default data type for integral values unless there is a concern
about memory.
• is useful for those occasions where an int type is not large enough to hold the desired
value.
• The process of converting a value from one data type to another is known as type
conversion in Java.
• If the two types are compatible, then Java will perform the conversion automatically
called as Implicit type casting.
• But, not all type conversions are implicitly allowed, For example, there is no automatic
conversion defined from double to byte.
• The conversion between incompatible types can be done using casting, called as
explicit type casting.
Implicit type casting:
• When one type of data is assigned to another type of variable, an automatic/ Implicit
type conversion will take place if the following two conditions are met:
• When these two conditions are met, a widening conversion takes place, guarantees
no loss of information.
• For example, the int type is always large enough to hold all valid byte values, so no
explicit cast statement is required.
Explicit type casting:
• If a double value is assigned to int variable, this conversion cannot be performed
automatically because an int is smaller than a double.
• In this case, we must use the explicit type casting to create a conversion between two
incompatible types. This kind of conversion is also known as narrowing.
• The conversion of a higher data type into a lower data type is called narrowing.
Example:
int a;
byte b;
b = (byte) a;
• Above casts an int to a byte. If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder of an integer division by the)
byte’s range.
class ExplicitTypeConversion {
public static void main(String args[])
{
byte b; int i = 257; double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println(i + "--->" + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println( d + "---> " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println(d + "---> " + b);
}
}
Automatic Type Promotion in Expressions:
• Consider expression:
byte a = 40; byte b = 50; byte c = 100;
int d = a * b / c;
• The result of term a * b easily exceeds the range of either of its byte operands.
• To handle this kind of problem, Java automatically promotes each byte, short, or char
operand to int when evaluating an expression.
• This means that the sub expression a*b is performed using integers, not bytes.
• Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a
and b are both specified as type byte.
• Consider code:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
• The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte
variable.
• However, because the operands were automatically promoted to int when the
expression was evaluated, the result has also been promoted to int.
• Thus, the result of the expression is now of type int, which cannot be assigned to a
byte without the use of a cast. This is true even if, as in this particular case, the value
being assigned would still fit in the target type.
• In cases where you understand the consequences of overflow, you should use an
explicit cast, such as
byte b = 50;
b = (byte)(b * 2);//which yields the correct value of 100.
The Type Promotion Rules:
1) if statements
2) If else statement
3) Else if ladder
4) Nested if else
5) switch statements
if Statement:
public class Test
If condition is true body statements executes. {
public static void main(String args[])
Syntax: {
if(Boolean_expression) int x = 10;
{ if( x < 20 )
{
//Statements
System.out.print("This is if statement");
} }
}
}
This would produce following result:
This is if statement
if...else Statement: public class Test
Syntax: {
if(Boolean_expression) public static void main(String args[])
{
{
int x = 30;
//True side statements
if( x < 20 )
}
System.out.print("This is if statement");
else
{ else
//False side statements System.out.print("This is else statement");
} }
}
else-if ladder : public class Test
Syntax: {
if(Boolean_expression 1) public static void main(String args[])
{ {
//statements int x = 30;
}
if( x == 10 )
else if(Boolean_expression 2)
System.out.print("Value of X is 10");
{
else if( x == 20 )
//statements
} System.out.print("Value of X is 20");
else if(Boolean_expression 3) else if( x == 30 )
{ System.out.print("Value of X is 30");
//statements else
} System.out.print("This is else statement");
else }
{ }
//statements
Nested if...else : Example:
Syntax:
if(Boolean_expression 1) public class Test
{ {
if(Boolean_expression) public static void main(String args[])
{ {
//Statements int x = 30, y = 10;
} if( x == 30 )
else {
{ if( y == 10 )
//Statements {
} System.out.print("X = 30 and Y = 10");
} }
else }
{ }
if(Boolean_expression) }
{
public class Test {
The switch Statement: It tests variable for equality against a
list of values. Each value is called a case, and the variable is public static void main(String args[]) {
checked for each case. char grade =‘A’;
Syntax: switch(grade) {
switch(expression) case 'A' : System.out.println("Excellent!");
break;
{
case 'B' : System.out.println(“Very Good!!");
case value :
//Statements; break;
break; case 'C' : System.out.println("Well done");
case value : break;
case 'D' : System.out.println("You passed");
//Statements;
break;
break;
case 'F' : System.out.println("Better try again");
----
break;
default : //Optional default :
//Statements; System.out.println("Invalid grade"); break;
break; //optional }
} System.out.println("Your grade is " + grade);
Loops in java: Example:
1) For public class Test
2) While {
3) Do-while public static void main(String args[])
1) For Loop: {
Syntax: for(int x = 10; x < 20; x = x+1)
for(initialization; Boolean_expression; {
update statement) System.out.println("value of x : " + x );
{ }
//Statements }
} }
Enhanced for / for each loop: public class Test
• for-each loop is used to iterate through {
arrays. public static void main(String args[])
Sytnax {
for(dataType item : array) int [] numbers = {10, 20, 30, 40, 50};
{ for(int x : numbers )
//statements System.out.println( x+”,” );
}
Here, String [] names ={“Ankit", “Rahul",
• array - an array “Sam”};
• item - each item of array is assigned to for( String name : names )
this variable System.out.print( name+”,” );
• dataType - the data type of the }
array/collection
}
The While Loop: public class Test
Syntax: {
initialisation public static void main(String args[])
while(Boolean_expression) {
{ int x = 10;
//Statements while( x < 20 )
incr/decr statement {
} System.out.println("value of x : " + x );
x++;
}
}
}
The do...while Loop: Example:
public class Test
Syntax: {
Initilisation; public static void main(String args[])
do {
{ int x = 10;
//Statements do{
Incr/decr statement System.out.println("value of x : " + x );
} while(Boolean_expression); x++;
}while( x < 20 );
}
}
Jump statements in java : public class Test
• Java supports three jump statements: {
1) break 2)continue 3)return public static void main(String args[])
• These statements transfer control to another part {
of your program.
int [] numbers = {10, 20, 30, 40, 50};
The break statement:
for(int x : numbers )
• Used to exit a loop or switch case. {
• The break keyword must be used inside any loop if( x == 30 )
break;
or a switch statement.
System.out.print( x );
• The break will stop the execution of loop and }
start executing the next line of code after the }
block. }
Syntax: break;
Continue statement: public class Test
{
• The continue causes the loop to
public static void main(String args[])
immediately jump to the next iteration of {
the loop. int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
• In a for loop, the continue keyword causes
{
flow of control to immediately jump to the
if( x == 30 )
update statement. continue;
• In a while loop or do/while loop, flow of System.out.println( x );
}
control immediately jumps to the Boolean
}
expression.
}
• Syntax: continue;
The return statement
• The value passed with return keyword must match with return type of the method.
Labelled loop:
• In nested loop, if break executes in inner loop, compiler will jump out from inner loop
and continue the outer loop again.
• What if we need to jump out from the outer loop using break statement given inside
inner loop?
• The answer is, we should define label along with colon(:) sign before loop.
• Syntax of Labelled loop
class WithoutLabelledLoop class WithLabelledLoop
{ {
public static void main(String args[]) public static void main(String args[])
{ int i,j; { int i,j;
for(i=1;i<=5;i++) loop1: for(i=1;i<=5;i++)
{ {
System.out.println(); System.out.println();
for(j=1;j<=10;j++) loop2: for(j=1;j<=10;j++)
{ {
System.out.print(j + " "); System.out.print(j + " ");
if(j==5) if(j==5)
break; //Statement 1 break loop1; //Statement 1
} }
} }
} }
} }
public class MathFunctions
{
public static void main(String[] args)
{
double x = 4; double y = 2; int z=-10;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println("Minimum number of x and y is: " +Math.min(x, y));
System.out.println("Absolute of x is: " +Math.abs(z));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("exp of x is: " +Math.exp(x));
System.out.println("exp of x is: " +Math.round(10.s));
}
}