Chapter 1 Basic Syntactical Constructs
Chapter 1 Basic Syntactical Constructs
Unit 1
Basic Syntactical Constructs In Java
What is Java
1.Java is a programming language and a platform.
2.Java is a high level, robust, object-oriented and secure programming language.
3.Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995.
4.James Gosling is known as the father of Java.
5.Before Java, its name was Oak.
6.Since Oak was already a registered company, so James Gosling and his team changed the Oak
name to Java.
2.Platform Independent
Java compiler produces a unique type of code called byte code unlike c compiler where compiler
produces only natively executable code for a particular machine.
When the Java program runs in a particular machine it is sent to java compiler, which converts this
code into intermediate code called byte code. This byte code is sent to Java virtual machine (JVM)
which resides in the RAM of any operating system. JVM recognizes the platform it is on and converts
the byte codes into native machine code. Hence java is called platform independent language.
Secure: Unlike C, there are no pointers in Java. The basic use of Pointers is to refer to the actual
memory location where the value is stored, and hence enabling the programmer to further modify the
actual value.
As java does not consist of pointers, there is no way one can refer to the actual value, and hence the
value remains protected or unaltered.
Due to these reasons, Java is known as a Secure language.
Prepared By Roshani K.Dharme Head Computer
5
Engg.Department
JAVA Features
5. Dynamic
Java is dynamic language
It is capable of dynamically linking in new class libraries ,methods and objects.
It can also determine the type of class through a query, making it possible to either dynamically link or
abort the program depending on the response.
6.Object Oriented
A fully object-oriented language needs to have all the 4 oops concepts i.e Abstraction, Polymorphism,
Encapsulation, Inheritance.
In addition to that, all predefined and, user-defined types must be objects and, all the operations should
be performed only by calling the methods of a class.
Though java follows all the four object-oriented concepts,
Java has predefined primitive data types (which are not objects).
You can access the members of a static class without creating an object of it.
Therefore, Java is not considered as fully object-oriented Technology.
7. Distributed
Java is a distributed language as it can be used to create applications to communicate over the
network as it supports TCP/IP, network communication protocol.
9.High Performance
Java has high performance than C and C++.
In real life applications ,most of the time java is prefer than C/C++.
Java Ecosystem
Java has emerged to be a robust, portable and high performing language and has been widely
adopted globally. One of the major reasons for the success of Java is the immense number of
third party libraries and components written in Java. Today it is rare to a find a component
which does not have a supporting Java connector. From traditional MySQL to NoSQL,
monitoring frameworks, network components all have a Java connector readily available.
data-type method-name1(parameter-list)
{
//body of the method1
} Member Methods
data-type method-nameN(parameter-list)
{
//body of the methodN
}
} Prepared By Roshani K.Dharme Head Computer
Engg.Department
12
Creating an Object
objectname. variablename
Constants:
A constant is fixed value that does not change during the execution of the program.
Java support following types of constants:-
Constants
Numeric Character
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It
is a combination of "vary + able" that means its value can be changed.
int data=50;//Here data is variable
Reserved Area
10
RAM
Prepared By Roshani K.Dharme Head Computer
16
Engg.Department
Java Variables
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
To declare an array, define the variable type with square brackets:
String[] cars;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Prepared By Roshani K.Dharme Head Computer
25
Engg.Department
Java Data Types
This statement accesses the value of the first element in cars:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
The main difference between primitive and non-primitive data types are:
❑ Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
❑ Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
❑ A primitive type has always a value, while non-primitive types can be null.
❑ A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase
letter.
Prepared By Roshani K.Dharme Head Computer
26
Engg.Department
Dynamic Initialization of Variable
The process of initializing variable at the time of its declaration at run time is known as dynamic
initialization of variable.
Thus in dynamic initialization of variable a variable is assigned value at run time at the time of its
declaration.
int main()
{
int a;
printf(“Enter Value of a”);
scanf(“%d”,&a);
int cube = a * a * a;
printf(“Cube is=%d\n”,cube);
return 0;
}
In above example variable cube is initialized at run time using expression a * a * a at the time of its
declaration.
Method Scope
Variables declared directly inside a method are available anywhere in the method following the
line of code in which they were declared:
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
Block Scope
A block of code refers to all of the code between curly braces {}. Variables declared inside blocks of
code are only accessible by the code between the curly braces, which follows the line in which the
variable was declared:
A block of code may exist on its own or it can belong to an if, while or for statement. In the case of
for statements, variables declared in the statement itself are also available inside the block's scope.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
} Prepared By Roshani K.Dharme Head Computer
30
} Engg.Department
Java Type Casting
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
Unary operators are used with only one operand. For example, ++ is a unary operator that increases
the value of a variable by 1. That is, ++5 will return 6.
Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
Prepared By Roshani K.Dharme Head Computer
^ Bitwise exclusive OR Engg.Department
37
Operator & Expressions
Other operators
Besides these operators, there are other additional operators in Java.
Java instanceof Operator
The instance of operator checks whether an object is an instance of a particular class. For example,
class Main {
public static void main(String[] args) {
String str = "Programiz";
boolean result;
// checks if str is an instance of
// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Output
Precedence Of an Operator
Precedence specifies the order in which operations are performed. Consider this expression:
a+b*c
The multiplication operator has higher precedence than the addition operator, so a is added to the
product of b and c. Operator precedence can be thought of as a measure of how tightly operators bind
to their operands. The higher the number, the more tightly they bind.
Default operator precedence can be overridden through the use of parentheses, to explicitly specify
the order of operations. The previous expression can be rewritten as follows to specify that the
addition should be performed before the multiplication:
(a + b) * c
Prepared By Roshani K.Dharme Head Computer
40
Engg.Department
Math Functions
The Java Math class has many methods that allows you to perform mathematical tasks on numbers.
Math.max(x,y)
The Math.max(x,y) method can be used to find the highest value of x and y:
Example
Math.max(5, 10);
Math.min(x,y)
The Math.min(x,y) method can be used to find the lowest value of x and y:
Example
Math.min(5, 10);
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:
Example
Math.sqrt(64); Prepared By Roshani K.Dharme Head Computer
41
Engg.Department
Math Functions
Math.abs(x)
The Math.abs(x) method returns the absolute (positive) value of x:
Example
Math.abs(-4.7);
Random Numbers
Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
Example
Math.random();
To get more control over the random number, e.g. you only want a random number between 0 and 100, you can
use the following formula:
Example
int randomNum = (int)(Math.random() * 101); // 0 to 100
Prepared By Roshani K.Dharme Head Computer
42
Engg.Department
Decision Making and Looping
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in Java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
if(condition){
//code to be executed
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true Prepared By Roshani K.Dharme Head Computer
43
}else{ //code if condition is false } Engg.Department
Decision Making and Looping
Using Ternary Operator
We can also use ternary operator (? :) to perform the task of if...else statement. It is a shorthand
way to check the condition. If the condition is true, the result of ? is returned. But, if the condition
is false, the result of : is returned.
Example:
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Prepared By Roshani K.Dharme Head Computer
45
Engg.Department
Decision Making and Looping
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail"); }
else if(marks>=50 && marks<60){
System.out.println("D grade"); }
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade"); }
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade"); }else{
System.out.println("Invalid!");
} } } Prepared By Roshani K.Dharme Head Computer
Engg.Department
46
Decision Making and Looping
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed } }
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} } }} Prepared By Roshani K.Dharme Head Computer
47
Engg.Department
Decision Making and Looping
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Points to Remember
1. There can be one or N number of case values for a switch expression.
2. The case value must be of switch expression type only. The case value must be literal or constant.
It doesn't allow variables.
3. The case values must be unique. In case of duplicate value, it renders compile-time error.
4. The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
5. Each case statement can have a break statement which is optional. When control reaches to the
break statement, it jumps the control after the switch expression. If a break statement is not found,
it executes the next case.
6. The case value can have a default label which is optional.
Prepared By Roshani K.Dharme Head Computer
48
Engg.Department
Decision Making and Looping
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
Prepared By Roshani K.Dharme Head Computer
52
Engg.Department
Decision Making and Looping
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Prepared By Roshani K.Dharme Head Computer
53
Engg.Department
Decision Making and Looping
Java Break and Continue
Java Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Prepared By Roshani K.Dharme Head Computer
54
Engg.Department
Decision Making and Looping
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}