Ava Identifiers, Variables, Datatype, Operators, Control Statement
Ava Identifiers, Variables, Datatype, Operators, Control Statement
TOPICS COVERED-
PART-1 :-
➢ Introduction to Java and Features
➢ Writing First Program and Basic Input/Output in Java
➢ Identifiers in Java
➢ Variables in Java
➢ Data Types in Java
➢ Operators in Java
➢ Sample Problems|Operators, Data Type, Input/Output
➢ Decision Control Statements
(If,Else,Switch,Break,Continue)
PART -2 :- (UPCOMING)
➢ Loops in Java
➢ Methods in Java
➢ Sample Problems|(Decision, Loops,Arrays & Strings)
➢ Arrays in Java
➢ Strings in Java
PART-1 :-
1.Introduction to Java and Features-
Getting started with any programming language should be purposeful,
we must understand the features and power of the programming
language to develop a deep interest in it.
Java was developed after the C and C++ around 1991. We can consider
Java as a complete package for software developers to play with it for
a variety of applications they want to build.
Output:
Hello, World
class HelloWorld
Like in C/C++, main method is the entry point for your application
and will subsequently invoke all the other methods required by
your program.
3. The next line of code is shown here. Notice that it occurs inside
main( ).
System.out.println("Hello, World");
This line outputs the string "Hello, World" followed by a new line
on the screen. Output is actually accomplished by the built-in
println( ) method. System is a predefined class that provides
access to the system, and out is the variable of type output
stream that is connected to the console.
Important Points :
In Java, there are three different ways of reading input from the user in
the command line environment(console).
Drawback: :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new
InputStreamReader(System.in));
This is probably the most preferred method to take input. The main
purpose of the Scanner class is to parse primitive types and strings
using regular expressions; however, it can also be used to read input
from the user in the command line.
Advantages:
Drawback:
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b); }}
It has been becoming a preferred way for reading user’s input from the
command line. In addition, it can be used for reading password-like
input without echoing the characters entered by the user; the format
string syntax can also be used (like System.out.printf()).
Advantages:
Drawback:
System.out.println(name);
3.Identifiers in Java-
Java Identifiers
In programming languages, identifiers are used for identification
purposes. In Java, an identifier can be a class name, method name,
variable name, or label. For example :
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
sum_of_array
geeks123
Examples of invalid identifiers :
Note : The keywords const and goto are reserved, even though they are
not currently used. In place of const, the final keyword is used. Some
keywords like strictfp are included in later versions of Java.
4.Variables in Java-
A variable is a name given to a memory location. It is the basic unit of
storage in a program.
Examples:
Types of variables
There are three types of variables in Java:
• Local Variables
• Instance Variables
• Static Variables
int age = 0;
age = age + 5;
obj.StudentAge();
Output:
Student age is : 5
In the above program the variable age is a local variable in the function
StudentAge(). If we use the variable age outside StudentAge() function,
the compiler will produce an error as shown in below program.
Sample Program 2:
int age = 0;
age = age + 5;
Output:
Sample Program:
import java.io.*; {
{ { //first object
} obj2.engMarks = 80;
System.out.println(obj2.mathsMarks);
System.out.println(obj1.engMarks);
System.out.println(obj2.phyMarks);
System.out.println(obj1.mathsMarks);
}
System.out.println(obj1.phyMarks); }
Output:
class_name.variable_name;
Sample Program:
import java.io.*;
class Article {
Article.rating = 4.5;
output:
• Each object will have its own copy of instance variable whereas
We can only have one copy of a static variable per class
irrespective of how many objects we create.
• Changes made in an instance variable using one object will not be
reflected in other objects as each object has its own copy of
instance variable. In case of static variable, changes will be
reflected in other objects as static variables are common to all
object of a class.
• We can access instance variables through object references and
Static Variables can be accessed directly using class name.
• Syntax for static and instance variables:
class Example
{
static int a; //static variable
int b; //instance variable
}
Primitive data
Primitive data are only single values; they have no special capabilities.
There are 8 primitive data types
1
boolean true or false false true, false
bit
two's
8
byte complement 0 (none)
bits
integer
unicode 16
char \u0000 'a','\n','\u0041'
character bits
two's
16
short complement 0 (none)
bits
integer
two's
32
int complement 0 -1,0,1
bits
integer
two's
64
long complement 0 -1L,0L,1L
bits
integer
IEEE 754
32
float floating 0.0 -1.23e100f,2.45e100f
bits
point
IEEE 754
64 -
double floating 0.0
bits 3.45e300d,4.56e245d
point
Class DEMO
boolean b = true;
if (b == true)
System.out.println("Hi DEMO");
• Output:
Hi DEMO
o Size: 8-bit
o Value: -128 to 127
class DEMO
byte a = 126;
System.out.println(a);
a++;
System.out.println(a);
a++;
System.out.println(a);
a++;
System.out.println(a);
Output:
126
127
-128
-127
o Size: 16 bit
o Value: -32,768 to 32,767 (inclusive)
• int: It is a 32-bit signed two's complement integer.
o Size: 32 bit
o Value: -231 to 231-1
Note: In Java SE 8 and later, we can use the int data type to
represent an unsigned 32-bit integer, which has value in the
range [0, 232-1]. Use the Integer class to use int data type as an
unsigned integer.
o Size: 64 bit
o Value: -263 to 263-1.
Note: In Java SE 8 and later, you can use the long data type to
represent an unsigned 64-bit long, which has a minimum value of
0 and a maximum value of 264-1. The Long class also contains
methods like compareUnsigned, divideUnsigned etc., to support
arithmetic operations for unsigned long.
o Size: 32 bits
o Suffix : F/f Example: 9.8f
Note: Both float and double data types were designed especially
for scientific calculations, where approximation errors are
acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and
use BigDecimal class instead.
{ // short s1 = 87878787878;
char a = 'G';
// for float use 'f' as suffix
// Integer data type is generally
float f = 4.7333434f;
// used for numeric values
System.out.println("char: " + a);
int i=89;
System.out.println("integer: " + i);
// use byte and short if memory is a
constraint System.out.println("byte: " + b);
// byte b1 = 7888888955; }
short s = 56; }
Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
6.Operators in Java-
Java provides many types of operators, which can be used according to the need.
They are classified based on the functionality they provide. Mostly used operators
are discussed below :
Output:
a+b = 30
a-b = 10
x+y = ThankYou
a*b = 200
a/b = 2
a%b = 0
Unary Operators: Unary operators need only one operand. They are used to
increment, decrement, or negate a value.
// unary operators
// pre-increment operator
c = ++a;
c = b++;
// pre-decrement operator
c = --d;
// post-decrement operator
c = e--;
Output:
Value of c (++a) = 21
Value of c (b++) = 10
Value of c (--d) = 19
Value of c (e--) = 40
Value of !condition =false
variable = value;
o +=, for adding left operand with right operand and then assigning it to
variable on the left.
o -=, for subtracting left operand with right operand and then assigning
it to variable on the left.
o *=, for multiplying left operand with right operand and then assigning
it to variable on the left.
o /=, for dividing left operand with right operand and then assigning it to
variable on the left.
o %=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
int a = 5;
a += 5; //a = a+5;
// assignment operators
c = b;
// compile.
// c = d;
a = a + 1;
b = b - 1;
e = e * 2;
f = f / 2;
a = a - 1;
b = b + 1;
e = e / 2;
f = f * 2;
a += 1;
b -= 1;
e *= 2;
f /= 2;
Output :
Value of c =10
a,b,e,f = 21,9,20,2
a,b,e,f (using shorthand operators)= 21,9,20,2
1. Relational Operators : These operators are used to check for relations such
as equality, greater than, less than. They return boolean result after the
comparison and are extensively used in looping statements as well as in
conditional if else statements. General format is,
o == , Equal to : returns true of left hand side is equal to right hand side.
o != , Not Equal to : returns true of left hand side is not equal to right
hand side.
o < , less than : returns true of left hand side is less than right hand
side.
o <= , less than or equal to : returns true of left hand side is less than or
equal to right hand side.
o > , Greater than : returns true of left hand side is greater than right
hand side.
o >= , Greater than or equal to: returns true of left hand side is greater
than or equal to right hand side.
// relational operators
Output :
a == b :false
a < b :false
a <= b :false
a > b :true
a >= b :true
a != b :true
x == y : false
condition==true :true
Logical Operators : These operators are used to perform "logical AND" and "logical
OR" operations, i.e., the function similar to AND gate and OR gate in digital
electronics. One thing to keep in mind is that the second condition is not evaluated
if the first one is false, i.e., it has short-circuiting effect. It is used extensively to test
for several conditions for making a decision.
Conditional operators are:
o && , Logical AND : returns true when both conditions are true.
o || , Logical OR : returns true if at least one condition is true.
// logical operators
{ (uuid.equals(y) &&
upwd.equals(x))) {
String x = "Sher";
System.out.println("Welcome
String y = "Locked"; user.");
Output :
Enter username:Sher
Enter password:Locked
Welcome user.
The above statement means that if the condition evaluates to true, then execute the
statements after the '?' else execute the statements after the ':'.
// ternary operator.
//numbers
Output :
o & , Bitwise AND operator: returns bit by bit AND of input values.
o | , Bitwise OR operator: returns bit by bit OR of input values.
o ^ , Bitwise XOR operator: returns bit by bit XOR of input values.
o ~ , 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.
// bitwise operators
{ // 0101 ^ 0111=0010
int b = 0x0007;
// can also be combined with
// bitwise and
// assignment operator to provide
// 0101 & 0111=0101 shorthand
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
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
o << , Left shift operator: shifts the bits of the number to the
left and fills 0 on voids left as a result. Similar effect as of
multiplying the number with some power of two.
o >> , 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. Similar
effect as of dividing the number with some power of two.
o >>> , 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.
// shift operators
int a = 0x0005;
int b = -10;
// similar to 5*(2^2)
// similar to 5/(2^2)
Output :
a2 = 1
b>>>2 = 1073741821
Precedence and associative rules are used when dealing with hybrid equations
involving more than one type of operator. In such cases, these rules determine
which part of the equation to consider first as there can be many different
valuations for the same equation. The below table depicts the precedence of
operators in decreasing order as magnitude with the top representing the highest
precedence and the bottom shows the lowest precedence.
int a = 20, b = 10, c = 0, d = 20, e = 40, f = // e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)
30;
System.out.println("a+b*d-e/f = "+(a + b *
// precedence rules for arithmetic d - e / f));
operators.
}
// (* = / = %) > (+ = -)
}
Output:
a+b/d = 20
a+b*d-e/f = 219
Be a Compiler: Compiler in our systems uses lex tool to match the greatest match
when generating tokens. This creates a bit of problem if overlooked. For example,
consider the statement a=b+++c;, to many of the readers this might seem to create
compiler error. But this statement is absolutely correct as the tokens created by lex
are a, =, b, ++, +, c. Therefore this statement has similar effect of first assigning b+c
to a and then incrementing b. Similarly, a=b+++++c; would generate error as tokens
generated are a, =, b, ++, ++, +, c. which is actually an error as there is no operand
after second unary operand.
Output:
Using + over (): When using + operator inside system.out.println() make sure to do
addition using parenthesis. If we write something before doing addition, then string
addition takes place, that is associativity of addition is left to right, and hence
integers are added to string first producing a string, and string objects concatenates
when using +, therefore it can create unwanted results.
int x = 5, y = 8;
// concatenates x and y
// further concatenated.
// addition of x and y
Output:
Concatenation (x+y)= 58
Addition (x+y) = 13
•if
•if-else
•nested-if
•if-else-if
•switch-case
•jump - break, continue, return
These statements allow you to control the flow of your program's execution based upon
conditions known only during the run time.
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
}
Here, condition after evaluation will be either true or false. if statement accepts boolean
values - if the value is true, then it will execute the block of statements under it.
If we do not provide the curly braces '{' and '}' after if( condition ), then by default if
statement will consider the immediate one statement to be inside its block. For example,
if(condition)
statement1;
statement2;
Flow chart:
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 when 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.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
if-else-if ladder:Here, a user can decide among multiple options. The if statements
are executed from the top to bottom. 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 (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
jump:J ava supports three jump statement: break, continue, and return. These
three statements transfer control to other part of the program.
.
}
break label;
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. This is, in effect, a goto just past the body of the loop, to the loop's end.
The continue statement performs such an action.
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.
HIMANSHU KUMAR(LINKEDIN)
https://www.linkedin.com/in/himanshukumarmahuri
CREDITS- INTERNET
DISCLOSURE- ALL THE DATA AND IMAGES ARE TAKEN FROM GOOGLE AND INTERNET.