CREATIVE MULTIMEDIA INSTITUTE
CH – 02
CORE CONCEPT
OF JAVA
Page | 1
CREATIVE MULTIMEDIA INSTITUTE
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it
means it is visible to all.
static is a keyword, if we declare any method as static, it is known as
static method. The core advantage of static method is that there is no need
to create object to call the static method. The main method is executed by
the JVM, so it doesn't require to create object to call the main method.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used print statement. We will learn about the
internal working of System.out.println statement later.
Page | 2
CREATIVE MULTIMEDIA INSTITUTE
Identifiers :
An identifier is a name given to a variable, a method, or a class.
To declare an identifier we must follow some rules :
Identifier may consist of letters (uppercase or lowercase), digits, underscore or a
dollar sign.
It must not start with a number.
No white space is allowed
No keyword can be used as identifier.
Some valid examples of identifiers:
Valid identifier :
sub1, mark1, first_value
Some invalid examples of identifiers :
1mark, first-value.
Literals :
In Java any constant value is known as literal.
The literal can be any one of the following
Integer literal
Floating-point literal
Character literal
Integer literal
Example :
int x=300;
Here x is a variable and 300 is value which is integer literal.
Floating point literal :
Example :
double d=39.86;
Here d is a variable and 39.86 is floating point literal.
Character literal :
Example :
char c=‘A’;
Page | 3
CREATIVE MULTIMEDIA INSTITUTE
Here c is a character type of variable and ‘A’ is a character literal.
Some character literals should be written using escape sequence character, which is back
slash (‘\’).
If we want to print some special character like quotes (“ ”) , we have to use back slash
Character literal :
Escape Sequence Meaning
\n To give new line
\t To give space as much as tab
\’ To print single quote
\” To print double quote
\\ To print back slash
White-spaces :
The white-space can be a space, a tab or a new line.
The extra white space are ignored by Java compiler.
Therefore if you write your program a single line it makes no difference.
The separators are used to separate the statements for each other.
For example,
The semicolon (;) is used to terminate a statement. The list of various separator is shown below.
Separators :
The separators are used to separate the statements for each other.
For example,
The semicolon (;) is used to terminate a statement. The list of various separator is
shown below.
Page | 4
CREATIVE MULTIMEDIA INSTITUTE
Separator Name Use
; Semicolon Used to terminate a statement
, Comma Used to declare more than one variables of same type. Also used in for()
loops to specify more than one conditions.
. Dot Used to access a variable or method of a class through object. Also used to
separate package from sub package.
: Colon Used to specify a label.
() Paren thesis Used in method declaration and method call. Also used in if conditions and
loops.
{} Braces Used to enclosed statements of methods, class or any block of code. Also
used to initialize an array.
[ ] Brackets Used to declare array and array elements.
Keywords :
Keyword is a pre-defined word. These words are reserved by programming language.
There are 49 keywords in Java which are reserved and each one has its unique meaning.
abstract assert boolean break byte case
catch char class const continue default
do double else extends final finally
float for goto if implements Import
instanceof int interface long native package
private protected public return static strictfp
super switch synchronized throw throws transient
try void while new short this
Page | 5
CREATIVE MULTIMEDIA INSTITUTE
Data Types :
In Java, every variable has a data type. They can be classified as follows…
Data Types
Integer Type Floating
- byte Character Boolean
Point Type
- short Type Type
- int - float - char - boolean
- long - double
Integer Data Type :
The byte, short, int and long are integer data types.
They all are signed types. So they can have positive as well as negative values.
Size
Type Range
(in bits)
byte 8 -128 to 127
short 16 -32,768 to 32767
Int 32 -2,14,74,83,648 to 2,14,74,83,647
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Page | 6
CREATIVE MULTIMEDIA INSTITUTE
Byte:
Byte is one byte data type.
Its size is 8 bits and it can store values between (-128 to 127)
To declare a byte type variable, we have to use byte as a keyword.
Example : byte a=10;
Short:
Short is a 16 bit data type. It can store values between -32768 to 32767
To declare a variable of a short type short keyword is used.
Example : short a=1000;
Int :
Size of int type is 32 bits. Its range is -231 to 231-1.
int keyword is used to declare an integer type variable.
Example :
int i, j;
Long :
Long type is of 64 bit store values.
To declare a long type variable long keyword is used.
Example :
long val=100000;
Floating point types:
The float and double are floating point type data types.
They are used to store floating point values. The size and range of these types are as
follows.
Type Size (in bits) Range
float 32 1.4e - 045 to 3.4e + 038
double 64 4.9e - 324 to 1.8e + 308
Float :
Float data type is used when no more precision is required. Its size is 32-bits.
It is generally used to store rupees, dollars, etc. with some less digit precision.
Example:
float f;
Double :
Double is a 64 bit data type. It stores data with double precision (keyword).
Therefore if we want to deal with the mathematical functions like sine, cosine, or want to
find square root of a number then double data type is used.
Example :
double d;
Page | 7
CREATIVE MULTIMEDIA INSTITUTE
Character Types
Type Size (in bits) Range
char 16 0 to 65,535
Char type is used to store a single character.
Example:
char c=‘A’;
char ch=65;
Both the variables c and ch have the same value.
Boolean type :
Type Size (in bits) Range
boolean 8 True or False
Boolean data type is 8 bit data type and used to store logical values. (true/false)
Every relational operator returns a boolean value.
Example :
boolean flag=false;
boolean isOK=true;
Type conversation and Type casting :
In Java, before assigning value to a variable, if their types are not same, type conversation
is necessary.
There are two types of type conversation
Implicit (Automatic) type conversion
Explicit type conversion
The implicit type conversion takes place automatically when the types are compatible
and the destination type are larger than the source type.
Page | 8
CREATIVE MULTIMEDIA INSTITUTE
Implicit (Automatic) type conversion :
All numeric data types are compatible with each other but not with char or boolean type.
Because char and boolean an are not compatible with each other.
Example :
Int a=10;
Long b;
B=a; // automatic type conversion
Explicit Type Conversion :
When in an expression the destination type is not larger than the source type, the
conversion will not be done automatically, but we have to do it explicitly by type casting.
For Example,
If we want to assign a long type value to an int type value, this will not done
automatically, but you have to use a cast.
The general form of type casting is:
Example: long x=100;
int i=(int)x;
Operators :
Meaning: Operator is a symbol that performs some operations on its operands and gives
the results.
Java has a rich set of operators. Operators in java can be divided in main eight categories.
1. Unary (Increment /Decrement)Operator,
2. Arithmetic Operator,
3. Shift Operator,
4. Relational Operator,
5. Bitwise Operator,
6. Logical Operator,
7. Ternary Operator
8. Assignment Operator.
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr
Arithmetic - * / % + -
Shift shift << Left Shirt >> Right shift
Relational comparison < > <= >=
equality == !=
Bitwise & |
Page | 9
CREATIVE MULTIMEDIA INSTITUTE
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %=
Arithmetic Operators :
Arithmetic Operators are those which are used in mathematical calculators such as
addition, multiplications etc.
In all these arithmetic operators we can use only numeric data type values such as
int or float, but we cannot use boolean type values in these operators.
Def. __ Demonstrate Use of arithmetic operators...
class test
{ public static void main(String args[])
{ float a=10, b=20, c;
c=a+b;
System.out.println("\nA+B = "+c);
c=a-b;
System.out.println("\nA-B = "+c);
c=a*b;
System.out.println("\nA x B = "+c);
c=a/b;
System.out.println("\nA / B = "+c);
}
}
The Modules Operator (%):
The modulus operator in Java is more powerful than other languages.
Because it can be applied to integer type values as well as floating point values.
It simply returns the reminder of division operation.
Page | 10
CREATIVE MULTIMEDIA INSTITUTE
Increment (++) / Decrement(--) Operators:
Both these operators are unary operators.
The increment operator increases the value of operand by one and the decrement
operator decreases the value of operand by one.
For Example:
a=a+1; is equivalent to a++; and
b=b-1; is equivalent to b--;
Here, these operators can be used in one of two forms: Postfix and Prefix.
Postfix operator is one which the operator is put after (post) the operand and in
Prefix operator the operator is put before (pre) the operand.
For Example:
x++ is same as ++x and y-- is same as -–y
int a=10, b=20;
int c=++a;
Here, value of c will 11 and a will be 11 too.
But, if we use postfix operator, like
int d=b++;
Then the value of d will be 20 and b will be 21.
Because in case of postfix operator the increment or decrement the happens after
(post) the assignment, and in prefix the increment or decrement happens before
assignment takes place. i.e.
a=10;
c=++a; ++a; a=a+1;
Here, c=11 and a=13
Relational Operators:
The relational operators in Java are used to check the relation between two
operands.
They return a Boolean value i.e. true or false.
The relational operators are listed below:
Page | 11
CREATIVE MULTIMEDIA INSTITUTE
Operator Description
== Is equal to
!= Is not equal to
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal to
Logical Operators:
Logical operators in Java are used to combine two or more Boolean conditions
together.
Here the operands must be of Boolean type variables or conditions and the results
returned is also a Boolean value.
Operator Description
&& Short-Circuit AND
|| Short-Circuit OR
! Logical NOT
The logical AND (&&) operators returns true if both the operands are true else
returns false.
Whereas the logical OR (||) operator returns false if both the operands are false
else returns true. Means it returns true if any one operand (condition) is true.
Conditional Operator:
C programming offers the conditional operator used in C language is ( ? ) question
mark and ( : ) column.
It is used for checking the condition and gives output according to the condition.
If condition is true then it will execute the first value or it will execute the second
value given in the syntax.
Syntax :
<Condition>?<True Value>:<False Value>
Page | 12
CREATIVE MULTIMEDIA INSTITUTE
Purpose:
If condition will be true then it will return the true value else it will return
the false value.
Example :
c=(a>b)?a:b;
Def.__ WAP to store two value in variables and check for big value.
class ConOp
{ public static void main(String args[])
{int a=12;
int b=100;
int c=(a>b)?a:b;
System.out.println(“Big Value is "+c);
}
}
Java Left Shift Operator :
The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.
Example
System.out.println(10<<1); // 1010 binary of 10 = 101000 =1 bit add on left
System.out.println(10<<2); // 1010 binary of 10 = 1010000 =2 bit add on left
Output:
20
40
Java Right Shift Operator :
The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.
System.out.println(10>>2);// 1010 binary = 101 right shift move = 101
System.out.println(20>>2);// 1010 binary = 101 right shift move = 10
Page | 13
CREATIVE MULTIMEDIA INSTITUTE
Bit wise operator :
Operators Symbol Uses
Bitwise AND & op1 & op2
Bitwise exclusive OR ^ op1 ^ op2
Bitwise inclusive OR | op1 | op2
Bitwise AND (&) :
It is a binary operator symbol &. It returns 1 if and only if both bits are 1, else returns 0.
Ex :
public static void main(String[] args)
{
int x = 9, y = 8;
// bitwise and
// 1001 & 1000 = 1000 = 8
System.out.println("x & y = " + (x & y));
}
Output :
x&y=8
Bitwise exclusive OR (^) :
It is a binary operator symbol ^ (caret). It returns 0 if both bits are the same, else returns 1.
Ex :
public static void main(String[] args)
{
int x = 9, y = 8;
// bitwise XOR
// 1001 ^ 1000 = 0001 = 1
System.out.println("x ^ y = " + (x ^ y));
}
Page | 14
CREATIVE MULTIMEDIA INSTITUTE
Output :
x^y=1
Bitwise inclusive OR (|) :
It is a binary operator symbol | (pronounced as a pipe). It returns 1 if either of the bit is 1, else returns 0.
Ex :
public static void main(String[] args)
{
int x = 9, y = 8;
// bitwise inclusive OR
// 1001 | 1000 = 1001 = 9
System.out.println("x | y = " + (x | y));
}
Output :
x|y=9
Assignment Operator in C :
The assignment operator is used to assign the value, variable and function to
another variable. Let's discuss the various types of the assignment operators such
as =, +=, -=, /=, *= and %=.
Example of the Assignment Operators:
A = 5; // use Assignment symbol to assign 5 to the operand A
B = A; // Assign operand A to the B
A+=B;
Control Structure:
There are two type of Control structure
Conditional
Looping
Page | 15
CREATIVE MULTIMEDIA INSTITUTE
In conditional statement there are optional environment available.
In looping statements we have to repeat same code one or more time.
Select Control Structure:
If Statement
Switch Statement
If Statement in Details
We can write conditional statement IF in different ways...
if (Simple if Without Else Statement)
if....else
Nested if (if within if)
if....else if ladder
if (Simple if without else) :
Syntax : if(condition)
{
statements;
}
Purpose:
If statement is the decision control statement. This statement will check the given
condition. If condition is TRUE then it executes given statements.
Def.__ WAP to store your age, Now check that you can VOTE or Not. (Using IF) :
int age=18;
if(age>18)
System.out.print("You Can Vote");
if(age<=18)
System.out.print("You Can’t Vote");
}
}
if....else :
Syntax : if(condition)
{ statement Group1; }
Page | 16
CREATIVE MULTIMEDIA INSTITUTE
else
{ statement Group2 ; }
Purpose:
If..else statement is a decision control statement.
If condition is TRUE then it execute given statements group1. If condition if
FALSE then it executes statement group2.
Def.__ WAP to store your age, Now check that you can VOTE or Not (Using if..else)
int age=18;
if(age>18)
System.out.print("You Can Vote");
else
System.out.print("You Can’t Vote");
}
}
if....else [ Nested ] :
Syntax :
if(Condition)
{ if(Condition)
{ }
else
{ }
}
Purpose:
If..else nested is also decision control statement.
If outer condition will be true then it will go inside and check inner condition.
This method is known as NESTED IF...ELSE
It will check conditions more then one time.
Example:
int a=12,b=23,c=1;
if(a>b){
If(a>c){
System.out.print(“a is max”);
}else{
System.out.print(“c is max”);
}else{
If(b>c){
System.out.print(“B is max”);
}else {
Page | 17
CREATIVE MULTIMEDIA INSTITUTE
System.out.print(“C is max”);
}
The if-else-if Ladder :
Syntax : if(condition1)
statement block1;
else if(condition2)
statement block2;
else if(condition3)
statement block3;
else
statement block n;
Purpose:
Here, condition1 is evaluated first, if it is true then the statement block 1 will
be executed. If condition1 is false then condition2 will be evaluated, if
condition2 is true then the statement block 2 will be executed. This will
happen until any one condition will be true. If all the condition are false then
the else part will be executed.
Def. WAP to store Student Percent and print its CLASS [ Distinction, First, Second,
Pass, *** ] (using if... else... if... ladder) :
int per=68;
if(per>=70)
System.out.print("Class = Dist");
else if(per>=60)
System.out.print("Class = First");
else if(per>=48)
System.out.print("Class = Second");
else if(per>=40)
System.out.print("Class = Pass");
else
System.out.print("Class = * * *");
switch... case :
Syntax :
switch(expression)
Page | 18
CREATIVE MULTIMEDIA INSTITUTE
{
case value1:
statement block1;
break;
case value2:
statement block2;
break;
case value3:
statement block3;
break;
case valueN:
statement blockN;
break;
default:
default statement block;
}
Purpose:
In switch statement, the expression gives one value which is compared with
the values written with case statements.
If one case is evaluated true then the statement block related to that case
will be executed.
Looping Statements:
If we want to execute one statement for one or more time, in programming
language there are some facility available for that.
In looping we have 2 type of looping structure available.
1. Entry control loop
2. Exit control loop
. Entry Control Loop
There are two types of entry control loops available
for loop
while loop
For... (Entry Control Loop) :
Syntax :
for(initialization;condition;increment or decrement)
Page | 19
CREATIVE MULTIMEDIA INSTITUTE
{ statement 1;
statement 2;
}
Purpose:
For loop is a counter loop. We can define number of loops with specified
number with condition.
Syntax explanation...
Initialization
Its a portion where we can define a value for counter variable.
Condition
We can specify the condition (logic) for counter loop.
Increment or Decrement in variable
We can increase or decrease in variable using this syntax.
Def.. Write a program to print your name 10 times. :
class args
{ public static void main(String args[])
{ int x;
for(x=1;x<=10;x++)
System.out.println("CREATIVE INSTITUTE");
}
}
while... (Entry Control Loop) :
Syntax :
while(condition)
{ statement 1;
statement 2;
}
Purpose:
While loop is a conditional loop. We can set condition as required. It loops
till the condition will be true.
class args
{ public static void main(String args[])
{ int x=1;
while(x<=10)
{ System.out.println(x);
x++;
Page | 20
CREATIVE MULTIMEDIA INSTITUTE
}
}
}
do...while (Exit Control Loop) :
Syntax :
do
{ statement 1;
statement 2;
}while(condition);
Purpose:
Do...While loop is a conditional loop. We can set condition as required. It
runs minimum one time. Then it loops till the condition will be true.
Def.. Print 1 to 10 using do while loop :
class args
{ public static void main(String args[])
{ int x=1;
do
{ System.out.println(x);
x++;
}while(x<=10);
}
}
Page | 21
CREATIVE MULTIMEDIA INSTITUTE
JAVA Keywords :
Break statement… :
Syntax :
break;
Purpose :
The break statement is used to terminate loops or to exit from switch case.
The break statement will break or terminate the inner-most loop.
We can use break statement within while, do-while, for or switch case
statement.
CONTINUE STATEMENT… :
Syntax :
continue;
Purpose :
Continue statement is used to skip or to bypass some step or interaction of
looping structure.
It does not terminate the loop but just skip the particular sequence of the
loop structure.
Return Statement :
The return statement cause the control to be transferred back from a method to the
caller of the method.
Syntax :
return;
Example :
public static void main(String[] args) {
int i;
for(i=1;i<=10;i++)
{
System.out.println(i);
if(i==5)
{
return;
}
}
}
Page | 22
CREATIVE MULTIMEDIA INSTITUTE
Output :
1
2
3
4
5
Assertions in Java :
An assertion allows testing the program. An assertion is achieved using the assert
statement in Java. While executing assertion, it is believed to be true. If it fails, JVM
throws an error named AssertionError. It is mainly used for testing purposes during
development.
Ex :
// Java program to demonstrate syntax of assertion
import java.util.Scanner;
first.java
class first {
public static void main(String args[])
{
int value = 15;
assert value >= 20 : " Underweight";
System.out.println("value is " + value);
}
}
Cmd Run Program :
Before Add exception :
Javac first.java
Java first
Output :
Value : 15
After Add exception :
Javac first.java
java -ea first
output : Exception in thread "main" java.lang.AssertionError: Underweight
Page | 23
CREATIVE MULTIMEDIA INSTITUTE
Java Strictfp Keyword :
strictfp is a modifier that stands for strict floating-point which was not introduced in the
base version of java as it was introduced in Java version 1.2. It is used in java for
restricting floating-point calculations and ensuring the same result on every platform
while performing operations in the floating-point variable.
Floating-point calculations are platform-dependent i.e. different output(floating-point
values) is achieved when a class file is run on different platforms(windows / mac / unix ).
To solve this type of issue, strictfp keyword was introduced in JDK 1.2 version by
following standards for floating-point calculations.
Ex .
float b=10;
strictfp void get()
{
System.out.println("Ans="+b/3);
}
Page | 24