0% found this document useful (0 votes)
9 views60 pages

Java 1.3

The document provides an overview of Java programming concepts, including the structure of a basic Java program, types of tokens, and variable types. It explains keywords, identifiers, constants, operators, and data types, detailing their roles and rules in Java. Additionally, it covers Java's primitive and non-primitive data types, variable declaration and initialization, and operator precedence.

Uploaded by

Kusumita Sahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views60 pages

Java 1.3

The document provides an overview of Java programming concepts, including the structure of a basic Java program, types of tokens, and variable types. It explains keywords, identifiers, constants, operators, and data types, detailing their roles and rules in Java. Additionally, it covers Java's primitive and non-primitive data types, variable declaration and initialization, and operator precedence.

Uploaded by

Kusumita Sahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

By

Lal Singh Kalundia


Assistant Professor
CSE Department
GCEK
 Understanding the first java program
public
static
void
main
(String args[] )
System.out.println("This is my first program in java");

------------ Already covered in Topic “FIRST JAVA PROGRAM”


A token is the smallest element or unit of a program that is
meaningful to the compiler or Java Tokens are the smallest individual
building block of a Java program. Tokens can be classified as follows:

Types of Tokens

1. Keywords
2. Identifiers
3. Constant or Literals
4. Operators
5. Special symbols or
Separators
6. Comments

1. Keywords:
These are the pre- Java provides
defined reserved words of the following
any programming language. 50 -52 java
Each keyword has a special keywords:
meaning. It is always written
in lower case.
Some valid identifiers are:
2. Identifier: PhoneNumber
Identifiers are used to name a variable, constant, function, class, and array. It PRICE
usually defined by the user. It uses letters, underscores, or a dollar sign as radius
the first character. Remember that the identifier name must be different a
from the reserved keywords. There are some rules to declare identifiers are: a1
1. The first letter of an identifier must be a letter, underscore or a dollar _phonenumber
sign. It cannot start with digits but may contain digits. $circumference
2. The whitespace cannot be included in the identifier. jagged_array
3. Identifiers are case sensitive. 12radius //invalid

3. Constant or Literals:
It is a notation that represents a fixed value (constant) in the source Literal Type
code. It is defined by the programmer. Once it has been defined cannot 23 int
be changed. Java provides five types of literals are as follows:
1. Integer 9.86 Float, double
2. Floating Point false, true boolean
3. Character
'K', '7', '-' char
4. String
5. Boolean “college" String
null any reference type
4. Operators:
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:

1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Unary Operators
5. Logical Operators
6. Ternary Operators
7. Bitwise Operators
8. Shift Operators
Operator Operation
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic + Addition
operations on variables and data. - Subtraction

* Multiplication
For example, a+b;
/ Division

Modulo Operation
%
2. Assignment Operators (Remainder after division)
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

int x = 10;

3. Java Relational or Comparison Operators


Relational or Comparison operators are used to compare two values:

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
4. Java Unary Operators
Unary operators are used with only one operand or variable.
For example, ++ is a unary operator that increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:
Operator Meaning
++ Increment operator: increments value by 1. example ++5 will return 6
-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a Boolean


For example,
int num = 5;
// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
Increment and decrement operators can be further classifies into
prefixes (++a, --b)
postfix (a++, b++)
6. b=a-- expands to
++ operator: temp = a;
➢ prefix : ++var, the value of var is incremented by 1; then it returns the value. a = a - 1;
➢ postfix like: var++, the original value of var is returned first; then var is b = temp;
incremented by 1.
7. b=++a expands to
NOTE: a = a + 1;
The -- operator works in a similar way to the ++ operator except -- decreases the value by 1. b = a;

Expansions for the prefix and postfix shorthand forms 8. b=--a expands to
a = a - 1;
1. a++ expands to 4. --a expands to b = a;
a=a+1; a = a - 1;
9. print(a++)
2. a-- expands to 5. b = a++ expands to print(a)
a = a-1; temp = a; a = a + 1;
a = a + 1;
3. ++a expands to b = temp; 10. print(++a)
a = a+1; a = a + 1;
print(a);
Example 1

(a) Prefix (b) Postfix (c) Prefix (d) Postfix


X= 10 X= 10 X= 10 X= 10
Y = ++X Y = X++ Y = --X Y = X--
Y? Y? Y? Y?
X? X? X? X?

Example 2 Example 3
a=5 int a=4;
++a; System.out.println(a--);
System.out.println(--a);
a++; System.out.println(a);
--a;
a--; Output ?

Output ?
Answer
Example 1
(a) Prefix (b) Postfix 5. Java Logical Operators
X= 10 X= 10
Y = X++
Logical operators are used to determine the logic between variables or values:
Y = ++X
Y ? 11 Y ? 10
X ? 11 X ? 11 Operator Name Description Example
(c) Prefix (d) Postfix && Logical and Returns true if both x < 5 && x < 10
X= 10 X= 10 statements are true
Y = --X Y = X--
Y?9 || Logical or Returns true if one of the x < 5 || x < 4
Y ? 10
X?9 statements is true
X?9
! Logical not Reverse the result, returns !(x < 5 && x < 10)
false if the result is true
Example 2
a=5
++a; // a becomes 6 6. Ternary Operators in Java
a++; // a becomes 7
This operator displays the result based on the condition. The condition
--a; // a becomes 6
a--; // a becomes 5 is an expression that returns a boolean value.
(Condition) ? (Statement1) : (Statement2);
Example 3
int a=4;
System.out.println(a--);
System.out.println(--a);
System.out.println(a);

This will print:


4
2
2 result = (marks > 40) ? "pass" : "fail";
7. Bitwise Operators in Java Java Operator Precedence
These operators perform bit by Operator Type Category Precedence
bit operation. Bitwise operators 1. Unary postfix expr++ expr--
work at binary level. The output prefix ++expr --expr +expr -expr ~ !
is either 1 or 0 based on the
comparison.
2. Arithmetic multiplicative */%
additive +-
Example:
3. Shift shift << >> >>>
Bitwise AND a&b
4. Relational comparison < > <= >= instanceof
bitwise AND operation of two integers
12 & 25.
equality == !=
5. Bitwise bitwise AND &
8. Shift Operators bitwise exclusive OR ^
Right shift and left shift operators. Right shift operator bitwise inclusive OR |
shifts all bits towards right by certain number of specified
bits. It is denoted by >>. Similarly for left shift << 6. Logical logical AND &&
logical OR ||
Denoted by :num>>i
7. Ternary ternary ?:
8. Assignment assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=

Ans: 2
Example The operator precedence of
int a = 10, b = 5, c = 1, result; prefix ++ is higher than that
result = a - ++c - ++b; of - subtraction operator
5. Special symbols or Separators:
The separators in Java is also known as punctuators. In Java, there are a few characters that are
used as separators. The most commonly used
separator in Java is the semicolon, it is used to terminate statements.
Symbol Name Purpose
Parentheses Used to contain lists of parameters in method definition and invocation. Also used for
() defining precedence in expressions, containing expressions in control statements, and
surrounding cast types.
Braces Used to contain the values of automatically initialized arrays. Also used to define a
{} block of code, for classes, methods, and local scopes.
Brackets Used to declare array types. Also used when dereferencing array values.
[]
Semicolon Terminates statements.
;
Comma Separates consecutive identifiers in a variable declaration. Also used to chain
, statements together inside a for statement.
Period Used to separate package names from subpackages and classes. Also used to separate a
. variable or method from a reference variable.

6. Comments:
Comments allow us to specify information about the program inside our Java code. Java compiler
recognizes these comments as tokens but excludes it form further processing. The Java compiler treats
comments as whitespaces. Java provides the following two types of comments:
1. Single Line : It begins with a pair of forwarding slashes (//).
2. Multi line: These begin with a /* and end with */. can be several lines long
Single Line comment
System.out.println(i); //printing the variable i
Multi Line comment
public static void main(String[] args) {
/* Let's declare and
print variable in java. */

NOTE: Compiler Ignores 2 things while scanning or checking tokens:

When you compile a program, the compiler scans the text in the source code
and extracts individual tokens. While tokenizing the source file, the compiler
recognizes and subsequently removes or ignores two things:

1. Comments are useful to explain the operation of the program to anyone


who is reading it. The Java compiler treats comments or texts as whitespaces

2. White spaces :
Java is a free form language which means that there are no specific indentation rules
while writing programs. However, note that there has to be at least one whitespace
character between each token. A whitespace can be a space, a tab or a newline.
Variable in Java is a data container that stores the data values during Java program execution. Every
variable is assigned data type which designates the type and quantity of value it can hold. Variable is a
memory location name of the data.

Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables

In order to use a variable in a program you to need to perform 2 steps

1. Variable Declaration: 2. Variable Initialization:


To declare a variable, you must To initialize a variable, you must
specify the data type & give the assign it a valid value.
variable a unique name.

int data=10;

int a,b,c;
You can combine variable declaration and initialization.
Types of variables
In Java, there are three types of variables:
1.Local Variables
2.Instance Variables class gcek
3.Static Variables {
static int a = 1; //static variable

int data = 99; //instance variable

void method1()
1) Local Variables {
Local Variables are a variable that are declared int b = 90; //local variable
inside the body of a method. }
}
2) Instance Variables
Instance variables are defined without the
STATIC keyword .They are defined Outside a
method declaration. They are Object specific
and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables. and it
can not be changed
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1.Primitive data types: The primitive data types include
boolean, char, byte, short, int, long, float and double.

2.Non-primitive data types: The non-primitive data types


include Classes, Interfaces and Arrays

An array can hold more


than one value at a time.
string is made up of
characters, and can
include letters, words,
phrases, or symbols
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language
NOTE:
Java is a statically-typed programming language. It means, all variables
must be declared before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:


1. boolean data type
2. byte data type
3. char data type Data Type Default Value Default size
4. short data type (min. value)
5. int data type boolean false 1 bit
6. long data type
byte 0 1 byte
7. float data type
8. double data type char '\u0000' 2 byte
short 0 2 byte
Points to Remember:
•All numeric data types are int 0 4 byte
signed(+/-).
long 0L 8 byte
•The size of data types float 0.0f 4 byte
remain the same on all
double 0.0d 8 byte
platforms (standardized)
Boolean(1 bit) boolean isJavaFun = true;
A boolean data type is declared with boolean isFishTasty = false;
the boolean keyword and can only
take the values true or false: System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Integer Types
Byte(1 byte) byte myNum = 100;
The byte data type can store whole numbers from -128 to 127. System.out.println(myNum);
It isan 8-bit signed two's complement integer. Its default value is 0.

Short(2 byte)
The short data type can store whole numbers from -32768 to 32767 short myNum = 5000;
System.out.println(myNum);
The short data type is a 16-bit signed two's complement integer.

Int(4 byte)
The int data type can store whole numbers from -2147483648 to int myNum = 100000;
2147483647. In general, the int data type is the preferred data type System.out.println(myNum);
when we create variables with a numeric value.

Long(8 byte)
long myNum = 15000000000L;
The long data type is used when int is not large enough to store
System.out.println(myNum);
the value. Note that you should end the value with an "L":
Float
You should use a floating point type whenever you need a number with a decimal, such as
9.99 or 3.14515.

Float(4 byte)
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":

float myNum = 5.75f;


System.out.println(myNum);

Double(8 byte)
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":
The precision of float is only six
double myNum = 19.99d; or seven decimal digits,
System.out.println(myNum); while double variables have a
precision of about 15 digits.

Char(2 byte)
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c’:

The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

char myGrade = 'B’; you can use ASCII char myVar1 = 65,
values to display
System.out.println(myGrade); certain characters: System.out.println(myVar1);
Why char uses 2 byte in java (1 byte in C, C++)
Before Unicode, there were many language
It is because java uses Unicode system not ASCII code system. standards:
Unicode is a universal international standard character encoding •ASCII (American Standard Code for Information
that is capable of representing most of the world's written Interchange) for the United States.
languages. •ISO 8859-1 for Western European Language.
•KOI-8 for Russian.
•GB18030 and BIG-5 for chinese, and so on.
Java supports unsigned 16-bit (2 byte) Unicode characters.
•The char range lies between 0 to 65,535 (inclusive). This caused two problems:
•Its default value is '\u0000'. 1. A particular code value corresponds
to different letters in the various
language standards.
2. The encodings for languages with
large character sets have variable
length. Some common characters are
encoded as single bytes, other require

Strings
two or more byte.
Solution
The String data type is used to store a sequence of characters To solve these problems, a new
(text). String values must be surrounded by double quotes: language standard was developed i.e.
Unicode System.
String greeting = "Hello World"; In unicode, character holds 2 byte, so
System.out.println(greeting); java also uses 2 byte for characters.
lowest value:\u0000
A String in Java is actually a non-primitive data type highest value:\uFFFF
Type casting is a method or process that converts a data type into another data type in both ways
manually and automatically. The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
In Java, there are two types of casting:
1. Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

Example: int to double Data Type size


int myInt = 9;
boolean 1 bit
double myDouble = myInt; // Automatic casting:
byte 1 byte
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0 char 2 byte
short 2 byte
2. Narrowing Casting (manually) - converting a larger type to a smaller size type int 4 byte
double -> float -> long -> int -> char -> short -> byte
long 8 byte
Example: double to int float 4 byte
double myDouble = 9.78;
double 8 byte
int myInt = (int) myDouble; // Manual casting
System.out.println(myDouble); // Outputs 9.78 Here (int) is
System.out.println(myInt); // Outputs 9 type cast operator
Program 1 : Write a java program to print Program 2: Write a java program to
Hello World add,subtract,multiply,divide two numbers
public class demo
public class hello {
{ public static void main(String args[])
{
public static void main(String[] args)
int a = 20;
{ int b = 10;
System.out.println("Hello World");
System.out.println ("Addition of a and b:"+(a+b));
} System.out.println ("Subtraction of a and b:"+(a-b));
} System.out.println ("Multiply of a and b:"+(a*b));
OUTPUT: Hello World System.out.println ("Division of a and b:"+(a/b));
}
ONLINE COMPILER }
OUTPUT:
https://www.tutorialspoint.com/compile_
java_online.php Addition of a and b:30
Subtraction of a and b:10
https://www.programiz.com/java-
programming/online-compiler/ Multiply of a and b:200
Division of a and b:2
https://onecompiler.com/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.

Control flow is the order in which the statements execute. For example, the
program’s flow is usually from top to bottom(Sequential flow), but what if we
want a particular block of code to only be executed when it fulfills a specific
condition or wants to run a block of the code a specified number of times?

Java provides us control structures, statements that can


alter(modify) the flow of a sequence of instructions.

There are three types of control statements:


1. Conditional/Selection statements/ Decision Making
2. Iteration/Loop statements
3. Jump statements
Selection or Loop or
Decision or
Conditional/selection statements

This statement allows us to select a statement or set of statements


for execution based on some condition.

These control statements help with implementing decision-making in a


program. A conditional statement will select the block of statements that
will execute based on the given condition. The result of the program
depends on the condition.

If the condition provided proves to be true, the result is 1; if it proves to be


false, the result is 0. When there is a truth value, the code will get executed;
otherwise, it will not.
1. if statement
In Java, the "if" statement is used to evaluate a condition. In Java, there
are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Syntax: public class IfDemo1
1.1 If {
public static void main(String[] args)
if(condition) {
{ int marks=70;
// Statements to execute if if(marks > 65)
// condition is true {
} System.out.print("First division");
}
}
}

WAP to check the division of marks scored by a student


1.2 If-else
public class IfElseDemo1
Syntax: {
if(condition)
public static void main(String[] args)
{ {
//code for true int marks=50;
} if(marks > 65)
else {
{ System.out.print("First division");
//code for false }
else
}
{
System.out.print("Second division");
Questions: }
1. Write a program to check a number odd or even }
2. Write a program to check leap year or not }
1.3 Nested-if if(condition)
Nested if statements means an if statement {
//statement
inside an if statement. Java allows us to nest if
if(condition)
statements within if statements. i.e, we can {
place an if statement inside another if //statement
statement. }
WAP using nested –if to check whether a student is }
eligible to vote if its age is >=18 and weight >50
public class NestedIfDemo1
{
public static void main(String[] args)
{
int age=25;
int weight=70;
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible");
}
}
}
}
1.4 if-else-if ladder
Here, a user can decide among multiple options. The if statements are executed from
the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, then the final else statement will be executed.

if(condition1)
{ //code for if condition1 is true
}

else if(condition2)
{ //code for if condition2 is true
}

else if(condition3)
{ //code for if condition3 is true
}
...
else { //code if all conditions are false
} Question:
1. Write a program to find greatest among 3 numbers
WAP to print Grade by using marks of a student

public class IfElseIfDemo1


{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{ System.out.println("fail"); }
else if(marks>=50 && marks<60)
{ System.out.println("D grade"); }
else if(marks>=60 && marks<70)
{ System.out.println("C grade"); }
else if(marks>=70 && marks<80)
{ System.out.println("B grade"); }
else if(marks>=80 && marks<90)
{ System.out.println("A grade"); }
else if(marks>=90 && marks<100)
{ System.out.println("A+ grade"); }
else
{ System.out.println("Invalid!"); }
}
} Output: C grade
2. switch Statement
The switch statement allows us to execute one code block among many alternatives. You
can do the same thing with the if...else..if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax of switch...case
When Java The expression is
reaches
a break keyw
evaluated once and
ord, it breaks compared with the
switch (expression) out of the
{ values of
switch block.
case constant1: each case label.
// statements
For example, if the value
break;
of the expression is
case constant2: equal to constant2,
// statements statements after case
break; constant2: are executed
. until break is
.
.
encountered.
default: If there is no match, the
// default statements default statements are
}
executed.
public class MyClass WAP using switch statement to print Day Question
{
public static void main(String[] args) Write a java program to calculate the grade
{ of a student by considering the following
int day = 4; range of marks using switch-case
switch (day) Output: Thursday statement.
{
Grades = switch(marks/10)
case 1:
{
System.out.println("Monday"); O, 90 ≤ Marks ≤100 case 10:
break; E, 80 ≤Marks < 90 case 9:
case 2:
A, 70 ≤Marks < 80 printf("Grade: O");
System.out.println("Tuesday");
B, 60 ≤Marks < 70 break;
break;
case 8:
case 3: C, 50 ≤Marks < 60 printf("Grade: E");
System.out.println("Wednesday");
D, 40 ≤Marks < 50 break;
break;
F, Otherwise case 7:
case 4:
printf("Grade: A");
System.out.println("Thursday"); Grades
Marks break;
break;
O case 6:
case 5: 90 - 100
printf("Grade: B");
System.out.println("Friday"); E
80 - 89 break;
break;
A case 5:
case 6: 70 - 79
printf("Grade: C");
System.out.println("Saturday"); B
60 - 69 break;
break; C
50 - 59 case 4:
case 7:
printf("Grade: D");
System.out.println("Sunday"); D
40 – 49 break;
break; F
0 - 39 default:
default : System.out.println("Invalid Day");
printf("Grade: F");
}
break;
}
}
}
Iteration Statements
Iteration is the process where a set of instructions or statements is executed repeatedly for a specified number of time or
until a condition is met. Iteration statements are most commonly know as loops, a loop is used to repeat a block of code
until the specified condition is met..
Loops in programming come into use when we need to repeatedly execute a block of statements. For example:
Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:
There are three types of looping statements:
1. For Loop
2. While Loop
3. Do-while loop

For Loop SYNTAX:


for(initiation ; condition ; update)
{
…..statements;
}

Example:
while loop
WAP to print first 3
numbers using for loop SYNTAX:

public class forloopdemo while(condition)


{ {
Statement 1;
public static void main(String args[]) Statement 2;
{ increment/decrement;
for(int i=1;i<=3;i++) }
{ WAP to print “Hello World” 5 times
System.out.println(i);
public class whileLoopDemo
{
} public static void main(String args[])
} {
} int i = 1;
while (i < 6) OUTPUT:
output
{
: Hello world
System.out.println("Hello World");
i++; Hello world
1 Hello world
}
2 Hello world
}
3 Hello world
}
Do while loop
Syntax:
do while loop is similar to while loop with only
do difference that it checks for condition after
{ executing the statements.
statements.. There is no checking of any condition for the first
increment/decrement; time.
}
while(condition);
WAP to print “Hello World” 5 times

public class MyClassdowhile


{
public static void main(String[] args)
{
OUTPUT:
int i = 0;
do Hello world
{ Hello world
System.out.println(“Hello World”); Hello world
Hello world
i++;
Hello world
}
while (i < 5);
}
}
Program to print Right Triangle Star Pattern
Print Pattern in Java public class RightTrianglePattern
{
We can print a Java pattern program in different designs: public static void main(String args[])
Start Pattern, Number Pattern, Character Pattern {
In the pattern programs, Java for loop is widely used. //i for rows and j for columns
//row denotes the number of rows you want to print
The row is denoted by i and the column is denoted by j. We
see that the first row prints only a star. The second-row
int i, j, row=6;
prints two stars, and so on. The colored blocks print
//outer loop for rows
the spaces.
for(i=0; i<row; i++)
logic for the pattern {
//inner loop for columns
for(int i=0; i<row; i++) for(j=0; j<=i; j++)
{ {
for(int j=0; j<=i; j++) //prints stars
{ System.out.print("* ");
System.out.print("* "); }
} System.out.println();
System.out.println(); }
}
}
Jump Statements
Jumping statements are control statements that transfer execution control
from one point to another point in the program

Break
In Java, break is majorly used for:
• Terminate a sequence in a switch statement.
• To exit a loop. Using break we can leave a loop even if the condition for its
end is not fulfilled.
• The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
WAP using break inside the loop, the loop will terminate when the value is 3.

public class BreakDemo1


{
public static void main(String[] args)
{ Output
1
for(int i=1;i<=5;i++) 2
{
if(i==3)
{
break;
}
System.out.println(i);
}
}
}
Continue
When we use continue statement with while and do-while statements, the execution
control directly jumps to the condition.
The continue statement causes the program to skip the rest of the loop in the current
iteration as if the end of the statement block had been reached, causing it to jump to
the start of the following iteration.
WAP using continue statement inside the loop, the loop will still continue
when the value is 3.

public class ContinueDemo1


{
public static void main(String[] args)
{ Output
for(int i=1;i<=5;i++) 1
{ 2
if(i==3) 3
4
{ 5
continue;
}
System.out.println(i);
}
}
}
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.
In java array is used as an object

Note: Array indexes start with


0: [0] is the first element. [1] is
the second element, etc.

For example, if we want to store the employee ID of 100 people then we can create an array of the int type
int empid [ ];
To create an array of integers, you could write:
int empid[] = {10, 20, 30, 40};

Declare array variables, create arrays, and Accessing an Array


1. Declaring Array Variables
To use an array in a program, you must declare a array variable, and specify the
type of array. Here is the syntax for declaring an array variable −
dataType - it can be primitive data
Syntax: types like int, char, double,byte, etc.
dataType[] arrayname; // preferred way. or or Java objects
dataType arrayname[]; // works but not preferred way. arrayName - it is an identifier
Example
double[] myList; Now, we have to allocate memory for the array in Java. For example,
or // declare an array
double myList[]; double[] data;

2. Initialize Arrays or allocate memory

we have created an array named age and initialized it with the values by ANY two ways

(A) using the ARRAY index number (B) inside the curly brackets.

//declare and initialize and array


// declare an array
int[] age = {12, 4, 5, 2, 5};
int[] age = new int[5];

// initialize array Note that we have not provided the size of the array.
age[0] = 12; In this case, the Java compiler automatically specifies
age[1] = 4; the size by counting the number of elements in the
age[2] = 5; array (i.e. 5).

The number of values in a Java array is always fixed.


How to Access Elements of an Array in Java? How to get the size of array?
We can access the element of an array using Syntax:
the index number. Here is the syntax Arrayname.length .
// access array elements using index(0,1,2..)
arrayname[index]

Write a program in java to show the access of array elements and length of array
public class arrayx
{
public static void main(String[] args)
{
// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:"); Output:
System.out.println("First Element: " + age[0]);
Accessing Elements of Array:
System.out.println("Second Element: " + age[1]);
First Element: 12
System.out.println("Third Element: " + age[2]); Second Element: 4
System.out.println("Fourth Element: " + age[3]); Third Element: 5
System.out.println("Fifth Element: " + age[4]); Fourth Element: 2
Fifth Element: 5
System.out.println(age.length); 5
}
}
One/Single Dimensional Array in Java

int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
Syntax to Declare an 1D Array in Java a[4]=50;

datatype arrayvaiable[]=new datatype[size]; OR


Example: int a[]=new int[5];
int a[]={10,20,70,40,50};
Example of One Dimensional Array
 Program to print elements of One Dimensional array.

class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70; Output:
a[3]=40; 10
a[4]=50; 20
70
40
for(int i=0;i<a.length;i++)//length is the property of array 50
System.out.println(a[i]);
}
}
Multidimensional Array in Java
In such case, data is stored in row and column based index (also known as matrix form)

Arr[3] [4], the first index specifies the


number of rows and the second index specifies
the number of columns and the array can hold
12 elements (3 * 4).

Example to instantiate 2-Dimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

Similarly, in a three-dimensional array,


there will be three dimensions.
arr[5] [10] [15]
can hold 750 elements (5 * 10 * 15).
Example of Multidimensional Java Array

int[][] arr=new int[3][3];//3 row and 3 column  Program to print elements of 2Dimensional array.

arr[0][0]=10; class Testarray3


arr[0][1]=20; {
arr[0][2]=30; public static void main(String args[])
arr[1][0]=40; {
arr[1][1]=50; int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++) Output:
arr[1][2]=60;
123
arr[2][0]=70; {
245
arr[2][1]=80; for(int j=0;j<3;j++) 445
arr[2][2]=90; {
System.out.print(arr[i][j]+" ");
}
OR System.out.println();
}
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; }
}
Java Program to add two matrices
Java Program to add/ subtract two matrices
public class matrixadd
{
We can add two matrices in java using binary + public static void main(String args[])
operator. A matrix is also known as array of arrays. {
We can add, subtract and multiply matrices.
//creating two matrices
int a[][]={{1,2},{3,4}};
int b[][]={{5,6},{7,8}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][2]; //2 rows and 2 columns
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++)
Output: {
for(int j=0;j<2;j++)
{
c[i][j] = a[i][j] + b[i][j]; //use - for subtraction ,
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Write a Java program to find the Determinant of a 2 * 2 Matrix
Java program to find Determinant of a matrix and 3 * 3 Matrix. The mathematical formula to find this Matrix
determinant is as shown below:
Determinant of 2 x 2 Matrix: Determinant of 3 x 3 Matrix:
public class determinantmatrix
{
public static void main(String[] args)
{
int arr[][]= {{1,2},{3,4}};
int rows, cols, determinant;

for(rows = 0; rows < 2; rows++)


{ In 2×2 matrix,
a[0][0] a[0][1]
a[1][0] a[1][1]
for(cols = 0; cols < 2; cols++) determinant = a[0][0] * a[1][1] - a[0][1]
{ * a[1][0];
System.out.print(arr[rows][cols] + " " ); // print matrix
}
System.out.println( );
}
determinant = (arr[0][0] * arr[1][1]) - (arr[0][1] * arr[1][0]);

System.out.println("The Determinant of 2 * 2 Matrix = " + determinant );


}
} Output:
In Java, there are four different ways for reading input from the user

👉 1. Using Scanner Class


2. Using Buffered Reader Class
3. Using Console Class
4. Using Command line argument
The java.io and java.util package provides various classes to read write data from
various sources and destinations.
You can read data from user (keyboard) using various classes such as, Scanner,
BufferedReader, InputStreamReader, Console etc.

The Scanner class is one of the simplest ways to get user input in Java. This class provides several built-
in methods to get the input of various types like int and float. Here, we used the nextInt() method to
get the int type of the input:

Scanner is a class in java.util package used for obtaining the


input of the primitive types like int, double etc. and strings
To use the Scanner class, create an object of the class and
Scanner class in Java is Input Types
mainly used to get the In the example above, we used
use any of the available methods found in the Scanner class
user input, and it the nextLine() method, which
documentation. In our example, we will use
belongs to the java.util is used to read Strings. To read
the nextLine() method, which is used to read Strings:
package other types, look at the table
below:
WAP to print your name by taking user input using scanner class
Method Description
import java.util.Scanner; // import the Scanner class
nextBoolean() Reads a boolean value from the user
public class MyClass
{ nextByte() Reads a byte value from the user
public static void main(String[] args)
{ nextDouble() Reads a double value from the user
// create an object of Scanner nextFloat() Reads a float value from the user
Scanner myObj = new Scanner(System.in);
nextInt() Reads a int value from the user
// Enter username and press Enter nextLine() Reads a String value from the user
System.out.println("Enter your name:");
nextLong() Reads a long value from the user
Output: nextShort() Reads a short value from the user
// Reads input from the keyboard/user Enter your name :
String yName = myObj.nextLine(); Xyz
Name is: xyz
// prints the name Qn: WAP to
System.out.println("Name is: " + yName); perform
} addition of
} any two
numbers
This method is used by wrapping the System.in (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the user
in the command line.
BufferedReader class is present in java.io package
WAP to print your name by taking user input using scanner class

import java.io.BufferedReader;
import java.io.InputStreamReader; Here, the readLine()
public class Test method reads the user
{ input and returns a
public static void main(String[] args) string as a result
{
//make object using BufferReader
BufferedReader myobj =
new BufferedReader(new InputStreamReader(System.in));

// Reading data using readLine


String yname = myobj.readLine(); Output:
Enter your name :
System.out.println("Enter your name:"); Xyz
// Printing the read line Name is: xyz
System.out.println("Name is: " + yname);
}
}
Using Console Class in Java
We can use the Console class to get user input in Java. This class belongs to the java.io package
and provides the readLine() method to read user input from the console.
import java.io.Console;
public class Main1 Output:
{ public static void main(String[] args) Enter your name :
{ Xyz
Console console1 = System.console1(); Name is: xyz
String str = console1.readLine();
System.out.println("Enter your name:");
System.out.println("Name is: " + yname);
}
}

Using Command line Arguments


• Command Line Argument in Java is the information that is passed to the program when it is executed.
• The information passed is stored in the string array passed to the main() method and it is stored as a string. It is the
information that directly follows the program’s name on the command line when it is running
• Information is passed as Strings.
• They are captured into the String args of your main method public static void main(String args[])
Example While running a java program/class Demo, you can specify command line arguments as
java Demo arg1 arg2 arg3 …
public class Demo
{ Example
public static void main(String b[ ])
public class cmd
{ {
System.out.println("Argument one = "+b[0]); public static void main(String[] args)
System.out.println("Argument two = "+b[1]); {
} for(int i=0;i< args.length;i++)
{
} System.out.println(args[i]);
}
Step 1) Copy the following code into an editor. }
}
Step 2) Save & Compile the code

Step 3) Run the code as java Demo apple orange. OUTPUT


Execute this program as
10
java cmd 10 20 30 20
30

Step 4) You must get an output as below.


Question:
compilation: javac Demo.java 1. WAP to print even numbers from 1-100
execution: java Demo apple orange 2. Write a program to print n Even numbers
Output : apple orange
WAP to print even numbers from 1-100 Write a program to print n Even numbers
public class xyz import java.util.Scanner;
{ public class xyz
public static void main(String args[]) {
{ public static void main(String args[])
int i; {
for( i=1 ;i<=100 ; i++ ) Scanner myObj = new Scanner(System.in);
{ System.out.println("Enter a number:");
if(i%2==0)
{ int n = myObj.nextInt();
System.out.println(i); int i;
} System.out.println("List of Even numbers upto " + n + " are:\n");
} Output: for( i=1 ; i<=n ; i++ ) Enter a number:
} 2 { 13
} 4 if(i%2==0) List of Even numbers upto 13 are:
6 {
….. System.out.println(i); 2
… }
. 4
} 6
100
} 8
} 10
12
Factorial Program in Java import java.util.Scanner;
class factorialexample
Factorial of n is the product of all positive {
descending integers. Factorial of n is public static void main(String args[])
denoted by n!. For example: {
4! = 4*3*2*1 = 24 int i, fact=1;
5! = 5*4*3*2*1 = 120 Scanner myObj = new Scanner(System.in);
System.out.println("Enter a number:");
int number = myObj.nextInt();
for(i=1; i<=number ;i++)
{
fact=fact*i;
Output:
}
Enter a number: 5 System.out.println("Factorial of "+number+" is: "+fact);
Factorial of 5 is: 120
}
}
INSTRUCTIONS:
✓Answer these questions in your assignment copy
✓Don’t simply copy answers from this ppt.
✓You have to refer ppt/google/text book, understand the
concepts and then you have to write mixed answer

1.What are the different ways to declare ARRAYS in java

2.Explain
SCANNER and BUFFEREDREADER class in java?
Why they are used?

You might also like