Java Introduction
Java Introduction
By Sanghamitra Panda
Introduction to Java
• Why Java?
Java is an object oriented platform independent computer
programming language, mainly designed to develop internet
applications.
• C, C++ programming languages supports developing only stand alone
application, it can only be executed in current system, cannot be
executed from remote system via remote call.
Check Java Version on Windows
• Open the Windows Start menu in the bottom-left corner and type
cmd in the search bar.
• Then, open the Command Prompt once it appears in the search
results.
• A new window with the command prompt should appear. In it, type
the command java -version and hit Enter.
Java Version
• Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
• All Java components require names. Names used for classes, variables, and methods are called
identifiers.
• In Java, there are several points to remember about identifiers. They are as follows −
• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore
(_).
• After the first character, identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly, identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value.
• Examples of illegal identifiers: 123abc, -salary.
Java Variables
• String - stores text, such as "Hello". String values are surrounded by double
quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
• boolean - stores values with two states: true or false
Declaring (Creating) Variables
• To create a variable, you must specify the type and assign it a value:
• Syntax :
type variableName = value;
• Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.
• To create a variable that should store text, look at the following example:
• Example :
Create a variable called name of type String and assign it the value "John":
• You can also declare a variable without assigning the value, and assign
the value later:
• Example
• int myNum;
• myNum = 15;
• System.out.println(myNum);
• Note that if you assign a new value to an existing variable, it will
overwrite the previous value:
• Example
• Change the value of myNum from 15 to 20:
• Example
• final int myNum = 15;
• myNum = 20; // will generate an error: cannot assign a value to a
final variable
• Other Types
• int myNum = 5;
• float myFloatNum = 5.99f;
• char myLetter = 'D';
• boolean myBool = true;
• String myText = "Hello";
Class
name
Predefined
Method class name
name
Variable name : args, name
Display Variables
Example
String name = "John";
System.out.println("Hello " + name);
• You can also use the + character to add a variable to another variable:
• Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
• For numeric values, the + character works as a mathematical operator
(notice that we use int (integer) variables here):
• Example
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
Declare Many Variables
• Example
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Java Data Types
• Example
• Primitive data types - includes byte, short, int, long, float, double,
boolean and char
• Non-primitive data types - such as String, Arrays and Classes
Primitive Data Types
• A primitive data type specifies the size and type of variable values,
and it has no additional methods.
• There are eight primitive data types in Java:
• Numbers
• Primitive number types are divided into two groups:
• Integer types stores whole numbers, positive or negative (such as 123 or -
456), without decimals. Valid types are byte, short, int and long. Which type
you should use, depends on the numeric value.
• Even though there are many numeric types in Java, the most used for
numbers are int (for whole numbers) and double (for floating point
numbers).
Integer Types
• Byte
• The byte data type can store whole numbers from -128 to 127. This
can be used instead of int or other integer types to save memory
when you are certain that the value will be within -128 and 127:
• Example
• You should use a floating point type whenever you need a number
with a decimal, such as 9.99 or 3.14515.
• Float
• The float data type can store fractional numbers from 3.4e−038 to
3.4e+038. Note that you should end the value with an "f":
• Example:
• The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only
six or seven decimal digits, while double variables have a precision of
about 15 digits. Therefore it is safer to use double for most
calculations.
Scientific Numbers
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Booleans
• A boolean data type is declared with the boolean keyword and can
only take the values true or false:
• Example
• The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c':
• Example
Example:
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
Example
• First, the value of the variable a incremented by 1 and store in the memory
location of variable a.
• Second, the value of variable a assign to the variable x.
public class Main {
public static void main(String[] args) {
int x = 5;
++x;
System.out.println(x);
}
}
public class GFG {
public static void main(String[] args)
{
int a = 10;
int b = ++a;
11
public class GFG {
public static void main(String[] args)
{
// Declaring and initializing variable
int a = 10;
int b = ++a;
Output:-
a: 11
x: 10
• Decrement Operators ( -- )
• Pre-decrement operator in Java ( --a )
• First, the value of a decremented by 1 and store in the memory
location of variable a.
• Second, the value of the variable a assigned to the variable x.
class PreDecrementOperator{
public static void main(String[] args) {
int a, x;
a = 10;
x = --a;
System.out.println("a: "+a);
System.out.println("x: "+x);
}
}
Output:-
x: 9
y: 9
public class Main {
public static void main(String[] args) {
int x = 5;
--x;
System.out.println(x);
}
}
• Post-decrement operator in Java ( a-- )
• First, value of variable a will assign to the variable x.
• Second, the value of a decremented by 1 and store in the memory
location of the variable a.
class PostDecrementOperator{
public static void main(String[] args) {
int a, x;
a = 10;
x = a--;
System.out.println("a: "+a);
System.out.println("x: "+x);
}
}
Output:-
a: 9
x: 10
Java Comparison Operators
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x == y); // returns false because 5 is not equal to 3
}
}
Output: False
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x != y); // returns true because 5 is not equal to 3
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x > y); // returns true because 5 is greater than 3
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x >= y); // returns true because 5 is greater, or
equal, to 3
}
}
Output: true
Java Logical Operators
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 && x < 10); // returns true because 5 is
greater than 3 AND 5 is less than 10
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 || x < 4); // returns true because one of the
conditions are true (5 is greater than 3, but 5 is not less than 4)
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false because ! (not)
is used to reverse the result
}
}
Output: false
Java Assignment Operators
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
int x = 10;
public class Main {
public static void main(String[] args) {
int x = 5;
x += 3;
System.out.println(x);
}
}
Output :8
public class Main {
public static void main(String[] args) {
int x = 5;
x -= 3;
System.out.println(x);
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
x %= 3;
System.out.println(x);
}
}
// returns the remainder of the two numbers after division.
(/=) operator:
This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current
value of the variable on the left by the value on the right and then assigning the quotient to
the operand on the left.
Syntax:
num1 /= num2;
Example:
a /= 10
This means,
a = a / 10
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 20, num2 = 10;
Example:
Output
x&y=8
Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values,
i.e., if either of the bits is 1, it gives 1, else it shows 0.
Example:
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values,
i.e., if corresponding bits are different, it gives 1, else it shows 0.
Example:
This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes
every 0 to 1, and every 1 to 0.
Example:
~ 0101
________
1010 = 10 (In decimal)
// Java program to illustrate
// bitwise operators // bitwise not
// ~0101=1010
public class operators { // will give 2's complement of 1010 = -6
public static void main(String[] args) System.out.println("~a = " + ~a);
{
// Initial values // can also be combined with
int a = 5; // assignment operator to provide shorthand
int b = 7; // assignment
// a=a&b
// bitwise and a &= b;
// 0101 & 0111=0101 = 5 System.out.println("a= " + a);
System.out.println("a&b = " + (a & b)); }
}
// bitwise or Output
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b)); a&b = 5
a|b = 7
// bitwise xor a^b = 2
// 0101 ^ 0111=0010 = 2 ~a = -6
System.out.println("a^b = " + (a ^ b)); a= 5
Java Left Shift Operator Example
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Exercise
• Write a program to display any message:
• Length and breadth of a rectangle are 5 and 7 respectively. Write a
program to calculate the area and perimeter of the rectangle.
• Write a program to calculate the perimeter of a triangle having sides of
length 2,3 and 5 units.
• Write a program to add 8 to the number 2345 and then divide it by 3. Now,
the modulus of the quotient is taken with 5 and then multiply the resultant
value by 5. Display the final result.
• Now, solve the above question using assignment operators (eg. +=, -=, *=).
• Write a program to check if the two numbers 23 and 45 are equal.
Java Strings
Strings are used for storing text.
The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):
Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)
If you add two strings, the result will be a string concatenation:
Example
String x = "10";
String y = "20";
String z = x + y; // z will be 1020 (a String)
If you add a number and a string, the result will be a string concatenation:
Example
String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)
Keywords
The Java programming language has total of 50 reserved keywords which have special meaning for
the compiler and cannot be used as variable names. Following is a list of Java keywords in
alphabetical order, click on an individual keyword to see its description and usage example.
abstract assert boolean break byte
Category Keywords
Access modifiers private, protected, public
Class, method, abstract, class, extends, final, implements,
variable modifiers interface, native,new, static, strictfp, synchronized, transient,
volatile
Flow control break, case, continue, default, do,
else, for, if, instanceof, return,switch, while
Package control import, package
Primitive types boolean, byte, char, double, float, int, long, short
Error handling assert, catch, finally, throw, throws, try
Enumeration enum
Others super, this, void
Unused const, goto
Java Control Statements | Control Flow in Java
• Java compiler executes the code from top to bottom. The statements
in the code are executed according to the order in which they appear.
However,
• 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.
• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement
1) 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.
if(condition) {
statement 1; //executes when condition is true
}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
2) if-else statement
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Exercise
• 1. Write a Java program to get a number from the user and print
whether it is positive or negative.
• Write a Java program to solve quadratic equations (use if, else if and
else)
• 3. Take three numbers and print the greatest number.
• 4. Write a Java program to find the number is even or odd.
• 5.Write a Java program that takes a year from user and print whether
that year is a leap year or not
public class Exercise1 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int input=5;
if (input > 0)
{
System.out.println("Number is positive");
}
else if (input < 0)
{
System.out.println("Number is negative");
}
else
{
System.out.println("Number is zero");
}
}
}
public class Main { else if (determinant == 0) {
// two real and equal roots
public static void main(String[] args) { // determinant is equal to 0
// so -b + 0 == -b
// value a, b, and c root1 = root2 = -b / (2 * a);
double a = 2.3, b = 4, c = 5.6; System.out.format("root1 = root2 = %.2f;", root1);
double root1, root2; }
// check if determinant is greater than 0 // roots are complex number and distinct
if (determinant > 0) { double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
// two real and distinct roots System.out.format("root1 = %.2f+%.2fi", real, imaginary);
root1 = (-b + Math.sqrt(determinant)) / (2 * a); System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
root2 = (-b - Math.sqrt(determinant)) / (2 * a); }
}
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2); }
}
else
System.out.println(num3+" is the largest Number");
}
}
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Leap Year Example:
• It can be used to replace multiple lines of code with a single line, and
is most often used to replace simple if else statements:
• Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Example
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
}
Example: }
else if(marks>=80 && marks<90){
//Java Program to demonstrate the use of If else-if ladder. System.out.println("A grade");
//It is a program of grading system for fail, D grade, C grade, B }else if(marks>=90 && marks<100){
grade, A grade and A+.
System.out.println("A+ grade");
public class IfElseIfExample {
}else{
public static void main(String[] args) {
System.out.println("Invalid!");
int marks=65;
}
}
if(marks<50){
}
System.out.println("fail");
}
Output:
else if(marks>=50 && marks<60){
System.out.println("D grade");
C grade
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Output:
NEGATIVE
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
}
}
Example:
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.
Points to Remember
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
• 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.
• The case value can have a default label which is optional.
Syntax:
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;
}
Example:
• The Java for loop is used to iterate a part of the program several
times. If the number of iteration is fixed, it is recommended to use for
loop.
• A simple for loop is the same as C/C++. We can initialize the variable, check
condition and increment/decrement value. It consists of four parts:
• Initialization: It is the initial condition which is executed once when the
loop starts. Here, we can initialize the variable, or we can use an already
initialized variable. It is an optional condition.
• Condition: It is the second condition which is executed each time to test
the condition of the loop. It continues execution until the condition is false.
It must return boolean value either true or false. It is an optional condition.
• Increment/Decrement: It increments or decrements the variable value. It
is an optional condition.
• Statement: The statement of the loop is executed each time until the
second condition is false.
Syntax:
Output:
*
**
***
****
*****
ForExample.java
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
1.Write a program to print even values between 0 and 10:
******
*****
****
***
**
*
3. . Write a program to print pattern like this.
12
23
44
56
78
1.public class even {
public static void main(String[] args) {
The Java while loop is used to iterate a part of the program repeatedly
until the specified Boolean condition is true. As soon as the Boolean
condition becomes false, the loop automatically stops.
while (condition){
//code to be executed
I ncrement / decrement statement
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Example
public class Test {
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
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);
Example
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Java Break Statement
We can use Java break statement in all types of loops such as for loop
, while loop
and do-while loop
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Continue Statement
The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for
loop or while loop.
The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop,
while loop and do-while loop.
//Java Program to demonstrate the use of
continue statement
//inside the for loop.
Output:
public class ContinueExample {
public static void main(String[] args) { 1
//for loop
2
for(int i=1;i<=10;i++){ 3
if(i==5){ 4
//using continue statement
6
continue;//it will skip the rest statement 7
} 8
System.out.println(i);
9
} 10
}
}
Java Methods
• Methods are used to perform certain actions, and they are also
known as functions.
• Why use methods? To reuse code: define the code once, and use it
many times.
Create a Method
• A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own methods to perform certain
actions:
• Example
// Liam is 5
// Jenny is 8
// Anja is 31
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.)
instead of void, and use the return keyword inside the method:
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}
In the example below, we overload the plusMethod method to work for both int and double:
Example
Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.
Exercise
• Write a program with a method named getTotal that accepts two integers
as an argument and return its sum. Call this method from main( ) and print
the results.
• Write a method named isEven that accepts an int argument. The method
should return true if the argument is even, or false otherwise.
• A prime number is a number that is evenly divisible only by itself and 1. For
example, the number 5 is prime because it can be evenly divided only by 1
and 5. The number 6, however, is not prime because it can be divided
evenly by 1, 2, 4, and 6.Write a method named isPrime, which takes an
integer as an argument and returns true if the argument is a prime number,
or false otherwise. Also write main method that displays prime numbers
between 1 to 500.
class Prime /*Simple prime program*/
{
public static void main(String[] args)
{
int n=9;
boolean prime =true;
for(int i=2;i<n; i++)
{
if(n%i ==0)
{
prime=false;
break;
}
}
System.out.println(prime);
}
public class PrimeNumbers
{
public static void main(String[] args)
{
for(int i = 1; i <= 500; i++)
{
if(isPrime(i))
{
System.out.print(i + " "); } } }
public static boolean isPrime(int number)
{
for(int j = 2; j < number; j++)
{
if(number % j== 0)
{
return false;
}
}
return true;
}
}