Basic Syntactical Constructs in Java
Basic Syntactical Constructs in Java
Introduction to java:
• Java is a high-level programming language and a platform.
• It was developed by the company named Sun MicroSystems which was later acquired
by Oracle Corporation. Now oracle manages and releases different versions of java.
• Java was created by a team led by James Gosling at Sun MicroSystem.
High Level Language :
• A High-Level Language is a computer programming language that uses English like statements
to write the computer instructions.
• High-level languages are most widely programming languages because they are easy to
understand to human being.
History of java:
• Java was created by the company named as Sun MicroSystems. James Gosling is known as the
creator of java language.
• In 1991, a team named Green team, led by James Gosling started working on java language
project.
• Initially their intention was to develop the language that can be used for digital devices like cell
phones, televisions, set-top boxes etc.
• Initially the name of language was Oak.
Q. List any eight features of Java. 2M
Q. Explain four or six features of Java. 4M or 6M
1.1.b. Java Features:
1. Java is Platform Independent
• Java is an object oriented programming language because java supports the principles of Object
Oriented.
• Programming(OOPs)like Encapsulation, Inheritance, Abstraction Polymorphism etc.
3. Java is Simple
• Java is a simple language because it's syntaxes are very similar to C++ syntaxes.
• It also provides automatic memory management through garbage collection.
• Java contains a lot of predefined class libraries to support different needs in a program.
4. Java is Secure
• Java is secure because it has features like automatic memory management, no explicit pointer,
bytecode verifier etc that enhances the security of java programs.
• Bytecode verifier ensures that .class files are not edited explicitly, any external edit fails the
program to run.
5. Java is Portable
• Java is portable because the bytecode(.class file) of a program can be run on different machines
without any change in it.
6. Java is Robust
• Classes in java are linked/loaded only when needed. The code can be downloaded.
• dynamically from anywhere on the network.
8. Interpreted
In java when you compile a program, the java compiler(javac) converts/rewrite your program in
another form/language which we call as bytecode. The .class file that is generated after
compilation is nothing else, it's basically the bytecode instructions of your program. The word
bytecode and .class are used interchangeably, so if someone says bytecode, it simply means the
.class file of program.
1.1.C. Java Runtime Environment:
What is JDK in Java:
• JDK stands for java development kit. As the name itself suggest, JDK helps the programmer in
development(compilation and execution) of java programs.
• It's a software package that contains tools and libraries needed for compilation and execution of
java programs.
• If you are a programmer then you must need to install JDK first in your system in order to start
programming in java.
• For windows OS, this software generally comes in the form of .exe or .zip file.
• JRE stands for java runtime environment. It provides a runtime environment to your program for
it's execution.
• As soon as you start running your program using java command, the job of JRE starts and it
ends when either the program ran successfully or any error is thrown.
JRE = JVM + runtime libraries(contains packages like util, math, lang etc.)+ runtime files
What is JVM in Java:
JVM stands for java virtual machine, a virtual machine which loads and executes java programs
in memory.
The machine loads not only your class(program) but also other required classes and libraries as
well which are needed to execute the program.
This section contains some basic examples of java programs, specially for beginners to get some
more idea about execution flow in java programs. It also shows you how to pass command line
arguments to java programs and how to call method of a program using object.
class FirstProgramFlow {
[Link]("first ");
[Link]("second ");
[Link]("third ");
}}
Output:
first
second third
Java Syntax:
[Link]
Public class Firstpgm{
Public static void main(String[] args)
{
[Link](“Hello world”);
}
}
Q. Define class and object in java?
1.2.a Java Classes:
• A Class is like an object constructor, or a "blueprint" for creating objects.
• Everything in Java is associated with classes and objects, along with its attributes and methods.
• For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Create a Class:
• Using the new keyword is the most popular way to create an object or instance of the class.
• When we create an instance of the class by using the new keyword, it allocates memory (heap)
for the newly created object and also returns the reference of that object to that memory.
• The new keyword is also used to create an array. The syntax for creating an object is:
• Local variable
• Instance variable
• Static or Class variable
• Variables defined inside a class but outside any method, constructor or block are known as
instance variable.
• Initialization of instance variable is not compulsory, if not initialized, these variables will have
default values as per their data type.
• Instance variables are created in memory(heap memory) as soon as the object of the class
containing the instance variable is created.
• The Instance variables are accessed using object name like [Link].
• The good practice is to always use the object name for accessing the instance variable.
Output:
Age=20
Name=Rahul
• Variables defined inside a class(not inside method, constructor or block) using static keyword
are known as static or class variables.
• Initialization of class variable is also not compulsory, if not initialized, these variables will have
default values as per their data type.
• These variables are known as class variables because they belong to class, not objects.
• The declaration of static or class variable is same as instance variable, except that they are
declared along with static keyword.
• The declaration of static or class variable is same as instance variable, except that they are
declared along with static keyword.
• Static variable can be accessed using class name as [Link] or using any of
the object instances as well like [Link].
• The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program.
• These tokens are separated by the delimiters. It is useful for compilers to detect errors.
• Remember that the delimiters are not part of the Java tokens.
Types of Tokens:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case.
01. abstract 02. Boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
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. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and [Link] are
some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with
digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code.
Separators: The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:
separator <= ; ( ) | { } | [ ]
Comments: Comments allow us to specify information about the program inside our Java code.
Java compiler recognizes these comments as tokens but excludes it form further processing. The
Java compiler treats comments as whitespaces. Java provides the following two types of
comments:
Java Constant:
• Constant is a value that cannot be changed after assigning it. Java does not directly support the
constants.
• There is an alternative way to define the constants in Java by using the non-access modifiers
static and final.
• Converting a lower data type into a higher one is called widening type casting.
• It is also known as implicit conversion or casting down. It is done automatically.
• Both data types must be compatible with each other.
• The target type must be larger than the source type.
• byte -> short -> char -> int -> long -> float -> double
[Link]
1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. [Link]("Before conversion, int value "+x);
11. [Link]("After conversion, long value "+y);
12. [Link]("After conversion, float value "+z);
13. }
14. }
Output
• Converting a higher data type into a lower one is called narrowing type casting.
• It is also known as explicit conversion or casting up.
• It is done manually by the programmer. If we do not perform casting then the compiler reports a
compile-time error.
double -> float -> long -> int -> char -> short -> byte
[Link]
Declaration pointInside a method, constructor, or [Link] the class. Inside the class
using static keyword.
Use of Access
Access Can be used. Can be used
Modifier modifier(public, private, protected)
can not be used with local variables
Access from
Not possible, Local variable can be Instance variables canSame as instance
outside accessed within the method,be accessed outside variable. It can be
constructor or block in which they are
depending upon it's accessed using object or
declared. access modifier. It class name.
can be accessed using
object of that class.
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.
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
An operator is basically a special symbol which tells the computer to perform specific operation
on one, two or three operands and then return a result.
Operand in Java:
• Unary operator
• Binary operator
• Ternary operator
An operator which operates on one operand is known as unary operator. For example +, -,
++ etc are unary operators, usage example +2, -3, ++a etc.
An operator which operates on two operands is known as binary operator. For example +, -,
* etc are binary operators, usage example 2+3, 5-3, a*b etc.
An operator which operates on three operands is known as ternary operator. There is only one
ternary operator in java which is ?:, also known as if then else operator.
• The = operator in java is known as assignment or simple assignment operator. It assigns the
value on its right side to the operand(variable) on its left side.
• For example :
int a = 10;
2. Arithmetic Operators:
• Arithmetic operators are also one of the most used operators in java programming language.
• Arithmetic operators are used to perform arithmetic operations like addition, subtraction,
multiplication and division.
• These operator performs the same operation as they perform in basic mathematics. Table below
shows the list of all arithmetic operators which you can use in your java programs.
Consider a and b as two operands or variables.
The table below shows the list of all operators in java which you can use in your programs. For
this table let's assume we have operands or variables a, b and c.
• Unary simply means one, so unary operators are the operators which operates on only one
operand.
• The table below shows the list of all unary operators in java. For this table let's assume we have
an integer variable a and a boolean variable isValid :
• The unary increment(++) operator increments the value of a variable by 1 while unary
decrement(--) operator decrements the value of a variable by 1.
• For example a++ increases the value a by 1 and is same as a = a + 1, similarly a-- decreases the
value of a by 1 and is same as a = a - 1. Both these operators can be used with a variable only,
not with any constant value, expression or method calls.
• In pre increment/decrement, the value of the variable is incremented/decremented first then it is
assigned or evaluated, that is why it is called pre-increment/decrement.
• While in post increment/decrement the current value of the variable is assigned or evaluated,
after that the increment/decrement happens, that is why it is called post increment/decrement.
• Let's understand this by the example below :
• int a = 2, b = 3, c = 4, d = 5;
• int p = a++; // p = 2; first assignment happens then the increment
• p = a; // a = 3, p = 3; // a was increased in previous line
• int q = ++b; // q = 4; first increment happens then the assignment
• int r = c--; // r = 4, first assignment happens then the decrement
• r = c; // c = 3, r = 3; // c was decreased in previous line
• int s = --d; // s = 4; first decrement happens then the assignment
• int a = 2;
• int p = a++ + --a - a-- * ++a;
• To understand it clearly let's see step by step how this expression is evaluated.
• Just remember in java an expression is evaluated from left to right.
• Relational operators are used to relate or compare if one operand is greater than, less than, equal
to, or not equal to another operand. Operators like >, >=, < etc are called as relational operators.
• while operator == is called as equality operator. All relational operators along with equality
operator returns either true or false.
• Table below shows the list of all relational operators in java.
class RelationalOperator {
public static void main(String[] args) {
int num1 = 3;
int num2 = 5;
if(num1 == num2)
[Link]("num1 == num2");
if(num1 != num2)
[Link]("num1 != num2");
if(num1 > num2)
[Link]("num1 > num2");
if(num1 >= num2)
[Link]("num1 >= num2");
if(num1 < num2)
[Link]("num1 < num2");
if(num1 <= num2)
[Link]("num1 <= num2");
}
}
Output:
num1 != num2
num1 < num2
num1 <= num2
Conditional operators in Java:
The result of conditional AND and conditional OR operators is also a boolean value which
is true or false.
• The ternary operator( ?:) is another conditional operator in java. This operator can be thought as
a short form of if-then-else statement.
• It is known as ternary operator because it uses three operands. Line below shows how to use this
operator.
Here someCondition is a boolean expression that returns either true or false. You can read this
operator as "if someCondition is true, assign the value of Expression1 into the variable else
assign the value of Expression2 into the variable.
Bitwise operators in Java:
As the name itself suggests, bitwise operator performs operation bit by bit wise. Table below
shows the list of all bitwise operators in java.
Bitwise complement
~ ~a Inverts the bits of variable a
Operator
• All the bitwise operators except complement operator are binary operators.
• The bitwise complement operator is a unary operator, as it requires only one operand to perform
the operation. It belongs to bitwise operator type because it works on bits.
• Bitwise AND(&) operator performs bitwise AND operation on corresponding bits of both the
operands.
• It returns 1 if both the bit's are 1 else it returns 0. For example & operation between
two byte variable with value as 53(00110101) and 79(01001111) will result in 5(00000101).
1&1=1
1&0=0
0&1=0
0&0=0
Bitwise OR operator in Java:
• Bitwise OR(|) operator performs bitwise OR operation on corresponding bits of both the
operands. It returns 1 if any of the bit's is 1 else it returns 0.
1|1=1
1|0=1
0|1=1
0|0=0
1|1=0
1|0=1
0|1=1
0|0=0
The unary bitwise complement operator ~ inverts the bit pattern of an operand. It
converts 0 as 1 and 1 as 0. For example a byte data type contains 8 bits, using this operator with
a byte variable with value whose bit pattern is "00110101" would be changed as "11001010".
Bit Shift operator in Java:
• As the name itself suggests, the bit shift operators shifts the bits of an operand to left or right
depending on the shift operator used.
• In bit shift operator, the bit pattern(operand) is given in left-side while the number of positions
to shift by is given in right side of the operator.
• All bit shift operators are binary operators in java as they requires two operands to operate.
Table below shows the list of all bit shift operators in java.
Unsigned right shift Right shifts the bits of a by 2 position and places 0's
>>> a >>> 2
Operator in left side.
• The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
• The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false.
• If we apply the instanceof operator with any variable that has null value, it returns false.
Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. [Link](s instanceof Simple1);//true
5. }
6. }
Output:true
Mathematical Function :
Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc
[Link]() It returns the value of first argument raised to the power to second argument.
Example:
Precedence:
It is meaningful only if an expression has more than one operator with higher or lower
precedence. The operators having higher precedence are evaluated first.
Associativity:
If an expression has more than two operators of the same precedence. In such a case, an
expression can be solved either left-to-right or right-to-left, accordingly.
Precedence Operator Type Associativity
class OperatorPrecedence {
public static void main (String[] args) {
int result = 0;
result = 5 + 2 * 3 - 1;
[Link]("5 + 2 * 3 - 1 = " +result);
result = 5 + 4 / 2 + 6;
[Link]("5 + 4 / 2 + 6 = " +result);
result = 3 + 6 / 2 * 3 - 1 + 2;
[Link]("3 + 6 / 2 * 3 - 1 + 2 = " +result);
result = 6 / 2 * 3 * 2 / 3;
[Link]("6 / 2 * 3 * 2 / 3 = " +result);
int x = 2;
result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;
[Link]("result = " +result); }}
Output:
5 + 2 * 3 - 1 = 10
5 + 4 / 2 + 6 = 13
3 + 6 / 2 * 3 - 1 + 2 = 13
6/2*3*2/3=6
result = 2
Mathematical Function :
Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc
[Link]() It returns the value of first argument raised to the power to second argument.
• Java provides statements that can be used to control the flow of Java code. Such statements are
called control flow statements.
• It is one of the fundamental features of Java, which provides a smooth flow of program.
• Java provides three types of control flow statements.
• Decision Making statements
o if statements
o switch statement
• Loop statements
o do while loop
o while loop
o for loop
o for-each loop
• Jump statements
o break statement
o continue statement
Decision-Making statements:
1) If Statement:
• The control of the program is diverted depending upon the specific condition. The condition of
the If statement gives a Boolean value, either true or false.
• In Java, there are four types of if-statements given below.
1. [Link] if statement
2. [Link]-else statement
3. if-else-if ladder
4. Nested if-statement
2) Simple if statement:
• It is the most basic statement among all control flow statements in Java.
• It evaluates a Boolean expression and enables the program to enter a block of code if the
expression evaluates to true.
• Syntax of if statement is given below.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
[Link]
Output:
x + y is greater than 20
3) if-else statement:
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
4) if-else-if ladder:
• The if-else-if statement contains the if-statement followed by multiple else-if statements.
• In other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true.
• Syntax of if-else-if statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
[Link]
Output:
Delhi
5. Nested if-statement:
• In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
• Syntax of Nested if-statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
[Link]
Output:
Delhi
Switch Statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type
as the variable. However, it will also be a constant value.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
[Link]
Output:
Number is 1
Loop Statements:
• In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order.
• The execution of the set of instructions depends upon a particular condition.
• In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.
Consider the following example to understand the proper functioning of the for loop in java.
[Link]
Output:
• Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable.
• The syntax to use the for-each loop in java is given below.
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
Java
C
C++
Python
JavaScript
The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements after
the loop will be executed.
1. while(condition){
2. /-+]/looping statements
3. }
The flow chart for the while loop is given in the following image.
Output:
0
2
4
6
8
10
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
Output:
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
[Link]
Output:
0
1
2
3
4
5
6
Output:
0
1
2
3
4
5
[Link] continue statement:
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Garbage Collector: