Java Programming Basics Explained
Java Programming Basics Explained
1
Chapter Contents
▪ Identifiers
▪ Keywords
▪ Input/output
▪ Variables
▪ Data Types
▪ Operators
▪ Precedence of operators
▪ Control structure 2
Simple Java Program
Step 1 ) Copy the following code into a notepad.
▪ The JVM loads the class specified by Class Name and uses that class name to
invoke method main.
▪ Declaring main as static allows the JVM to invoke main without creating an
5
instance of the class.
Java Tokens
o In Java, Tokens are the smallest elements of a program that is meaningful to the
compiler.
o They are also known as the fundamental building blocks of the program.
oTokens can be classified as follows:
▪ Keywords
▪ Identifiers
▪ Constants/Literals
▪ Operators
▪ Separators
6
Java Keywords
✓Keywords are predefined identifiers reserved by Java for a specific purpose.
✓These keywords cannot be used as names for a variable, class or method [Identifiers].
7
Java Identifiers
o Identifiers are tokens that represent names of variables, methods, classes,
packages and interfaces etc.
• An identifier must start with a letter, an underscore (_), or a dollar sign ($).
• It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length. 8
Java Literals
o Literals are tokens that do not change or are constant.
o The different types of literals in Java are:
• Integer Literals: decimal (base 10), hexadecimal (base 16), and octal (base 8).
Example: int x=5; //decimal
• Floating-Point Literals: represent decimals with fractional parts.
Example: float x=3.1415;
• Boolean Literals: have only two values, true or false (0/1).
Example: boolean test=true;
• Character Literals: represent single Unicode characters. A Unicode character is a
16-bit character set that replaces the 8-bit ASCII character set.
Example: char ch=‘A’;
• String Literals: represent multiple/sequence of characters enclosed by double
quotes.
Example: String str=“Hello World”;
9
Separators
▪ Separators are used to separate different parts of the codes.
▪ It tells the compiler about completion of a statement in the program
Example: Semicolon, comma, dot, curly brackets, parenthesis
Separator Role Descriptions
{} (Curly Used to define code blocks like the body of methods, loops, or
Braces) conditional statements.
▪ Comment texts are not part of the program and compiler ignores executing them.
3. Documentation Comments: The documentation comment begins with a /** and ends
with a */.
12
Java Input Statements
o Scanner and BufferedReader class are used to accept data from user/keyboard.
o Scanner class
• Java provides various ways to read input from the keyboard, the [Link] package
• Reads input from the user and pass the input stream ([Link]) in the
constructor of Scanner class.
Scanner in = new Scanner([Link]);
13
import [Link];
public class javaIO
{
public static void main(String[] args) {
String name;
int x;
double y;
Scanner input = new Scanner( [Link] ); //obtain input from command window
[Link]("Enter Your Name: "); //prompt user to enter name
name= [Link](); // Obtain user input(line of text/string) from keyboard
[Link]("Enter x, y:"); //prompt user to enter values of x & y
x= [Link](); // Obtain user integer input from keyboard
y= [Link](); // Obtain user double input from keyboard
[Link]("Your Name is: "+name);
[Link]("The Value of x is: "+x);
[Link]("The Value of y is: "+y);
}
14
}
o BufferedReader
▪ Reads text from a character-input stream to provide efficient reading of
characters, arrays, and lines.
▪ It can be used to read data line by line by readLine() method and makes the
performance fast.
15
//Accepting inputs using BufferedReader
import [Link];
import [Link];
import [Link];
public class javaIO {
public static void main( String[] args )throws IOException
{
String name;
int age;
String str;
BufferedReader br= new BufferedReader(new InputStreamReader( [Link]) );
[Link]("Please Enter Your Name:");
name=[Link]();
[Link]("Please Enter Your Age:");
str=[Link](); //to read an input data
age=[Link](str); //convert the given string int to integer
[Link]("Hello "+ name +"! Your age is: "+age);
16
} }
Data Types in java
o Data types specify the different sizes and values that can be stored in the variable.
▪ They are the building blocks of data manipulation and cannot be further divided
into simpler data types.
▪ Example: Boolean, char, byte, short, int, long, float and double.
18
Enumeration (enum) in Java
▪ Java enumerations are a special type that enables a variable to be a set of
predefined constants.
▪ Mainly useful when we have a small set of possible values for an item like
directions, days of week, etc.
▪ In the Java programming, you define an enum type by using the enum keyword.
▪ The syntax to create an enum :
enum EnumName
{
CONSTANT1, CONSTANT2, CONSTANT3;
} 19
Example of enum demo in Java
public class MainClass
{
enum Colour
{
RED,
BLUE, Output
GREEN, BLUE
YELLOW
}
public static void main(String[] args)
{
Colour c = [Link];
[Link](c);
}
20
}
Variables
▪ A variable is an item of data used to store state of objects and variable has a data
type and a name.
▪ The data type indicates the type of value that the variable can hold and the variable
name must follow rules for identifiers.
▪ Declaring Variables: The variable declaration tells the compiler to allocate appropriate
memory space for the variable based on its data type.
}
Java Operators
o An operator is a symbol that operates on one or more arguments to produce a
result.
25
Demonstration of arithmetic operators
public class ArithmeticOperators
x <= y Less than or equal to True if x is less than or equal to y, otherwise false.
x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.
}
Logical operators Demonstration 2
import [Link]; //import statement for accepting input from keyboard
public class LogOps {
public static void main(String[] args) {
double mark;
Scanner input = new Scanner( [Link] ); //Create Scanner to obtain input from command window
[Link]( "Enter Student Mark: "); // prompt user to enter mark
mark = [Link](); // obtain user input from keyboard
if(mark<0 || mark>100) {
[Link]("Invalid Input! Mark Must be between 0 & 100");
}
else if(mark>80 && mark<=100) {
[Link]("A");
}
else if(mark>=60 && mark<80) {
[Link]("B") ;
} else {
[Link](“F");
30
} }}
Increment & Decrement Operators
o The auto increment (++) and auto decrement (--) operators provide a convenient
way of, respectively, adding and subtracting 1 from a numeric variable.
o When used in prefix form, the operator is first applied and the outcome is then
used in the expression.
o When used in the postfix form, the expression is evaluated first and then the
operator applied. Example: int k=5;
31
Illustration of increment & decrement operators
public class IncDec
{
public static void main(String[] args)
{
int num;
num = 10; // assign 10 to num
[Link](num ); // prints 10
[Link](++num ); // prints 11 (Prefix)
[Link](num ); // prints11
Program Output
[Link](num++ ); // prints 11 (Postfix) 10
[Link](num ); // prints 12 11
11
}
11
} 12
32
Precedence of Java operators
o The order in which operators are evaluated in an expression is significant and is
determined by precedence rules.
33
34
Example
public class OperatorPrecedence
{
Output
public static void main(String[] args)
a+b/d = 20
{
a+b*d-e/f = 219
int a = 20, b = 10, c = 0;
int d = 20, e = 40, f = 30;
// (* = / = %) > (+ = -) precedence rules
[Link]("a+b/d = " + (a + b / d));
[Link]("a+b*d-e/f = "+ (a + b * d - e / f));
}
}
35
Java Expressions
36
▪ Arithmetic Expressions: These involve mathematical operations and produce
a numerical result.
int sum = 2 + 3; // Evaluates to 5
double product = 2.5 * 4.0; // Evaluates to 10.0
37
▪ Assignment Expressions: These assign a value to a variable. The expression itself
evaluates to the assigned value.
int count = 12; // Evaluates to 12
String name = “Bob"; // Evaluates to “Bob"
▪ Method Invocation Expressions: These call a method and evaluate to the return
value of that method.
int length = [Link](); // Evaluates to the length of myString
[Link]("Hello"); // Evaluates to void (no return value)
38
Java Statements & Blocks
▪ A statement is one or more line of code terminated by semicolon (;).
Example: int x=5;
[Link](“Hello World”);
▪ A block is one or more statements bounded by an opening & closing curly braces
that groups the statements as one unit.
Example: public static void main(String args[]) {
int x=5;
int y=10;
char ch=‘Z’;
[Link](“Hello ”);
[Link](“World”); //Java Block of Code
[Link](“x=”+x);
[Link](“y=”+y);
[Link](“ch=”+ch);39
}
Simple Type Conversion/Casting
o Type casting enables to convert the value of one data from one type to another type.
(int) 3.14; // converts 3.14 to an int to give 3
(double) 2; // converts 2 to a double to give 2.0
(char) 122; // converts 122 to a char whose code is 122 (z)
Example
public class TypeCasting {
public static void main(String[] args) {
float x=3.14f;
int ascii = 65;
[Link]("Demonstration of Simple Type Casting");
[Link]((int) x); //3
[Link]((long) x); //3
[Link]((double) x); //3.140000104904175
[Link]((short) x); //3
[Link]((char) ascii); //A
} }
40
Java Control Structure
o The statement is the instruction given to the computer that performs specific types
of work. They can make decisions and repetitive tasks.
❖ if statement
o The if-statement specifies that a statement (or block of code) will be executed if
and only if a certain boolean statement is true.
o Syntax: if(condition)
statements;
o The first expression is evaluated. If the outcome is true then statement is executed.
Otherwise, nothing happens.
o Example: When dividing two values, we may want to check that the denominator
is nonzero. if(y!=0)
42
div=x/y;
❖ if-else statement
44
}
Nested if-else-if statement
▪ An if statement inside another if statement is known as nested if statements.
▪ Nested if statements are used if there is a sub condition to be tested after one
condition has been checked.
▪ Syntax:
if (outerCondition) { // Code to execute if outerCondition is true
if (innerCondition1) {
} else if (innerCondition2) { // Code to execute if innerCondition1 is true
// Code to execute if innerCondition1 is false and innerCondition2 is true
} else {
// Code to execute if both innerCondition1 and innerCondition2 are false
}
} else if (anotherOuterCondition) {
// Code to execute if outerCondition is false and anotherOuterCondition is true
} else {
// Code to execute if all preceding conditions
45 are false
}
Nested if-else-if statement demonstration
46
switch statement
o The switch statement used to select one of many code blocks to be executed.
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed unless the default
statement is executed .
o Syntax:
switch(expression)
{
case label: // code block
break;
case label: // code block
break;
47
default: // code block }
Demonstration of switch statement
int day = 4;
switch (day)
{
case 1: [Link]("Monday");
break;
case 2: [Link]("Tuesday");
break; Output
case 3: [Link]("Wednesday"); Thursday
break;
case 4: [Link]("Thursday");
break;
case 5: [Link]("Friday");
break;
case 6: [Link]("Saturday");
break;
default:
[Link]("Sunday");
48
}
Looping Statements
▪ Looping statements are Java statements that allows to execute specific blocks
of code a number of times.
▪ Entry controlled loop: The loop in which test condition is checked in the
beginning of the loop.
▪ Exit controlled loop: when statements inside the loop body is executed and
then the condition is checked that loop.
• The loop will stop the execution if the testing expression evaluates to false.
• Syntax:
while(Conditions)
{ // code block to be executed
}
• Example: Adding the first 10 natural numbers(1-10)
int i=1,sum=0;
while(i<=10)
sum+=i;
50
i++;
2) do-while Loop statement
• The do-while loop is similar to the while loop, except that the test
condition is performed at the end of the loop instead of at the beginning.
• When the loop condition becomes false, the loop is terminated and
execution continues with the statement immediately following the loop.
• Syntax:
do
51
Example
public class do_while
{
public static void main(String[] args)
{
int i = 10;
do
{
[Link]("i is " + i);
i++;
}
while (i < 5);
}
}
52
3) for loop statement
✓ The for loop allows execution of the same code a number of times.
✓ Syntax: for (Initialization; Condition; Expression)
{ // code block to be executed
}
• Initialization –is executed (one time) before the execution of the code block.
• Condition -defines the condition for executing the code block.
• Expression - is executed (every time) after the code block has been executed
✓ Example: int i, sum=0; int i;
for (i = 1; i <= n; i++) for ( i = 0; i < 10; i++ )
{ {
sum += i; [Link](i)
} }
53
▪ A loop becomes infinite loop if a condition never becomes false.
▪ Removing all the expressions gives us an infinite loop.
▪This loop's condition is assumed to be always true.
• Examples infinite while loop:
while (true)
54
• Infinite for loop examples:
for (;;)
{ // No initialization, condition, or increment
[Link]("This will also print forever!");
}
• Infinite loop due to unupdated variable:
int counter = 0;
} 55
Nested loop statement
▪ Many applications require nesting of the loop statements, allowing on loop
statement to be surrounded with in another loop statement.
56
//Nested loop demo
public class NestedLoop
{
public static void main(String[] args)
{
int i;
int j;
for(i=5;i>=1;i--) Output
{ 55555
for(j=1;j<=i;j++) 4444
{ 333
[Link](i+ " "); 22
}
1
[Link](" ");
}
}
57
}
Branching Statements
o Branching statements allows us to redirect the flow of program execution.
o Java offers three branching statements: break, continue and return.
❖Continue statement
o The continue statement terminates the current iteration of a loop and instead causes to
jump/proceed to the next iteration of the loop.
o Example:
public class Continue {
public static void main(String[] args) {
int i, sum=0;
Output
for ( i = 1; i <= 10; i++ ) { 1
if ( i% 2== 0) { 3
5
continue; }
7
sum+=i; 9
System. [Link](i+" "); The sum is = 25
}
[Link]("the sum is = "+sum );
58
}}
❖ break statement
• Break causes immediate termination/exit from looping statements entirely.
• Example:
public class Break {
public static void main(String[] args) {
int num;
num = 10;
//loop while i is less than 6
for(int i=num; i >=1; i--) {
if(i<6){
break; // terminate loop if i <6
}
[Link](i + " ");
}
Output
[Link]("Aborted!");
10 9 8 7 6 Aborted!
}} 59
❖return statement
• The return statement is used to exit from the current method.
• The flow of control returns to the statement that follows the original
method call.
• The return statement has two forms: one that returns a value and one that
doesn't.
Syntax: return expression;
• To return a value, simply put the value (or an expression that calculates
the value after the keyword return.
For example:
return sum;
public double Sum(double x, double y) {
return sum = x+y;
}
• When a method is declared void, use the form of return that doesn't
return a value.
60
The demonstration of return statement
public class Power {
private int x; // //instance
instance variables
variables
private int y;
public Power(int a, int b) { //A constructor to Initializes instance variable
x=a;
y=b;
}
public double computePower() { //a method to access the data members
double z;
z=Math . pow (x, y);
return z;
}
public static void main(String args[]) {
Power p= new Power(2,3); //Object creation with a parameterized constructor
double result=p. computePower(); //Assign the return value of the function to the variable result
[Link]("Output :"+result);
} } 61