Unit 1 - Arrow .Java
Unit 1 - Arrow .Java
A] Class Declaration
The first line
class Sample
declares a class, which is an object-oriented construct.
Java is a true object-oriented language and therefore, everything must be placed inside a class. class
is a keyword and declares that a new class definition follows.
Sample is a Java identifier that specifies the name of the class to be defined.
B] Opening Brace
Every class definition in Java begins with an opening brace "{“ and ends with a matching closing brace
“}”. This is similar to C++ class construct (Note that class definition in C++ ends with a semicolon.)
The main() method is marked static so that the JVM may call it without having to create
static:
an object of the class that contains the main() method.
void: It is a returntype and is used to specify that main() method doesn’t return anything.
Here, String args[] declares a parameter named args, which contains an array of objects of the class
type String.
System:
It is a built in class defined in the [Link] package.
It provides access to standard input, output
out:
This is an object of PrintStream type, which is a public and static member field of the
System class.
It handles the actual writing of data to the output destination.
As it is static, it can be accessed directly using the class name ([Link]).
println():
It prints any argument passed to it and adds a new line to the output.
This is an upgraded version of print().
Every Java statement must end with a semicolon.
Remember that, before we begin creating the program, the Java Development Kit (JDK) must be
properly installed on our system.
Q] Explain the concept of platform independence and portability with respect to Java language.
(S-19 ) [4 Marks]
Java is a platform independent language. This is possible because when a java program is
compiled, an intermediate code called the byte code is obtained.
Byte code is a highly optimized set of instructions designed to be executed by the JVM which is
the interpreter for the byte code. Byte code is not a machine specific code.
Byte code is a universal code and can be moved anywhere to any platform.
Therefore java is portable, as it can be carried to any platform.
JVM is a virtual machine which exists inside the computer memory and is a simulated computer
within a computer which does all the functions of a computer.
Only the JVM needs to be implemented for each platform. Although the details of the JVM will defer
from platform to platform, all interpret the same byte code.
3. Object-Oriented
Q] Why Java is called as Truly Object Oriented Programming? [S-09, 11, 12, 13, W-11]
- Java is a true object-oriented language.
- Almost everything in Java is an object.
- All program code and data reside within objects and classes.
- Java includes all the features of OOP including Inheritance, Polymorphism, and Dynamic Binding
etc.
- Most of methods and constructors used in Java are overloaded.
- So JAVA itself supports Polymorphism.
- JAVA does not support Multiple Inheritance to avoid duplication of data, but it is supported by the
way of Interface.
4. Robust
Java is a robust language that can handle run-time errors as it checks the code during the compile
and runtime.
Java incorporates the concept of exception handling where any serious runtime error is identified
by the JVM, and it will not be passed directly to the underlying system.
Instead, it will immediately terminate the program and stop it from causing any harm to the system.
Java has a strong memory management system.
It also supports the concepts of garbage collection and exception handling.
5. Secure
Java is a secure language that ensures that programs cannot access memory locations without
authorization. It has access modifiers to check memory access.
It does not allow programmers to explicitly create pointers.
Java also ensures that no viruses enter an applet.
Java’s bytecode verifier checks the code blocks for any illegal code that violates the access right.
9. High Performance
Being a compiled language, Java tends to offer better performance compared to interpreted
languages. Its Just-In-Time (JIT) compiler further optimizes the performance by translating bytecode
into native machine code just before execution.
Q] What is byte code? Explain any two tools available in JDK. [S-09, S-12]
Q] What is Byte code explain JVM? [W-11, W-13]
Q] What is JVM? What is bytecode? [S-13]
Compiler translates source code into machine code for specific computer (platform dependent).
But the Java compiler produces an intermediate code known as byte code, for a machine that does not
exist.
This machine is called as ‘Java Virtual Machine’ (JVM) and it only exist inside the computer memory.
It is simulated computer within the computer and performs all major functions of real computer.
Java Tokens
Prof. Akshay Somwanshi :- 8788335443 JPR (Unit 1) Arrow Computer Academy
Smallest individual units in a Program that are meaningful to the Java compiler are called Tokens.
Java language includes 5 types of Tokens:
1. Keywords
2. Identifiers
3. Literal
4. Operators
5. Separators
In the above code, public, class, Demo, {, static, void, main, (, String, args, [, ], ), System, ., out,
println, Arrow, etc. are the Java tokens.
1) Keywords:
- pre-defined reserved words of Language definition.
- Each keyword has a special meaning.
- Must be written in Lowercase
- Eg. do, while, int, if, short, void, continue, public etc.
3) Literals:-
Any constant value that can be assigned to the variable is called a literal.
Types of Literals:-
1. Integer
2. Character
3. Floating-point
4. String
5. Boolean
6. Null
4) Operators:-
An operator is a symbol that indicates one or more arguments and operates on them to
produce result.
Arithmetic Operators
Assignment Operators
Relational Operators
Unary Operators
Logical Operators
Ternary Operators
Bitwise Operators
Shift Operators
5) Separators:-
- Separators are symbols used to indicate where groups of code are divided and arranged.
- Eg. {}, [], () etc.
- The separators in Java is also known as punctuators
Declaration of Variables:
Before a variable can be used, it must be declared.
Syntax:-
dataType variableName;
Example:
Variable Initialization
To assign a value, use the assignment (=) operator followed by the value.
Each declaration or initialization statement must end with a semicolon (;).
Example: a = 25;
Syntax:-
final data_type CONSTANT_NAME = value;
final:
The final keyword indicates that the value of the constant cannot be changed once it is initialized.
data_type:
The data type of the constant such as int, double, boolean, or String.
CONSTANT_NAME:
The name of the constant which should be written in all capital letters with underscores separating
words.
value:
The initial value of the constant.
Example :-
final double PI = 3.14;
Primitive data types in Java are those data types whose variables can store only one value at a
time. We cannot store multiple values of the same type. These data types are pre-defined in Java.
int x; // valid
x = 10; // valid because "x" store only one value at a time because it is the primitive type variable.
x = 10,20,30; // invalid.
Java defines eight primitive data types: boolean, char, byte, short, int, long, float, and double.
1] Integer Types
Integer type stores whole numbers that may be positive or negative and should not contain any
decimal places such as 123, -96, and 5639. Type Size
Valid Integer types are byte, short, int, and long.
byte 1 byte
Long is used when int data type cannot hold a value.
short 2 byte
It is 2 times larger than int(integer).
int 4 byte
We must use L or l at the end of the value.
long 8 byte
Example: 123L , 123l
1. float :
The float data type in Java is a single-precision 32-bit floating-point data type used to store
fractional numbers
A float uses 4 bytes (32 bits) of memory.
It offers a single precision of approximately 6 to 7 decimal digits.
When assigning a literal value to a float variable, you must append the letter f or F to the number
(e.g., 3.14f), because Java treats all floating-point literals as double by default.
2. double:
The double keyword in Java is also a primitive data type, and its size limit is 8 byte or 64
bits double-precision, up to 15 digits precision after the decimal.
We often use this keyword when we have a larger floating value and if we want a more precise
and accurate value.
By default, Java considers any decimal or float values of double type, so we do not need to typecast
any decimal value to double manually.
Hence, adding the suffix 'd' or 'D' in the number is optional in the case of Double data type values.
Note:- double is best suited for applications that require a high degree of accuracy and a wide range
of values
3] Character Type
In order to store character constant in memory, Java provides a character data type called char.
The char type assumes a size of 2 bytes but basically, it can hold a single character.
4] Boolean Type
Used when we want to test a particular condition during the execution of the program. There are only
two values that a Boolean type can take: true and false. It uses only 1 bit.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
1) Arithmetic Operators
Q] Explain Arithmetic Operators with suitable example. [W-08, S-13]
Arithmetic Operators are used to construct mathematical expressions.
Operators Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division (Remainder)
2) Relational Operator
6) != Not equal to
This operator returns true if the values of both the expressions are not equal else returns false.
eg. if x=10; then x!=20 is true
This expression which combines two or more relational expressions is known as a logical expression
or a compound relational expression. The logical relation given above is True only if both a > b and
x==10 are true. If either (or both) of them are false, the expression is false.
OP-1 && OP-2 is true if both the operands are true and false otherwise.
OP-1 || OP-2 is true if either one of the operands are true.
1111 1001 -> 0000 0110 +1 -> 0000 0111 (It is equivalent to 7)
Reesult -> 1’s Complement -> 2’s Complement
Since the MSB was 1, as mentioned above, therefore result is :- (-7)
The AND operator, &, produce a 1 bit if both operands are also 1. A zero is produced in all the cases.
e.g 0101 & 0011 = 0001
(decimal 5) (decimal 3) (decimal 1)
3) Bitwise OR ( | ) :
The OR operator, | , combines bits such that if either of the bits in the operand is a 1, then the resultant
bit is a 1.
e.g 0101 | 0011 = 0111
(decimal 5) (decimal 3) (decimal 7)
4) Bitwise XOR ( ^ ):
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1. Otherwise
result is zero.
e.g 0101 ^ 0011 = 0110
(decimal 5) (decimal 3) (decimal 6)
The left shift operator, <<, shifts all of the bits in a value, to the left a specified number of times
specified by num.
General form: value <<num
e.g. int x=12;
x << 2 ;
0000 1100 << 2 = 0011 0000 (decimal 48)
The right shift operator, >>, shifts all of the bits in a value, to the right a specified number of times
specified by num.
General form: value >>num.
e.g. (x=32)
x>> 2;
0010 0000 >> 2 = 0000 1000 (decimal 8)
Program of bitwise operators
class Bitwise
{
public static void main(String[] args)
{
int A =35, B=2;
[Link]("A&B is "+(A&B));
[Link]("A|B is "+(A|B));
[Link]("A^B is "+(A^B));
[Link]("~A is "+(~A));
[Link]("A<<B is "+(A<<B));
[Link]("A>>B is "+(A>>B));
}
}
Output:-
A&B is 2
A|B is 35
A^B is 33
~A is -36
A<<B is 140
A>>B is 8
Java has two very useful operators i.e. increment (++) and decrement (--) operators.
The increment operator increases its operand by one.
The decrement operator decreases its operand by one.
This statement: x = x + 1; can be rewritten like x++;
Similarly, this statement: x = x - 1; is equivalent to x--;
Both are unary operators and are used in following form:
1) Postfix Increment (x++)
2) Prefix Increment (++x)
3) Postfix Decrement (x--)
4) Prefix Decrement (--x)
In the prefix form, the operand is incremented or decremented before the value is assigned to the
other variable in the expression.
For example:
x = 42;
y = ++x;
In above example; first value of x is incremented (43) and this changed value is assigned to variable
y (43).
In the postfix form, first the operand is assigned to another variable and then it is incremented or
decremented.
For example:
x = 42;
y = x++;
In the above example, first value of x is assigned to variable y (42) and then the value of x is
incremented(43).
Output:
a = 11
c = 11
b=6
d=5
c = 10
a = 10
b=5
d=6
When Java evaluates this assignment expression, it first looks at the expression to the left of the
question mark.
If x>y, then the expression between the question mark and the colon is evaluated and used as the
value of the entire ? expression.
If x<y, then the expression after the colon is evaluated and used for the value of the entire ?
expression. The result produced by the ? operator is then assigned to a.
Output:
n1 and n2 : 10 20
n1 is 10
3) Local Variable
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
There is no default value for local variables, so local variables should be declared and an initial
value should be assigned before the first use.
Assigning a value of one type of a variable to another type is known as Type Casting
There are 2 types of type casting
1. Widening or Implicit type casting
2. Narrowing or Explicit type casting
Widening casting is done automatically when passing a smaller size type to a larger size type.
For assigning one type of data to another type of data variables, casting is required.
But java provides this type of assignment without casting, known as Automatic Type Conversion.
It is possible only if the destination type has enough precision to store the source value.
Example: int is large enough to hold a byte value.
Hence
byte b=75;
int a = b;
are valid statements.
Example:
Example:
int m = 50;
byte n= (byte) m;
long count = (long) m;
Example:
public class Test
{
public static void main(String args[]) {
double d = 100.04;
long l = (long) d; // explicit type casting required
int I = (int) l; // explicit type casting required
[Link] ("Double value " +d);
[Link] ("Logn value " + l);
[Link] ("Int value " + I);
}
}
To create an object of Scanner class, we usually pass the predefined object [Link], which
represents the standard input stream.
Then we can use the nextLine() method, which is used to read Strings:
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other
types, look at the table below:
Method Description
In the example below, we use different methods to read data of various types:
import [Link];
// String input
String name = [Link]();
// Numerical input
int age = [Link]();
double salary = [Link]();
// Output
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Salary: " + salary);
}
}
1) Simple if Statement
General form of a statement is
if (test expression)
{
statement block;
}
statement n;
Statement in block may be single statement or multiple
statements. If condition is true then statement block will be
executed otherwise block is skipped & statement n is
executed.
Example of if statement
if (b > a)
{
[Link]("b is greater");
}
else
{
[Link]("a is greater");
}
}
}
import [Link].*;
public class Main
{
public static void main (String[] args)
{
}
}
if (test expression 1)
{
if (test expression 2)
{
statement block 1;
}
else
{
statement block 2;
}
}
else
{
statement block 3;
}
statement n;
If condition-1 is false, statement block-3 will be executed; otherwise it continues to perform second
test. If condition-2 true, the statement block-1 will be evaluated; otherwise statement block-2 will be
evaluated & then control is transferred to statement n.
Example :
class Test {
public static void main(String[] args) {
int n1 = 150, n2 = 180, n3 = 170;
When multipath decisions are involved either nested if or else ……if ladder can be used.
A multipath decision is chain of ifs in which statement associated with each else is if.
General form is:
if (test expression 1)
statement 1;
else if (test expression 2)
statement 2;
else if (test expression 3)
statement 3;
.
.
.
.
else if (test expression n)
statement n;
else
default statement;
statement x;
Example 1:
import [Link].*;
public class Main
{
public static void main (String[] args)
{
}
}
}
}
General form:
switch (expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break; .
.
.
.
.
case value n:
block n;
break;
default:
default block;
break;
}
statement x;
class Switch
{
public static void main(String[] args)
{
String str = "two";
switch (str)
{
case "one":
[Link]("one");
break;
case "two":
[Link]("two");
break;
case "three":
[Link]("three");
break;
default:
[Link]("no match");
}
}
}
class Switch
{
public static void main(String[] args)
{
char ch = '*';
int a=20,b=30;
switch(ch)
{
case '+':
[Link](a+b);
break;
case '-':
[Link](a-b);
break;
case '*':
[Link](a*b);
Examples:
import [Link].*;
class Swich
{
public static void main(String args[]) throws Exception
{
int choice,num1;
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("1. Odd / Even");
[Link]("2. Square");
[Link]("Enter the choice");
choice=[Link]([Link]());
switch (choice)
{
case 1:
[Link]("Enter the number");
num1=[Link]([Link]());
if(num1%2==0)
{
[Link]("Number is Even");
}
else
{
[Link]("Number is Odd");
}
break;
case 2:
[Link]("Enter the number");
num1=[Link]([Link]());
[Link]("Square of the number is"+(num1*num1));
break;
default:
[Link]("Enter the correct choice");
}
}
}
Introduc The Java for loop is a The Java while loop is a The Java do while loop is a control
tion control flow statement control flow statement flow statement that executes a
that iterates a part of that executes a part of the part of the programs at least once
the programs multiple programs repeatedly on and the further execution
times. the basis of given boolean depends upon the given boolean
condition. condition.
When to If the number of If the number of iteration If the number of iteration is not
use iteration is fixed, it is is not fixed, it is fixed and you must have to
recommended to use recommended to use execute the loop at least once, it is
for loop. while loop. recommended to use the do while
loop.
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 [Link] a simple for 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.
Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; incr/decr)
{
//statement or code to be executed
}
Flowchart:
Output:
1
2
3
4
5
6
7
8
9
10
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
Example:
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++)
{
//loop of j
for(int j=1;j<=3;j++)
{
[Link](i+" "+j);
}//end of i
}//end of j
}
}
Output:
11
12
13
21
22
23
31
32
33
Pyramid Example 1:
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
[Link]("* ");
}
[Link]();//new line
} } }
Output:
*
**
***
****
*****
The Java while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed, it is recommended to use while loop.
Syntax:
while(condition)
{
//code to be executed
}
Output:
1
2
3
4
5
6
7
8
9
10
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed and you must have to execute the loop at least once, it is recommended to use do-while
loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
Do
{
//code to be executed
}while(condition);
Example:
Output:
1
2
3
4
5
6
7
8
9
10
Prof. Akshay Somwanshi :- 8788335443 JPR (Unit 1) Arrow Computer Academy
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break is used to break loop or switch statement. It breaks the current flow of the program at
specified condition.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
Output:
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.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while
loop.
Syntax:
jump-statement;
continue;
Example:
0369
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if
we have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr)
{
//code to be executed
}
Example:
public class LabeledForExample {
public static void main(String[] args)
{
aa:
for(int i=1;i<=3;i++)
{
bb:
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break aa;
}
[Link](i+" "+j);
}
}
}
}
Output:
11
12
13
21
If you use break bb;, it will break inner loop only which is the default behavior of any loop.
Output:
11
12
13
21
31
32
33
Sytnax
Here,
array - an array
item - each item of array is assigned to this variable
dataType - the data type of the array/collection
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
3
9
5
-5
Here, we have used the for-each loop to print each element of the numbers array one by one.
In the first iteration, item will be 3.
In the second iteration, item will be 9.
In the third iteration, item will be 5.
In the fourth iteration, item will be -5.
class Main {
public static void main(String[] args) {
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
Sum = 19