0% found this document useful (0 votes)
3 views

Basics

Uploaded by

shiven.chilveri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Basics

Uploaded by

shiven.chilveri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Basic Syntactical constructs in Java

Unit Objectives
⚫ Write Programs to create classes and objects for
the given problem
⚫ Explain the characteristics of given java token
⚫ Explain the function of given operator with
example.
⚫ Construct the expression by using implicit and
explicit type conversion
⚫ Develop the programs using control structure to
solve the given problem
Somethings about java
⚫ James Gosling and Sun Microsystems
⚫ Oak
⚫ Java, May 20, 1995, Sun World
⚫ HotJava
⚫ The first Java-enabled Web browser

⚫ JDK Evolutions
⚫ J2SE, J2ME, and J2EE (not mentioned in the book, but
could discuss here optionally)
Why Java???
1) Simple
2) Object Oriented
3) Robust
4) Platform Independent
5) Secure
6) Multi Threading
7) Architectural Neutral
8) Portable
9) High Performance
Comparison between Java & C++
Java C++

Platform Independent Platform dependent

Uses Compiler and Interpreter Uses Compiler only

Don‟t have pointers and References Have pointers and References

Don‟t have Structures and Union Have Structures and Union

Used to built web based applications Used to built only Desktop applications

Have Built in support to thread. Don‟t Have Built in support to thread.


Platform Independence/Portability in
java
"write once run anywhere"
Contd…
Bytecode/Magic Code
⚫ Bytecode is program code that has
been compiled from source code into low-level code
designed for a software interpreter.
⚫ It may be executed by a virtual machine (such as
a JVM) or further compiled into machine code, which
is recognized by the processor.
Contd..
Steps to Start..
1. Write a source code in any text editor
2. Save that file with .java extension
(Example: HelloWorld.java)
3. Use Javac command to Compile the source code(javac
HelloWorld.java)
4. Source code will be converted into bytecode
(HelloWorld.class)
5. Execute the compiled file by using Java command
(java HelloWorld)
Simple Things to Remember
1. File Name should be same as class containing main
Function
2. Java is a case sensitive language
3. We can run java programs on command prompt or we
can install IDE like NetBeans or eclipse
JDK and JRE
⚫ JDK 1.02 (1995)
⚫ JDK 1.1 (1996)
⚫ Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
⚫ Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
⚫ Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
Structure of a java program
⚫ Comments
⚫ Package
⚫ Reserved words
⚫ Modifiers
⚫ Statements
⚫ Blocks
⚫ Classes
⚫ Methods
⚫ The main method
Simple program
Class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
Save-> HelloWorld.java
Compile->javac HelloWorld.java
Execute->java HelloWorld
Data types,
Identifiers, variables
and constatnts
Identifiers
⚫ Identifiers are the names of variables, methods, classes,
packages and interfaces.

⚫ Unlike literals they are not the things themselves, just ways of
referring to them.

⚫ In the HelloWorld program, HelloWorld,String,args main


and println are identifiers.

⚫ Identifiers must be composed of letters,numbers,the


underscore _ and the dollar sign $.

⚫ Identifiers may only begin with a letter, the underscore or a


dollar sign.
Variable Declaration
⚫ Have to declare all variables before using them!
int number;
1) new variable of type “int”
2) having the name “number”
What's wrong in these ?

1) Int x;

2) float y

3) int float;

4) int 2good;

5) int yes&no;
Constants
⚫ A constant is a variable whose value cannot change once
it has been assigned. Java doesn't have built-in support for
constants.
⚫ To define a variable as a constant, we just need to add the
keyword “final” in front of the variable declaration.

e.q-> final float pi = 3.14f;


In the above statement declares the float variable “pi” as a constant with a
value of 3.14f. We cannot change the value of "pi" at any point in time in
the program.
Type casting
⚫ Type casting is when you assign a value of one primitive
data type to another type.
⚫ Two types of casting:
⚫ Widening Casting (automatically) - converting a smaller
type to a larger type size
byte -> short -> char -> int -> long -> float -> double

⚫ Narrowing Casting (manually) - converting a larger type


to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a
smaller size type to a larger size type:

public class MyClass


{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt;
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing casting
Narrowing casting must be done manually by placing the type
in parentheses in front of the value:
public class MyClass
{
public static void main(String[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble;
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}
Operators in java
⚫ Arithmetic Operators
⚫ Unary Operators
⚫ Assignment Operator
⚫ Relational Operators
⚫ Logical Operators
⚫ Ternary Operator
⚫ Bitwise Operators
⚫ Shift Operators
⚫ instance of operator
Arithmetic Operators:
⚫ They are used to perform simple arithmetic operations
on primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Unary Operators:
Unary operators need only one operand. They are used to increment, decrement or negate a
value.
1. – :Unary minus, used for negating the values.
2. + :Unary plus, used for giving positive values. Only used when deliberately converting a
negative value to positive.
3. ++ :Increment operator, used for incrementing the value by 1. There are two varieties of
increment operator.
Post-Increment : Value is first used for computing the result and then incremented.
Pre-Increment : Value is incremented first and then result is computed.
4.- : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operator.
Post-decrement : Value is first used for computing the result and then decremented.
Pre-Decrement : Value is decremented first and then result is computed.
5. ! : Logical not operator, used for inverting a boolean value.
Assignment Operator :
⚫ ‘=’ Assignment operator is used to assign a value to any
variable. It has a right to left associativity, i.e value given
on right hand side of operator is assigned to the variable on
the left and therefore right hand side value must be declared
before using it or should be a constant.
General format of assignment operator is,

variable = value;
e.g
int a = 5;
a += 5;
Contd..
1. +=:for adding left operand with right operand and then
assigning it to variable on the left.
2. -=:for subtracting left operand with right operand and then
assigning it to variable on the left.
3. *=:for multiplying left operand with right operand and then
assigning it to variable on the left.
4. /=:for dividing left operand with right operand and then
assigning it to variable on the left.
5. %=:for assigning modulo of left operand with right operand
and then assigning it to variable on the left.
Relational Operators
⚫ These are a bunch of binary operators that are used to check for
relations between two operands including equality, greater than, less
than etc.
⚫ They return a boolean result after the comparison and are extensively
used in looping statements as well as conditional if-else statements and
so on.
⚫ The general format of representing relational operator is:
Syntax:
variable1 relation_operator variable2
Example:
A<b
Relational Operators

Operator Meaning

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to


Logical Operators
⚫ These operators are used to perform “logical AND”
and “logical OR” operation, i.e. the function similar to
AND gate and OR gate in digital electronics.
⚫ &&, Logical AND : returns true when both conditions
are true.
⚫ ||, Logical OR : returns true if at least one condition is
true.
Ternary Operator
⚫ Ternary operator is a shorthand version of if-else statement. It
has three operands and hence the name ternary.
⚫ General format is-
condition ? if true : if false
⚫ The above statement means that if the condition evaluates to
true, then execute the statements after the „?‟ else execute the
statements after the „:‟.
⚫ Example

(a>b)?a:b
Bitwise Operators
⚫ These operators are used to perform manipulation of individual bits of
a number. They can be used with any of the integer types. They are
used when performing update and query operations of Binary indexed
tree.
⚫ ‘&’Bitwise AND operator: returns bit by bit AND of input values.
⚫ ‘|’ Bitwise OR operator: returns bit by bit OR of input values.
⚫ ‘^’ Bitwise XOR operator: returns bit by bit XOR of input values.
⚫ ‘~’ Bitwise Complement Operator: This is a unary operator which
returns the one‟s compliment representation of the input value, i.e. with
all bits inversed.
Shift Operators
⚫ These operators are used to shift the bits of a
number left or right thereby multiplying or
dividing the number by two respectively. They can
be used when we have to multiply or divide a
number by two. General format-
number shift_op number_of_places_to_shift;
Example
a=2(0020)
a<<2 (2000 i.e 8)
Contd…
⚫ <<, Left shift operator: shifts the bits of the number to the
left and fills 0 on voids left as a result..
⚫ >>, Signed Right shift operator: shifts the bits of the
number to the right and fills 0 on voids left as a result. The
leftmost bit depends on the sign of initial number.
⚫ >>>, Unsigned Right shift operator: shifts the bits of the
number to the right and fills 0 on voids left as a result. The
leftmost bit is set to 0.
instance of operator
⚫ Instance of operator is used for type checking. It can
be used to test if an object is an instance of a class, a
subclass or an interface. General format-
⚫ Syntax
object instance of class/subclass/interface
⚫ Example:
Person obj1 = new Person();
obj1 instance of Person
Decision Making and Looping
⚫ if
⚫ if-else
⚫ nested-if
⚫ if-else-if
⚫ switch-case
⚫ jump – break, continue, return
if

⚫ if statement is the most simple decision making statement. It is


used to decide whether a certain statement or block of statements
will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
if-else
⚫ The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won‟t. But what if we want to do something
else if the condition is false. Here comes the else statement. We can use the else
statement with if statement to execute a block of code when the condition is false.
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
nested-if
⚫ A nested if is an if statement that is the target of another if or else.
Nested if statements means an if statement inside an if statement.
Yes, java allows us to nest if statements within if statements. i.e, we
can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
if-else-if ladder
⚫ Here, a user can decide among multiple options.The if statements are
executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
if (condition)
statement;
else if (condition)
statement;
..
else statement;
switch-case
⚫ The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
..
case valueN: statementN;
break;
default: statementDefault;
}
break, continue, return
⚫ Java supports three jump statement:
⚫ break, continue and return.
⚫ These three statements transfer control to other part of the
program.
⚫ Break: In Java, break is majorly used for:
⚫ Terminate a sequence in a switch statement (discussed above).
⚫ To exit a loop.
⚫ Used as a “civilized” form of goto.
⚫ Using break to exit a Loop
⚫ Continue: Sometimes it is useful to force an early iteration of a
loop. That is, you might want to continue running the loop but stop
processing the remainder of the code in its body for this particular
iteration.
for (int i = 0; i < 10; i++)
{
// If the number is even skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
O/p: 1 3 5 7 9
⚫ Return : The return statement is used to explicitly return from
a method. That is, it causes a program control to transfer back
to the caller of the method.
Example:
boolean t = true;
System.out.println("Before the return.");

if (t)
return;
// Compiler will bypass every statement after return
System.out.println("This won't execute.");
Looping in Java
⚫ while : while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean
condition. The while loop can be thought of as a repeating
if statement.
⚫ Syntax:
while (boolean condition)
{
loop statements...
}
⚫ For : for loop provides a concise way of writing the loop
structure. Unlike a while loop, a for statement consumes the
initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
⚫ Syntax:
for (initialization; testing condition;
increment/decrement)
{
statement(s)
}
⚫ For Each : Java also includes another version of for loop
introduced in Java 5. Enhanced for loop provides a simpler
way to iterate through the elements of a collection or array. It is
inflexible and should be used only when there is a need to
iterate through the elements in sequential manner without
knowing the index of currently processed element.
⚫ Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
⚫ Example
String array[] = {"Ron", "Harry", "Hermoine"};

//enhanced for loop


for (String x:array)
{
System.out.println(x);
}

Simple For Loop:


/* for loop for same function
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
Summary
⚫ Features of java
⚫ Bytecode and execution
⚫ Operators and data types
⚫ Decision making and Looping in java

You might also like