java notes1
java notes1
Java Environment
Java Environment includes large number of development tools.
The development tools are part of the system known as Java Development Kit ( JDK ).
Java Data Types
Data types are the kind of data that variables hold in a programming language. A data type is an attribute of
data that tells the compiler or interpreter how the programmer plan to use the data. There are two types of data
types in Java:
Primitive types are predefined (already defined) in Java. A primitive type starts with a lowercase letter.
The primitive data types include char, byte, short, int, long, boolean, float, and double.
Non-primitive types are created by the programmer. non-primitive types start with an uppercase letter. The
non-primitive data types include Classes, Interface, Strings, and Arrays.
Classes:
A class is a group of objects which have common properties. It is a user-defined data type with a template that
serves to define its properties. To create a class, use the keyword class. Let's learn the class in detail in
upcoming chapters.
public class Main { // Main is the class name int num = 20; void getdata(){ } void putdata(){ } }
Interfaces:
The interface keyword to create an interface. An interface is slightly different from the class. It contains only
constants and method declarations.
interface car // car is the interface name{ void start(); void stop(); }
Strings:
The String data type is used to store a sequence of characters (text). String values must be surrounded by
double quotes.
String greeting = "Hello World"; System.out.println(greeting);
Arrays:
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value. To declare an array, define the variable type with square brackets.
String[] cars = {"Audi", "BMW", "Ford"}; int[] num = {10, 20, 30, 40};
Java Variables
A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored
in a variable can be changed during program execution. In Java, all the variables must be declared before use.
1. Declaring variables
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
Syntax:
data_type variable_name;
Example:
Where alphabet and number are then variables of type character and integer.
Example:
Where A and 100 are the values assigned to the variable alphabet and number.
Variable names may consists of alphabets , digits , underscore ( _ ) and dollar sign ( $ ).
They must not be begin with digits.
It should not be a keyword.
White space is not allowed.
Variable names can't be in length.
Uppercase and Lowercase are distinct.
Java Constants
Constants in Java refer to fixed values that do not change during the execution of the program. A
constant is a variable whose value cannot change once it has been assigned.
To define a variable as a constant, we just need to add the keyword “final” in front of the variable
declaration.
Syntax:
inal data_type = value;
Example:
final float pi = 3.14f;
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.
Types of Constants
1. Integer Constants :
It refers to sequence of digits . There are three types of integers namely decimal integer , octal
integer and hexadecimal integer.
final int num1 = 225; // decimal integer begins with non zero digitfinal int num2 = 035; // octal
integer begins with 0final int num3 = 0x2; // hexadecimal integer begins with "0x" or "0X"
2. Real Constants:
Integer numbers are inadequate to represent quantities that are very continuously, such as
temperatures, prices, heights ,etc. These numbers are represented by fractional parts. Such
numbers are called real constants.
Example:
final int num1 = 435.36;
real constants are represented by fractional parts.
3. Single Character Constants :
It contains a single character enclosed within a pair of single quote marks.
Example:
final char alphabet1 = 'A';
'A' is a single character constant enclosed with single quote.
final char num1 = '5';
'5' is single character constant enclosed with single quote.
iv) String Constants: It contains a single character enclosed within a pair of double quote marks.
Example: “hello", “2000”, “7+5”.
final String greeting = "Hello"; // "Hello" is a string constant enclosed with double quotes final String
num = "20"; // "20" is a string constant enclosed with double quotes
Java Typecasting
Convert a value from one data type to another data type is known as type casting.
byte -> short -> char -> int -> long -> float -> double
Example:
int x = 7;
long y = x; //automatically converts the integer type into long type
Narrowing Casting (manually) - converting a larger type to a smaller type. It is also known
as explicit conversion or casting up.
double -> float -> long -> int -> char -> short -> byte
Syntax:
type variable1 = (type) variable2;
A Loop executes the sequence of statements many times until the stated condition becomes false. A loop
consists of two parts, a body of a loop and a control statement. The purpose of the loop is to repeat the same
code several times.
1. while loop :
A while loop statement in Java programming language repeatedly executes a target statement as long as a
given condition is true. When executing, if the boolean_expression result is true, then the actions inside the
loop will be executed. When the condition becomes false, the loop will exit.
Syntax:
while(Boolean_expression)
{
// Statements
}
Example:
public class Looping
{
public static void main(String args[]) {
int x = 10;
while( x < 15 ) {
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}
}
}
EXPLANATION:
The loop executes until the value of x is less than 15, the value of x is incremented by 1. When the condition is
false the loop exit */
OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
2. do while loop :
A do-while loop is similar to a while loop with one exception that it executes the statements inside the body of
the do-while before checking the condition. If the Boolean expression is true, the statements in the loop
execute again. This process repeats until the Boolean expression is false.
Syntax:
do
{
// Statements
}while(Boolean_expression);
Example:
public class Looping
{
public static void main(String args[])
{
int x = 10;
do
{
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}while( x < 15 );
}
}
EXPLANATION:
The control passes to the body of the loop and then checks the condition.
If the condition is less than 15 loop executes, and then the value of x is incremented
by 1.When the condition false the loop terminates. */
OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
3. for loop
A for loop ( finite loop ) is a repetition control structure that allows you to efficiently write a loop that needs
to be executed a specific number of times. A for loop is useful when you know how many times a task is to be
repeated.
Syntax:
for(initialization; Boolean_expression; update)
{
// Statements
}
Example:
public class Looping
{
public static void main(String args[])
{
for(int x = 10; x < 15; x = x + 1)
{
System.out.print("value x : " + x );
System.out.print("\\n");
}
}
}
EXPLANATION:
The loop executes until the value of x is less than 15,
when the condition is false the loop exit*/
OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
Jump Statements:
Jump statements are used to unconditionally transfer program control from one point to elsewhere in the
program. Jump statements are primarily used to interrupt loops or switch-case instantly. Java supports three
jump statements: break, continue, and return.
i) break statement:
The break construct is used to break out of the middle of loops: for, do, or while loop. When a break statement
is encountered, execution of the current loops immediately stops and resumes at the first statement following
the current loop.
Example:
public class BreakStatement
{
public static void main(String args[])
{
System.out.println("Welcome to ShapeAI");
for (int i = 1; i <= 10; i++)
{
System.out.println("i = "+i);
if (i == 5)
{
System.out.println("\\nBye");
break;//hence break statement is used to terminate the loop
}
}
}
}
OUTPUT:
Welcome to ShapeAI
i=1
i=2
i=3
i=4
i=5
Bye
The continue statement also skips the remaining statements of the body of the loop where it is defined but
instead of terminating the loop, the control is transferred to the beginning of the loop for the next iteration.
The loop continues until the test condition of the loop becomes false.
Example:
public class ContinueStatement
{
public static void main(String args[])
{
int i;
for (i = 1; i <= 10; i++)
{
if (i == 5)
continue; // continue statement breaks the loop continues until the test condition of the loop becomes
false
System.out.print(i + " ");
}
}
}
OUTPUT:
1 2 3 4 6 7 8 9 10
Example:
public class ReturnStatement
{
int display()
{
return 5;
}
public static void main(String[] args)
{
ReturnStatement e = new ReturnStatement();
System.out.println(e.display());
}
}
OUTPUT:
5
Java Decision Making And Branching
“Decision making and branching” is one of the most important concepts of computer programming. Programs
should be able to make logical (true/false) decisions based on the condition provided. So controlling the
execution of statements based on certain condition or decision is called decision making and branching.
1.If Statements
The if statement is used to test the condition. It checks boolean conditions true or false. There are various
types of if statements in Java.
Simple if statement
if-else statement
if-else-if ladder
nested if statement
i) Simple if Statement :
The Java if statement tests the condition. It executes the *if block* if the condition is true. Where
boolean_expression is a condition.
Syntax:
if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true
}
Statement-X;
Example:
public class Branching
{
public static void main(String args[])
{
int num = 10;
if( num < 20 ) {
System.out.print("Welcome to ShapeAI");
}
}
}
EXPLANATION:
Hence num value 10 is less than 20, it executes the statement inside if block
OUTPUT:
Welcome to ShapeAI
The Java if-else statement also tests the condition. It executes the if block, if the condition is true
otherwise else block, is executed.
Syntax:
if(Boolean_expression)
{
// Executes when the Boolean expression is true
}else
{
// Executes when the Boolean expression is false
}
Statement-X;
Example:
public class Branching
{
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
// Executes when the Boolean expression 3 is true
}
else
{
// Executes when the none of the above condition is true.
}
Statement-X;
Example:
public class Branching
{
public static void main(String args[])
{
int num = 30;
if (num == 10)
{
System.out.print("Value of num is 10");
}
else if (num == 20)
{
System.out.print("Value of num is 20");
}
else if (num == 30)
{
System.out.print("Value of num is 30");
}
else
{
System.out.print("This is else statement");
}
}
}
EXPLANATION:
executes the second else if block hence the num value 30 is equal to 30
OUTPUT
Value of X is 30
iv) nested if statement :
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when the outer if block condition is
Syntax:
switch(expression)
{
case value :
// Statements
break;
case value :
// Statements
break;
EXPLANATION:
The given expression grade is assigned with 'C'. hence it matches with the case 'C'.
So case 'C' statement "Well done" is executed
OUTPUT:
Well done
Your grade is
Labeled Loop in Java
A label is a valid variable name that denotes the name of the loop to where the control of execution should
jump. To label a loop, place the label before the loop with a colon at the end. Therefore, a loop with the label
is called a labeled loop.
Syntax for labelled for-loop:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}
Example:
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
Output:
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9