Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Java Notes Jul 2024 MBatch

Ghbfj hai gunj gg cutting and Y Chaitanya and selenium testing tool learning and
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Java Notes Jul 2024 MBatch

Ghbfj hai gunj gg cutting and Y Chaitanya and selenium testing tool learning and
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 158

************************************************************

11-Jul-2024
************************************************************

Manual Testing :
--------------
Testing :
----------
checking /Verifying sthng on the appl whether functionality is working properly
(or) not as Per FRS or BRS.

FRS -Functional Req Specification Doc -- .word doc


BRS -Business Req Sepcification doc -

User stories- in Jira tool

Manual testing :
----------------
checking the functionality with help of manual efforts

entering the data in user name --> manually


entering the data in password --> manually
click login button --> manually

ex1: gmail Login functionality

Steps:
-----------
Open chrome browser, with gmail.com,
Enter user,
Enter pwd
Click Login btn
Verify home page is displayed ---Compose mail button

ex 2: create user - new gmail

first name , last name, mobile no : submit --


Verify user is created ...

Disadvantages of manual testing :


----------------------------------
- Time consuming task --
ex: Login with 1 user -- 1 min
2 users -- > 2*1= 2min
500 --> 500 min

Automation : 20 to 30 min

- cannot provide accurate results -


ex esal : 78,97.45 INR
78,79.54 - Incorrect

- Test resources will be tired .. we will not execute Tc, missing to execute
TC's
Automations tools -- never -
- Costly -- more no of Resources - 8
Automation- initially - we need more resources- -- 2 to maintian
automation code

--------------------
Automation Testing :
---------------------
checking the apppl functionality with help of some automation tool and some
Programming languages.

ex:

ex: gmail Login functionlaity

Steps:
-----------
Open chrome browser --> cmd -- line of code
with gmail.com, ---> cmd - code
Enter user, --> code
pwd, --> code
Click Login btn --> code
Verify home page is displayed ---Compose mail button --> code

Functional Testing Tools:


--------------------------

check only functionality of the appl.

Commerical tools (or) Paid tools : purchase license for tool

ex:
----------------------------------
QTP by Mercury Interacive -> UFT (Unified Functioanl Testing ) by HP > UFT
acquired by MicrFocus
Test Complete -
KatalonStudio -

Open source tool :


-----------------
Free - source code of project is open to all.
Selenium - free

Performance Testing Tools:


-------------------------
check about performance

ex: gmail login -- calculate time taken to login to appl -- 3 sec

ex for Performance Testing Tools:


------------------------
Load Runner by 'Mercury Interactive' > HP -Load Runner > Load runner by
MicroFocus - paid tool

NeoLoad

Locust

Gatling
Jmeter -Open source tool or Free tool

------------------------

FAQ: Difference b/w Manual and Automation?


-------------------------------------------

1. time consuming task 1. is not time consuming task

2. Cannot provide accurate results 2. We can provide accuarte results

3. Resources are tired 3. nevers tired

4. costly 4. free automation -- less costly compare


to manual testing
------------------------------------------------------------------------

************************************************************
12-Jul-2024
************************************************************

Selenium Introduction:
----------------------
Selenium : is Open source automation tool.
source code of the project is open to all people -- Free --

any body can download Selenium and


available in the form Selenium.jar

- can be used to automate browser - only web based appl


but not desktop appl's

Web appl :
----------
the appl's which are opened by browser -- chrome, firefox , Edge...etc

ex: amazon.com, Redbus.com

- at a time multiple people can access the web appl

Desktop appl :
--------------
the appl which are installed in our desk top machine -

ex: VLC.exe , note pad

-at a time only one user can access the appl

FAQ What is the diff b/w Web based appl and Desktop appl?
--------------------------------------------------------
1.Def:
2.ex:
3.how many users can access?

to automate Desktop appl 's --> 3r party s/w or tools ex:AutoIT

Selenium alone - cannot automate desktop appl's


-supports multiple browsers
ex:
Chrome
IE - Microsoft - stopped giving support
Edge --->
Firefox browser
Safari (in MAC o/s) -- not avaialble in windows o/s

- supports Multiple Programing languages


ex: Java, ..NET, Python , JavaScript , Perl,ruby....etc

UFT - paid tool -- buy licence -- > supports only one language i.e VBscript

- Supports Multiple o/s


ex: Windows , Linux , Mac o/s

UFT - supports only windows o/s

- migrate to Selenium automation code project

demand --
UFT -- paid tool ---> free tools / open source -- > use in project
UFT code --- > migrate to Selenium automation code project

Selenium Advantages:
-------------------
tell same above points

---------------------------
Comparison with commercial tools :
------------------------------------------
Selenium UFT
(Open source Tool) (Commercial /paid tool)
-------------------------------------------------------------------
1. Open source - freely
- buy license in order to use tool

2. to automate web appl's only


- UFT- automate web appl's and also Desktop appl's

3. supports multiple browsers : ex: chrome, Firefox, IE , Edge , Safari


initially designed to Firefox browsers

UFT -- intially IE, later chrome, FF

4.Suports multiple lang's ex: Java, Python ,Perl Ruby..etc

UFT - VBscript programing

5. Suports multiple o/s ex: windows, Linux, MAC o/s


UFT -- Windows o/s only
tools cannot be used in Linux. MAc o/s as UFT s/w is not aavilable for
Linux, MAC o/s.

6.Cannot generate Automation test results by Default


Note : to generate Test results --> 3rd part s/w -- TestNG, Extent
Reports

UFT -- generate test results by default at end of execution


7. - does not support OR concept by default

OR- Object Repository :


-----------------------
is place where we maintain all the obj's info
ex: in login page--> user name, pwd, Login btn

- UFT -- supports OR concept by default

8. no proper techincal help/ support Team from Selenium


--> Selenium forums.

UFT ---> Customer support team


if any where some tool functioanlty is not working -- > setup meeting
with UFT support Team
Resolve ur issue

------------------------------------------------------
FAQ: Disadvantages of Selenium:
-------------------------------

1. Selenium cannot automate Desktop appl's


note: 3rd party tool--> AutoIT tool --> to automate Desktop appl

2. Cannot automate bar code scanninng appl's

3. Recpatcha testing cannot be done

4. cannot generate automation Test results by default


to genarete test results >>> 3 rd party tool --TestNG, Extent reports

5. No proper techncial Support from Selenium

------------------------------------
Download Install JDK 8 or 11 Version
Download Eclipse IDE

***********************************************************************************
*********************
13-jul-2024
***********************************************************************************
*********************
Java Introduction:
-----------------
Java is open source Programming language.

- to establish communictaion b/w 2 things


- English --> English lang
- Machine ---> Programming language

Program : collection of stmts


can be used to perform specific task

ex: addition 10 + 20 = 30
substraction 20 - 10 = 10

- is Object oriented Proagramming Language


- means in Java is everything is represneted in the form obj and class

OOPS features :
----------------

Object & class


Inheritance
Polymorphism
Abstraction
Encapsulation

ex: Java , C#.net, Python. etc

if any Programing lang supports above OOPs features -- Object oriented Programming
language.

• Platform independence:
-------------------------------
-Java is platform indepenent lang

-- platform -- any o/s


windows
Linux
Mac o/s

A.java -->run windows --> A Results (Same results)


Linux --> A Results (Same results)
Mac o/s --> A Results (Same results)

platform dependent lang:

ex: C- Language ,

A.c --> Run in window --> A Results


--> Linux --> B Results

Note: VB script (in Windows o/s)

Java applications:
-----------------
1. develop Desk top appl's

ex: vlc.exe, notepad(text file)

2. develop web based applications


ex: amazon.com , facebook.com

3. Mobile applications (android appl's)


eX: Whats app, amazon

4. in ERP applications
ex: Saleforce -

5. Java can be used in Automation testing tools

6. to develop webservices also


------------------------------------------
FAQ: JDK,JRE,JVM:
------------------

JDK : Java Development Kit

- can be used to develop/ write java program + run Java program


- JDK s/w

JRE: Java RunTime Environment

- can be used to run Java Program only

- Note: we cannnot write/develop java Programs using JRE

-can be installed individually

install JDK > installs also JRE by default

JDK contains JRE . JRE part of JDK

JDK = JRE + JVM + LIB + BIN + etc..

FAQ Diff b/w JDK and JRE ?


--------------------------

JVM : Java Virtual Machine

- set of programs or specifications -


- can be to execute Java Program.

Java - developed James Gosling -- By Sun Micro Systems company

-now acquired by Oracle Company


-------------------------------------
• JDK installation:
------------------------
download JDK 11:
https://www.oracle.com/in/java/technologies/javase/jdk11-archive-downloads.html

Note : after clicking download link > Select checkbox 'I reviewed and accept the
Oracle Technology Network License Agreement for Oracle Java SE
' --> Click Download btn > create Oracle account with ur gmail and password >
login with ur gmail > download

it will download - "jdk-11.0.15.1_windows-x64_bin.exe"


Click jdk.exe file from downloads folder> Click Next > Next > Finish

Check Java Installed :


-----------------------
Go and check in ur system:
C:\Program Files\Java\jdk-11.0.15.1

cmd :
-----
open cmd Prompt window : Pressing 'Windows' btn + R --> It opens 'Run' window >
Type 'cmd' > click 'Ok' or Press enter button > opens 'Cmd prompt window' in
black screen

java -version

ex:
C:\Users\Lenovo>java -version

java version "11.0.15.1" 2022-04-22 LTS


Java(TM) SE Runtime Environment 18.9 (build 11.0.15.1+2-LTS-10)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.15.1+2-LTS-10, mixed mode)
--------------------------------

Download "Eclipse" :
-----------------
Open Eclipse :

Create Workspace :
------------------

Create Project :
---------------
steps:
--------
File >New > Other > Search for Java Project > Select 'Java Project > Click "Next"
> ' Give some "Project name" i.e "Jul2024JavaProject" > finish or Next> Click
Finish button > click 'Dont create ' button > it creates new Project i.e
'Jul2024JavaProject" in 'package explorer' window in left side

if we expand Java project, there are 2 folders available .

1. src
2.JRE System Libraries

check Project Current Location in our system:


------------------------------------------
Steps:
----
Select project > Rt click > Properties ' option (or) alt + Enter > Location :C:\
brahma\Practise\SelniumPractiseNew\Nov2023WorkSpace\Nov182023JavaProject > click
'Right arrow' icon > it opens the Folder in ur system.

HW Create 2 Java Projects in Eclipse and find the location of the project in ur
system ?

***********************************************************************************
*********************
15-Jul-2024
***********************************************************************************
*********************
Keywords in Java :
-----------------
to learn any lang --> alphabets A, B,C
make words Apple, Bat...etc

make stmt - > I like an apple - --> have to follow some grammar rules -->
Syntax rules
Apple like I ---invalid stmt
I apple like

Sys will not understand our lang english --> java lang stmts---> Machine
Level Lang (001010101) -- (Sys or Processor understands)

Keyword:
---------

Def:
----
are pre defined words in Java lang.
Reserved words: which has special meaning in Java lang.
which are reserved for Special purpose.

ex:

int --> is keyword, can be used to store integer numbers 10,20, -15

float --> decimal number ex: 10.23f, 4.5f

double --> decimal number ex: 10.23, 4.5

char --> used to store single character 'A' , 'B'

boolean --> to store true, false values

if --> k/w in java , can be used write if (condi) stmt


else -->
for
while
break

class --> is k/w in java lang-can be used to define/ write class

Syntax:
class someClassName
{

ex2: creating some 'employee' class


class employee
{

ex3: create student class


class student
{
}

Note:
-----
without writing/defining any class, we cannot write any java Program.
- if we want to write any java program, we must write/define class

interface- k./w
syntax :

interface I1
{

public
static
void ---

...etc

---------------------
Create Package and Class:
-------------------------
Package :
---------
collection of classes and Interfaces

class1 + Interface1
class2 + Interface2
class3 + Interface3

create Package :
------------

Steps:
--------
select 'src' folder> Rt click > New > Package > enter Name: package1 > clk
'Finish' button > it creates new package i.e Package1 in src folder

Create class :
----------------
Select Package i.e Package1 , Rt click > new > class >Enter some class name :
class1 class1 > click Finish
> it create new class i.e class1 in the selected package

Create Interface :
------------------
HW : write Naviagation steps how to create interface (same as above)

HW Create 2 packages,2 classes , 2 interfaces


package: MyJavaPrograms ---> create some classes (A, B) + interfaces
(I3,I4)
Package : MySeleniumPrograms --> Create some classes(C1,C2) +
interfaces (I5,I6)
Comments:
---------
can be used to understand the program clearly

• Types of comments:
--------------------------

2 types

1. Single line comment:


start with //

2. Multi Line comments

package Package1;

public class MyClass1


{
// Program name : Writing comments
// Devleoped Date: 6-Apr-2023
// Comments will not be executed .. and it will be ignored

// Note: Single line comments :


// select line + Press Ctrl + / == to comment lines
// uncomment line = Press Ctrl + /

// stmt1
// stm2
// stmt3

// note2 :
//select multiple lines and Press ctrl + / -- it comments selected lines
// select multiple lines and Press ctrl + / -- it uncomments selected lines

// stmt1
// stm2
// stmt3

2. Multi line comments :


--------------------

// Multi Lines : starts with /* */

package SamplePackage1;

public class MulitLineComments


{
// Multi Lines : starts with /* */

/* Author : Brahma
Program name : Writing comments
Devleoped Date: 15-Jul-2024

*/

/* stmt-1
stm-2
stm-3
*/

// Note : select multiple lines - Press ctrl+ shft + /


// uncomment - ctrl+ shft + \

/*
* Author : Brahma Program name : Writing comments Devleoped Date: 6-Apr-2023
*
* stnt-1 stm2 stm-2
*/

/* stmt-1
stm-2
stm-3
*/

First Java program in Eclipse:


------------------------------
package Package1;

public class FirstJavaProgram {


// we have to write main()
public static void main(String [] args)
{ // special method in java
// program execution always starts from main() method only

// stmt : collection of words + syntax rules


// display some msg "Hi Java" in console window/ monitor
System.out.println("Hi Java");
// print given msg and it goes to new line

//println() : predefined method in java


// can be used to display given msg in console window/ o/p window/
monitor
// what ever we write in dbl quotes -- it displays as it is ..

// Semicolon ; is stmt terminator


// Every stmt must end with semi colon;

// to display msg How are you?


System.out.println("How are you");
// print given msg and it goes to new line

}
run java :
----------
right click inside main method > run as > Java applictaion

o/p:
-----
Hi Java
How are you

------------------------------------

ex2:
package Package1;

public class JavaProgram2


{
// write main () -special method --
///when we run java, JVM or o/s Calls main- method by default
// Execution starts from main - method
public static void main(String args[])
{
// Display msg in stmt-1
System.out.println("stmt-1");

// // Display msg in stmt-2


System.out.println("stmt-2");

// Display msg in stmt-3


System.out.println("stmt-3");

// Short cut :
// to write println () --
//type syso + Press -(ctrl + space) and press enter- it displays
println() stmt fully
System.out.println("stmt-4");
System.out.println("stmt-5");

}
//o/p:
stmt-1
stmt-2
stmt-3
stmt-4
stmt-5

If we dont have laptop, We can run java program in online java -compiler
Refer: https://www.programiz.com/java-programming/online-compiler/

------------------------------------

**************************************
16-Jul-2024
**************************************
println("Hi Java"); : can be used to print the given msg and cursor goes to next
line

print(): - is predefined method in java


- can be used to print the given msg in console window and cursor is in the same
line

print basics Program:


-----------------------

package Introduction;

public class printBasics {

public static void main(String[] args)


{
System.out.print("Hi Java"); // print given msgs and cursor is in the
same line
System.out.print("How are you");
System.out.print("I am fine");
}

/*
* o/p:
* Hi JavaHow are youI am fine
*
*/

FAQ : Diff b/w println() and print() ?

HW : display below o/p using println and print()

o/p:
Hi Ram
Learn Java
sure

HW : display below o/p using println() and print()


o/p: Hi RamLearn Javasure

-------------------------
package Introduction;

public class MixingPrintlnAndPrint


{
// write main ()
public static void main(String args[])
{
System.out.print("Hi Java");
System.out.println("How are you");
System.out.println("I am fine");
System.out.print("What about you.");

/* ctrl + / or ctrl+ shft +/


* o/p:

* I am fine
* What about you.
*
*
*/

HW write o/p for below program:

System.out.println("Hi Java");
System.out.print("How are you");
System.out.print("I am fine");
System.out.println("What about you.");

\n - goes to new line


ex:

package Package1;

public class MixingPrintlnAndPrint


{

public static void main(String args[])


{
//\n - goes to new line
System.out.print("Hi Java\n");
System.out.print("How are you\n");
System.out.print("I am fine\n");
System.out.print("What about you.\n");

o/p:
Hi Java
How are you
I am fine
What about you.

-------------------------------------
HW in the above program replace \n by \t write the o/p?
\t -represents tab (Enter 5 spaces)
.
A B C D
5 spaces
Different ways to run Java Program:
------------------------------------
1. from Eclipse
2. through command prompt window

1. Eclipse:
----------------
1. RT click inside main () --> Run as --> Java appl
2. In Menu Items (under 'navigate' or 'Project' menu) >click 'play button
(or) Run button' > it runs java program

2. through command prompt window:


---------------------------------

We can write java program in notepad/txt file

steps to create java file in notepad:


------------------------------------
open note pad > type Java Program > Go to file menu > Save as > Give File name
as same as class name with extension .java (SampleJava.java) > Save > it creates
'SampleJava.java' file

cmds :
-------------------
1. compile java program:
syntax :
javac javafilename.java
javac SampleJava.java

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>javac SampleJava.java
SampleJava.java:7: error: unclosed string literal
System.out.println("Hi Java')
^
1 error

System.out.println("Hi Java")

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>javac SampleJava.java
SampleJava.java:7: error: ';' expected
System.out.println("Hi Java")
^
1 error

Compilation Process:
--------------------------
Compiler : will check all errors in programs. if at all we have errors, it
displays all error details
. if at all there are no errors >

Sample.java to > Sample.class ( contains byte code instructions) --> JVM


( Run / execute java programs)

> to low level lang (or) Machine level lang ( 01010) --> Processor (or) system >
executes the instruction
> display the o/p on console window

once we compile java progam- it creates class file with same name as classname >>
byte code instructions
> JVM -> Machine lang (or) low level language > machine (or) system or
processor understands only machine lang only > Executes program and displays the
o/p

FAQ JVM ?
JVM convert byte code instructions to machine lang and it will be given to
processsor . executes the instruction
> display the o/p on console window

- used to run Java program

2. run java Program :


-----------------------------
Syntax: cmd : java javafilename

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms> javac SampleJava.java

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>java SampleJava
Hi Java

Modify Some msg in code : Hi Ram

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>java SampleJava
Hi Java

not displaying Hi Ram .. again we must compile java if we modify any line in java
program.

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>javac SampleJava.java

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>java SampleJava
Hi Ram

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>

Note : every java program, first we must compile and then Run Java program.

if you modify some code/ add 2 (or) 3 lines of code, first we must compile again
, then run java program.

compile : javac filename.java


Run : java filename

java Filename.java -- error - dont use it i.e .java


java Filename.class --> error - donot use it i.e .class
eX:

C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>java SimpleJava.class
Error: Could not find or load main class SimpleJava.class
Caused by: java.lang.ClassNotFoundException: SimpleJava.class
C:\brahma\Practise\SelniumPractiseNew\JavaPrograms>java SimpleJava.java
error: class found on application class path: SimpleJava

HW Create 2 Programs in notepad and compile and Run it?


Sample2.java
Sample3.java

----------------------------
Datatypes in Java:
--------------------
what type of data we are storing / using

numbers : 10,20,-34 --> int - predefined word or keyword or datatype

decimal nos --> float , double 10.54, 3.45

'A', 'B' -- > char

true/ false --> boolean

"RamaRao" ---> String

2 types:
-------
1.Primitive data types:

2.Reference Data types

1.Primitive data types:


------------------------------
can be used to store single value at a time

Numbers:
-------

Data Type Size Description


---------------------------------------------------------------
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
------------------------------------------------------------
----------------------------------
Decimal nos : 10.5 , 3,45

float : is predefined word in java lang


-- to store decimal numbers
- allocates 4B memory
- can store 7 decimal numbers after decimal point
eX: 2.1234567f - f - represnts float value

double :
----------
is predefined in java .
- can be used to store decimal nos
-allocate 8B of memory
- can store 15 values after decimal point

eX: 10.34 - if we dont write f, it will consider as double value


2.34d -- d for double

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 dig

character:
-----------
to store single character -- char
char - is predefined k/w in java

--can be used to single char

ex: 'A', 'B', 'C'

invalid : 'ABC'
- it must be enclosed in single quotes
-- allocated 2Bytes of memory

char 2 bytes Stores a single character/letter or ASCII values

----------------------
boolean :
------------
is predefined k/w in java lang.

- can be used store only true and false values

Note: we cannnot store any other values in boolean data type


ex: true, false

-- invalid ex: 'A' , "true", 10, 20, 10.24 -invalid


Memory
boolean 1 bit S stores true or false values

----------------------------------------------------------

Revision:
-------

• Numbers --> Byte, short, int, long


• Decimal numbers --> float, double
• Character --> char 'A'
• true/false --> boolean
-----------------------------------

************************************************************************
17-Jul-2024
************************************************************************

2.Reference Data types:


------------------------
can be used to store multiple values (10,20,30) at a time
ex: arrays -- can be used to store group of values -- later classes
String (is predefined class in java language)
or any predefined class

String :
-----------

"Rama", "Sita"

collection of characters which must be enclosed in dbl quotes i.e "rama"

group of .... "abc123" ,, "123" , "123.()", ".*"

-is not primitive data type - is predefined class in java. but it is often used
in the form of data types.

***********************************************************************************
*********************

FAQ Diff b/w primitive data type and reference data type ?
Def
ex: byte,short,int, long
float , double ,
char, boolean

arrays- store multiple values


String

-----------------------
Variable:
------------------
In Mathemtics,

x = 10
y = 20
z = x + y , what is the value of z?

Z =
//
// z= 30

x,y,z - are variables

ex2:
a = 3
b =2
c = a*b, c= ?
c =
c =

a,b,c - are variables

= : assignment operator, can be used to assign/ Store some value/


a = 10 // comment:
// 10 value is tored in var i.e a
Variable Def: is some meaningful name (or) container - can be used to store some
value
- to hold some value

Declare Variables and Assign values:


------------------------------------
Syntax :
--------
datatype somevarname;

ex: store numbers

// declaring var i.e a of type int --> int a;


byte a2;

// a is var , which is of type - int . so in var i.e a , we can store integer


numbers

Declare var (esal) and store decimal no's --> float esal;

// esal is var of type float data type- so esal var we can store only decimal
no's

Declare byte var --> byte b;


b is var , which is of type - byte- so in var b, we can store integer numbers.

HW Delcare short variable ,long variable , double, char variable ?

Assign values to variable :


-------------------------
Syntax :
--------

a = 10;

varName = val/ var/ Expression;

1. varname= val;

we need = operator - assignment operator


// store 10 in variable 'a'
a =10;
10 val is assigned to left side var i.e a contains 10

// store 20 in variable 'b'


b =20;

20 val..... b contains 20

2. varName = var;
int a;
a =10;
int b;
b = a;// value of a i.e 10 is assigned to left side var i.e b so b contains
10 val.
// 10

b = 10

3. varName = Expression;
c = a +b;
c= 10 + 20
30
c = 30 rt side expression is evaluated/calculated first and result will
be stored in left side var i.e c
so C contains 30 val.

Note:
---------
1. Left side, always we must use varname only
invalid :
10 = a ; Left side, we have to use varname only
10.657 = b; // invalid stmt

Check below are valid and invalid:

c =25; --> left side is var valid


35 = d; --> invlaid
1.45f = f ; --> invalid

2. Right side, we can write val/ var/ Expression


a = 10;
c = a;
c = a+ b;

Check below are valid and invalid:

a =c; --> valid


a+ b = c --> invalid

----------------------------------
Int basic program:
-----------------
package SamplePackage1;

public class IntBasicsProgram


{
public static void main(String args[])
{
// int :
// a =10
// b=20
// c= a+b

// If we want to use some var i,e a , so first we must declare var


// with out declaring var name , we cannnot use var in program
// datatype varName;
// Declare var's a,,b,c of type int
int a;
int b;
int c;

// store 10, 20 values in variables a, b


a = 10;
b = 20;
c = a + b;
// 10 +2 0
// 30
// c = 30
/// c = ?
// print the val of a, ,b ,c

System.out.println("hi Java");
System.out.println(a);
// 10
System.out.println("a");// a

System.out.println(b);
// 20

System.out.println(c);
// 30

o/p:
---
hi Java
10
a
20
30

---------------------

HW Declare variables for "byte" data type and store some values and display
o/p ?
HW Declare variables for "short" data type and store some values and display
o/p ?
HW Declare variables for "long" data type and store some values and display
o/p ?

package SamplePackage1;

public class IntBasicsProgram2


{
public static void main(String args[])
{
//Can We store decimal numbers in int variable ?
int a;
a = 10;
// a = 3.45f; // Error : Type mismatch: cannot
convert from float to int
// we cannot store decimal no in int
var
// int var- we can store integer values but not decimal
numbers

// Note :
//Can We store char value into int variable ?
a = 'B';
// 66
// value of ASCii no A -65 , B -66, C-67.....
// 66
// a= 66
// ascci
System.out.println(a);
// 66 . Note: it wont display 'a'

// Can We store true/ false value into int variable ?


// a = true; ///Error: Type mismatch: cannot convert
from boolean to int

---------------------------------------

Float basics:
--------------
package SamplePackage1;

public class FloatBasics {

public static void main(String[] args)


{
// float : store decimal no's 10.45f, 2.34f
// at end of decimal no , we have to use 'f' ex: 10.45f,
1.3f
// Declare float var
// datatype varname;

// Declare float var f and store 2.3 f


float f;

// so we can store only decimal nos


f = 2.3f;
// display f var value
System.out.println(f);
// 2.3

//can we store int value (4) into float var i.e f


f = 4;
// 4 --> 4.0 5 -> 5.0 8 --> 8.0
// f= 4.0
// int val is converted to left side data type i.e
float
// int val is converted to float val
// --->
// display f var value
System.out.println(f);
// 4.0 but not 4

// can we store char value ('A') into float var i.e f


f = 'A';

// A - 65
// 65
// f = 65
// 65 ---> 65.0
// f = 65.0
// display f var value
System.out.println(f);
// 65.0 but not 'A' and
not 65

// left side float data type, it always o/p in the


form float value only

//HW can we store boolean vals (true, false) into float


var

// Type mismatch: cannot convert from boolean to float

o/p:
------------
2.3
4.0
65.0

--------------------------
double basics:
-------------
package SamplePackage1;

public class DoubleBasics {

public static void main(String[] args) {


// Double : store decimal no
// declare var i.e x is of type 'double' data type and store 2.34
// so we can store dec no

double x;
x = 2.34d;
// d- double. even if we dont write 'd' at end - it will be considered
as double value
//x = 3.45;// d is optional

// display x
System.out.println(x);
// 2.34

// store 4.534d; into x


x = 4.534d;

// display x var
System.out.println(x);

// 4.534
// note :
//Select all lines > ctrl + I - Indentation (or) allignment of
lines proper

********************************************
18-Jul-2024
********************************************
char basic program:
---------------------
package SamplePackage1;

public class CharBasics {

public static void main(String[] args) {

// char : 'a', 'F'


// Declare char var (ch) and store 'A'
// datatype someVarName;
char ch;

// ch is var name, which is of type -char


// so we can store char values only 'A', 'B'
// char value must be written in single quotes i.e 'A' , 'B'
// store 'A' into ch
ch = 'A';

// ch = B;//Error : B cannot be resolved to a variable

// Can we store "B" into ch


// ch = "B"; // "B" -- String
//Error : type mismatch: cannot convert from String to char

// ch = 'ABC';//error: Invalid character constant


// in single quotes , we have to write single char only but not group
of characters.

// display var ch
System.out.println(ch);// A
// A

// Can we store int number (66) in char var ?


ch = 66;
// 'B'
// ch ='B'
// A - Ascci no - 65, B - 66, C - 67
// 66 --> 'B'
// int no converted to char
// always , o/p will be displayed based on left side var data type
// left side- char data type, so o/p will be displayed as char value
only i.e 'B' but not 66
System.out.println(ch);
// B

o/p:
----
A
B

---------------------------------------

// HW Can we store float, double , booolean values into char var ?


ch = 65.96f;
ch = 67.965d;
ch = true;
---------------------------------------------

Boolean Basics Program:


--------------
package SamplePackage1;

public class BooleanBasics {

public static void main(String[] args) {


// boolean : store true / false values --> boolean values
// Declare boolean var (a) and store true value
// datatype varName;
boolean a;

// a is var, which is of type boolean


// so in var a, we can store boolean values i.e true or false only
a = true;

// display var a
System.out.println(a);
// true

// store false value in var a


a = false;

// display var a
System.out.println(a);
// false

// Can we store int value 10 into boolean var a


// a = 10;
//Error: Type mismatch: cannot convert from int to boolean

// Error : boolean data type , we can store only true / false values
but not int no

//// Can we store float value 2.34f into boolean var a


// a = 2.34f;//Type mismatch: cannot convert from float to boolean
// // Error : bolean data type , we can store only true /
false values but not decimal no

//// Can we store char value 'A' into boolean var a


// a = 'A';//Type mismatch: cannot convert from char to boolean
// Error : bolean data type , we can store only true / false values
but not character value

//// Can we store String value "Rama" into boolean var a


// a = "Rama";//Type mismatch: cannot convert from String to boolean
// Error : boleean data type , we can store only true /
false values but not String

String :
---------
is collection of characters (or) group of chars's
- must be enclosed dbl quotes

ex: "rama" , "Sita" , "abc123", "abc123(.*"

Declare String variable :


-------------------------

package SamplePackage1;

public class StringBasics {

public static void main(String[] args) {


// Declare String var and store "rama"
// delcare int var a --> int a;
String s;

// s is var, which is of type String


// so in String var,we can store String value "Ram", "Sita123",
"Ram.@gmail.com"
// We must write double quotes to store string value

// store "rama" into s variable


s= "rama";

// display string s var


System.out.println(s);
// rama

Revision :
---------
// byte, short,int, long --> to store integer values 10,20,-10
// float, double --> decimal no 1.34f, 1.45d
// char --> 'A'
// boolean --> true / false
// String --> "ram"

-----------------------------
Concatenation Operator (+):
---------------------
package SamplePackage1;

public class ConcatenationOpertaor {

public static void main(String[] args) {


// + is addition operator (or) concatenation
// 10 + 20 = 30

// declare var i.e c and perform addition of 10 and 20


int c;
c= 10 +20;

// 30
// c = 30
// c = right side expression is evaluated /
calculated and result will be stored in left side var
// i.e C so C contains 30 val.
// display var c
System.out.println(c);
// 30

// + concatenation Operator:
// performs concatenation (or) joining values
// Note: if any one value is String, it performs
concatenation or joining values
// "ram" + 20 --> ram20

// 10 + "sita" --> 10sita

// "rama" + "sita" --> ramasita

System.out.println("ram"+20);// --> ram20


System.out.println(10+"sita");// -->10sita
System.out.println("rama" + "sita");// --> ramasita

System.out.println("rama" + "sita" + "lakshman");//--


>ramasitalaskshman

System.out.println(1 +3);//--> 4
System.out.println("1" + 3); // --> joining 13
System.out.println(1+ "3");// joining 13
System.out.println("1"+ "3");//joining 13

System.out.println(1 + "Sita");// 1Sita


System.out.println(1 + "Sita"+ 2);// 1Sita2

// Declare var and store Rama value in the same line


// String s;
// s = "Rama";
// or
String s = "Rama";

// possible / valid stmt


System.out.println("s");// s -- here "s" -s string
System.out.println(s);// Rama
// here s is var

// display o/p --> String s value is =Rama


System.out.println("String s value is =" + s);

// "String s value is = + "Rama"


// String s value is =Rama

// FAQ : Written exam 10 + 20 + "Ram" -->


System.out.println( 10 + 20 + "Ram"); // 30Ram but not
1020Ram
// 30 + "Ram"
// 30Ram

// FAQ : Written exam "Ram" + 10 +20 -->


System.out.println( "Ram" + 10 +20);// Ram1020 but not
Ram30
// "Ram10" + 20
// / "Ram1020"

// System.out.println("Rama" -10);// invalid stmt


//The operator - is undefined for the argument type(s)
String, int

o/p:
30
ram20
10sita
ramasita
ramasitalakshman
4
13
13
13
1Sita
1Sita2
s
Rama
String s value is =Rama
30Ram
Ram1020

-------------------------------
• Declare Multiple Variables and assign values:
-----------------------------------------------
declare single var :
------------------

datatype varName;

// Assign value to var

varName= val/var/ Expression;

declare var i.e a of type int and store some value 20

int a;
a = 20;

or
int a =20;

--------------------
declare variables a,b,c of type = int in and store 10,20,30

int a;
int b;
int c;

a =10;
b=20;
c=30;

Syntax :
--------
datatype VarName1 , VarName2, VarName3.... etc ;

// Declare 3 variables a, b,c of type int in single line


int a,b,c;

// Declare 2 float variables in single line


float f1, f2;

//HW Declare 3 double variables in single line

//HW declare 2 char variables in single line

//HW declare 2 boolean variables in single line

//HW Declare 2 String variables in single line?


Assign Value to variables:
--------------------------
varName = val / var/ Exp;

Store 10,20,30 values into variables a,b,c

---------------
package SamplePackage1;

public class MultipleVarDeclaration {

public static void main(String[] args) {


// Declare variables a,b,c in single line and store multiple values in
diff lines
int a,b,c;

// store 10 into a
a = 10;

// print a
System.out.println("a="+ a);
// a = 10

//store 20 into b
b =20;
System.out.println("b="+ b);
//store 30 into c
c = 30;
System.out.println("c="+ c);

// a= 11, b=22,c=33;// invalid stmt - dont write


// a, b ,c = 10;// invalid

// Declare variables i.e a1,b1,c1 and assigning 1,2,3 values in the


same line
// syntax: datatype var1 =val1 , var2 = val2 , var3 = val3;
int a1 =1 , b1 =2,c1=3; // Valid stmt

// Display a1
System.out.println("a1=" + a1);
// 1
// Display b1
System.out.println("b1=" + b1);
// 2
// Display c1
System.out.println("c1=" + c1);
// 3
// Can we declare one int , one float var in single line
// int a5, float f;

// invalid - diff data types declaration in single line -is not


possible

// declaring single var a2 and and assign the 20 value in the same
line
int a6 =20;

// int x,y,z = 10,20,30;// invalid stmt

// -------------------
Note:
package SamplePackage1;

public class MultipleVarDeclaration {

public static void main(String[] args) {


// local var : the variables , which are declared inside method
// all local variables must be initialised with some value
else it throws error

int a3;// // all local variables must be initialised with


some value else it throws error
// display a3
System.out.println("a3=" + a3);
// The local variable a3 may not have been initialized
}

------------------------
package SamplePackage1;

public class MultipleVarDeclaration {

public static void main(String[] args) {

int a, b ,c; // local var : the variables , which are declared inside
method
a= 10; // all local variables must be initilased with some value else
it throws error
b=20;
c=30;

// a, b ,c = 10;// invalid
a = b = c = 20;
// c= 20
// b =20
// a =20
//
//

// display a,,b,c
System.out.println("a="+a);
// "a=" + 20
// a=20
System.out.println("b="+b);
// "b=" + 20
// b = 20
System.out.println("c="+c);
// c =20

**********************************
19-Jul-2024
**********************************

Rules to Declare variable name:


package SamplePackage1;

public class RulesToDeclareVarName {

public static void main(String[] args) {

// while writing any var name, we have to follow some rules


//
// A variable name must start with a letter or an
underscore character (_)
// A variable name cannot start with a digit
// A variable name can only contain alpha-numeric
characters and underscores (a-z, A-Z, 0-9, and _ )
// Variable names are case-sensitive (age, Age and AGE
are three different variables)
// There is no limit on the length of the variable name
// A variable name cannot contain spaces
// The variable name cannot be any java keywords

// A variable name must start with a letter or an underscore


character (_)
//ex:valid
int abc;
int _eid;

//ex invalid
// int 1ename;// invalid. var name should not
start with digit
// int 25;// var name must start with alphabet or
Underscore

// A variable name can only contain alpha-numeric characters


and underscores (a-z, A-Z, 0-9, and _ )
int ename123_City;

// special char's ( . * @ ) are not allowed except _


// int emp(id; // special char i.e '(' is
not allowed in var anme
// int emp.id; // . is special char - not
allowed in var name

// _ is special char --
String emp_name;// valid

// Except _ underscore - it wont allow any other special charaters

// float emp#salary; // invalid. # is special char

// Variable names are case-sensitive (age, Age and AGE are


three different variables)
int age = 10;
int Age = 20;
int AGE = 30;

// Display age, Age,AGE


System.out.println("age ="+age);
System.out.println("Age ="+Age);
System.out.println("AGE ="+AGE);

// There is no limit on the length of the variable name


// 256 max length of var name
String
enameafsafsafsakjfjksafhjsahfsafdsafsafsafasfafafsf2341442134325325325;

// Note : always try to give very short name and meaningful name

// A variable name cannot contain spaces


// int emp id;

// Var name must not allow any space

// The variable name cannot be any Java keywords


// ex: int, float, char, boolean-- if , class

// int char; /error // char is predefined


keyword in java lang

// if is predefiend wor or k/w in java lang


// so we should not use any k/w for var name

// int boolean;// invalid


// boolean int;// invalid
// class String ; // dont use String as var name

// any prefdefined k/w , we should not use for class name


// above rules are applicable for class name also
// class if
// {
//
// }

// ex: class int


// {
//
// }

// duplicate var names are not allowed in java


// int empno;//Eror Duplicate local variable empno
// int empno;// empno already declared in previous lines some
where

// String empname;
// String empname;// Duplicate local variable empname

ex: find out which var name is valid /invalid?

variable name valid/invalid


------------------------------------
ename --> valid var name
123Empno --> invalid. var name (var name shoust start with alph + _)
_empno --> valid var name
emp_city --> valid var name
emp123 --> valid var name
emp.no --> invalid var name as it does not allow special char's except _
(empname --> invalid as '(' is special char
int --> invalid var name as int is predefined word/ key word
any k/w in java lang ,we should not use for var name .

-------------------------------------------------------
Operators:
-----------
1. Arithmetic operators: + , - ,*, / , %

2.Relation operators /Comparison operators

3.Compound operators

4.Logical operators - and -&&, OR- ||, not ! (not missed)

5.Increment operators , ++pre, Post ++

6.Decrement operators --Pre, post--

1.Arithmetic operators:
-----------------------
+ - * / %
used perfom arithematic opertions like addition, subtsraction , Multiplication,
division
+
-
*
/ - Quotient val
% - Remainder operator

2 + 3
3 - 2
3 * 2
3 / 2 = Division operator - gives Quotient val
3 % 2 = Remainder opertator --gives Remainder val

package OperatorsBasics;
public class ArithematicOperators {

public static void main(String[] args)


{
// Arithematic : + - * / %
// 2 nos
//Declare 2 variables a,b and store 3,2 values
int a, b;
a =3;
b =2;

// Declare add var


int add;

// perform addition of a and b


add = a+b;
// 3 + 2
// = 5
// add = 5 rt side exp is evaluated and result will be stored in
left side var i.e add
// so add contains 5 val
// display result
System.out.println("add="+ add);
// 5

// Declare sub var and perform subtsraction


int sub;
sub = a-b;
// 3- 2
// 1
// sub = 1

// Display sub o/p


System.out.println("sub="+ sub);
// 1

// HW Perform Multiplication Operation of 2 no's and display the o/p?

// / - Division operator - Gives Quotient value

int div = a/b;


// 3/2 // Quo = 1
// 1
// div =1
// display division

// "div=" + 1
// div=1

// 3 /2 - Quotient val

// 2) 3 ( 1 -(Quotient val)
// 2
// ---------------
// 1 (Remainder)
System.out.println("div= " + div);
// % - Remainder operator
int rem = a % b;
// rem = 3 % 2 ;
// rem= 1
System.out.println("rem ="+ rem);
// rem val=1

// 5/ 2 = quotient val
// 5 % 2 = Remainder val

// 2 ) 5 (2 Quotient val)
// 4
// ------------------------
// 1(remainder val)

System.out.println(5/2);// 2
System.out.println(5%2);// 1

System.out.println(9/2);//4 -quotient
System.out.println(9%2);// 1 rem val
}
}

// HW Perform add, sub, mul, div (quo, Remainder) of 2 nos 6 ,2 and display the
o/p?

// HW Perform add, sub, mul, div (quo, Remainder) of 2 nos 7,2 and display the
o/p?

------------------------
o Relation operators /Comparison operators:
------------------------------------------------
can be used to compare 2 nos and gives the o/p in the form of true/ false

<
>
<=
>=
==
!= not equal

check these stmts are true / false:


-------------------------
6 == 6 --> gives o./p : true
6 == 3 -->

6 < 5 =
3 < 5 =

6 > 5 =
3 > 5 =

6 <= 5 -->
6 <= 6 -->
3 <= 6 -->

6 >= 5 -->
6 >= 6 -->
3 >= 6 -->

6 != 3 -->
6 != 6 -->
package OperatorsBasics;

public class RelationalOperators {

public static void main(String[] args) {


System.out.println(6<5);//false
System.out.println(3<5);// true

System.out.println(6>5);// true
System.out.println(3>5);// false

System.out.println(6<=5);// false
System.out.println(6<=6);// true
System.out.println(3<= 6);// true

System.out.println(6>=5);// true
System.out.println(6>=6);// true
System.out.println(3>=6);// false

// HW do below work
// 6 == 6 gives o./p : -->
// 6 == 3 -->

//// HW do below work


// 6 != 3 - -->
// 6 != 6 - -->

// declare a,b variables of int and store 6,5


int a,b;
a = 6;
b = 5;

// compare a<b and store into int result variable


// int res = a < b;
// int res = a < b;
// 6 < 5
// false
// int res = a < b;// Type mismatch: cannot convert from
boolean to int
// if we want to store boolean values true/ false values , we have to
use 'boolean ' data type left side
// We cannot store boolean value true/ false values in int var i.e res
boolean res = a<b;

// 6 < 5 ;
// res = false = is a boolean val

// display result
System.out.println("res= "+ res);
// res=false
}

HW : write the o/.p for below stmts?

2 == 2
2 == 3

3 > 2
2 > 3

6 < 3
6 < 8

3 >= 2
3 >= 3
3 >= 10

3 <= 2
3<=3
3<=10

3 !=3
3! =10

Note :
----
3 > 3 --> False
3 < 3 --> False
System.out.println(3>3);// false
System.out.println(3<3);// false

------------------------
Compound operators:
--------------------------
mixed operators =

+=
-=
*=
/=
%=

package OperatorsBasics;

public class CompoundOperators {

public static void main(String[] args) {

int a = 2;
a += 5;
// a = a +5;
// 2 + 5
// 7
// a = 7
System.out.println("a="+ a);// 7 but not 2

a -= 5;
// a= a-5;
// 7-5
// 2
// dont substitute a= 2 , substitute a=7
//
// a = 2
System.out.println("a="+ a);//2

a *= 5;
// a = a*5 ;
// 2* 5
// 10
// a = 10
System.out.println("a="+ a);// 10

a/=5;
// a = a / 5;
// 10 / 5 == Quotient
//
// a = 2
System.out.println("a="+ a);// 2

a%=5;
// a = a %5;
// 2 % 5;
// a= 2 rem val
// 5) 2 ( 0 - not 0.4
// 0
// ---------
//// 2 -- rem

System.out.println("a="+ a);// 2

// we can store + ve no, and -ve no's in var


// store -3 val into var a
a = -3;
System.out.println("a="+ a);
// -3
// assign +3 val into var i.e a
a = +3;
System.out.println("a="+a);//a=3

We can write below stmts like

a= 3;
b =2;

a+=b;
// a = a + b;
//
//

a-=b;
// a = a-b;
//
//

HW
a*=b;
a/=b;
a%=b;

2) 5 ( -Quotient val

-------------
-rem val

Logical operators - and -&&, OR- ||, not !


--------------------------------------------------

&& - Logical and operator :


- can be used to perform Mulitplication (*) operation on Boolean values

0 - false
1 - true (or any no 235)

a b a && b (Multiplication)
-------------------------------
0 0 0
0 1 0
1 0 0
1 1 1
--------------------
a b a && b (Multiplication)
---------------------------------------
false false false
false true false
true false false
true true true

// if any one i/p is false- && gives o/p - false


// if both i.p's are true - && - true

package OperatorsBasics;

public class LogicalAndOperator {

public static void main(String[] args) {


// Declare boolean var a, b and store false , false
boolean a, b;
a = false;
b = false;

// Declare boolean var result and perform logical and operation


boolean result = a && b ;
// false && false; *
// false
// result = false
// if any one i/p is false- && gives o/p - false else true
// if both i.p's are true - && - true

// Display Result a &&b


System.out.println("result ="+ result);
// false
// Store false, true values into a, b
a= false;
b = true;

// Declare boolean var result and and performs logical and


operation
// boolean result;
// no 2 var's can have same name.
// Var name must be unique
// duplicate var names are not allowed in java lang.
result = a && b;
// false && true
// false

// Display var result and and performs logical and


operation
System.out.println("result ="+ result);

// Store true, false values into a, b


a = true;
b = false;

// // Display Result a &&b


result = a&&b;
// true && false;
// false

// result = false
System.out.println("Result a &&b ="+ result); // false

// Store true, true values into a, b

a = true;
b = true;

// // Display Result a &&b


result = a && b;
// true && true
// true
System.out.println("Result a &&b ="+ result);// true

// System.out.println("&& on numbers" + (1&&3));


// the operator && is undefined for the argument type(s)
int, int
// Note: we should not use any numbers for Logical and
operator
// always we must give boolean val / boolean var

}
-------------------------

|| - Logical OR operator :
-------------------------
Pipe symbol
- can be used to perform addition (+) operation on boolean values

if any one i/p is true - Logical OR gives o/p: true else false
if both i/p's are false - false

a b a || b (Addition +)
------------------
0 0 0
0 1 1
1 0 1
1 1 1
--------------------
a b a || b (addition+)
--------------------------------
false false false
false true true
true false true
true true true
-------------------------

HW check logical OR truth table with all bolean values?

package OperatorsBasics;

public class LogicalOROperator {

public static void main(String[] args) {


// Declare boolean variables a,b and store false, false

// declare boolean var result and performs logical OR operation

// addition
//
// Display Result

//

// store false, true into a,b

// perform logical OR operation and store the o/p into result var

//
// Display Result

// store true,false into a,b

// perform logical OR operation and store the o/p into result var

//
// Display Result

// store true,true into a,b

// perform logical OR operation and store the o/p into result var

//
// Display Result

// Can we use || for numbers?


// System.out.println(" || on numbers" + (1||3));
// the operator || is undefined for the argument type(s) int, int
// Note: we should not use any numbers for Logical OR operator
// always we must give boolean val / boolean var with Logical OR
operator

****************************
20-Jul-2024
****************************

logical Not (!):


----------------
performs nagation operation

!true = false
!false = true
package OperatorsBasics;

public class LogicalNotOperator {

public static void main(String[] args) {


boolean a = true;
boolean res = !a;
/// ! true
// false
// res = false

System.out.println("res ="+ res); // false

a = false;
res = !a;
// ! false
// true
// res = false;
System.out.println("res ="+ res);// false

}
AND, OR , Not
&& || !
* + Negation

Note: && has high priority than ||

Write o/p for below programs?

Ex1:
boolean result = true || false && true;
// 1st calculate / evaluate && only
// true || false
// true
System.out.println(result);// true

Ex2:
boolean result = (5 > 3) && (2 < 4);
// true && true
// true
System.out.println(result);// true
Ex3:
int x = 5;
boolean result = (x >= 5) || (x < 2);
// 5>=5 5<2
// true || false
// true
System.out.println(result);

HW Ex4:
boolean result = (7 < 5) && (8 > 3) || (9 != 9);
// //
// //
// //
System.out.println(result);

HW Ex5:
int x = 4;
int y = 6;
boolean result = (x == 4) && (y != 6) || (x < y);
// //
// //
// //
System.out.println(result);

HW Ex6:
int a = 8;
int b = 3;
boolean result = (a % 2 == 0) || (b % 2 != 0);
//
//
//
System.out.println(result);
HW Ex7:
boolean result = (4 >= 4) && (2 != 2) || (7 <= 7);
//
//
//
System.out.println(result);
HW Ex8:
boolean a = true;
boolean b = false;
boolean result = (a && b) || (!b);
//
//
System.out.println(result);
HW Ex9:
int x = 10;
boolean result = (x < 5) && (x == 10) || (x > 5);
//
//
//
System.out.println(result);

-----------------------------
Increment operators :
-------------------------------
can be used to increment val of var by 1

Pre Increment Operator:


++ var;

Post Increment Operator:


var ++;

-------------------
package OperatorsBasics;

public class IncrementOperator1 {

public static void main(String[] args) {

int a = 2;
++ a;// pre Increment
// a = a +1;
// 2 +1
// a = 3
System.out.println("a="+ a);// 3

a= 3;
a ++;// Post Increment
// a = a+1;
// 3 +1
// a= 4
System.out.println("a="+ a);// 4

---------------------
package OperatorsBasics;

public class IncrementOperator2 {

public static void main(String[] args)


{
int a = 2;
System.out.println(++a);//
// 1st Increment val + displays the var val
// a= a +1
// 2 +1
// 3
// 3
a = 4;
System.out.println(a++);//
// displays var val + increment val later
// print a = 4 1st, a+1
// 4+1
// a= 5
a= 5;
System.out.println(++a);//
// 1st increment the var value + display var vale
// 5+1
// 6
// a=6. print a= 6
a = 4;
System.out.println(++a);//
// 1st incremnting + display var value
// a+1
// 4+1
// a =5 ,, dispaly a=5

a= 7;
System.out.println(a++);
// 1st display var value + incremnting
// 7 7+1 =8

o Decrement operators --Pre, post--:


--------------------------------------------
can be used to decrease the val by 1

Pre Decrement Operators:


----------------------
-- var; PreDecrement

Post decrement :
var --;

package OperatorsBasics;

public class DecementOperator {

public static void main(String[] args) {

int a = 3;

--a;
// a= a -1
// 3-1
// a=2
System.out.println("a="+a);// 2

a= 4;
a --;//
// a = a-1;
// 4-1
// a= 3

System.out.println("a="+a);// 3

------------------

package OperatorsBasics;

public class DecementOperator2 {

public static void main(String[] args) {


int a = 3;

System.out.println(--a);//
// 1st perform decrement + display var
// a-1
// 3-1
// a=2 , display a=2

a= 5;
System.out.println(--a);//
// 1st it performs decrementing + display var value
// a-1
// 5-1
// a= 4,, display a =4

a= 6;
System.out.println(a--);//
// display var , + perform Decrement
// print a =6 , a-1
// 6-1
// a = 5

System.out.println("a="+a);// 5

a =7;
System.out.println(a--);// 7
// display var value + decrementing
// a-1
// print a = 7 7-1
// A= 6

}
}

--------------------
package OperatorsBasics;

public class USTWrittemExam {

public static void main(String[] args)


{
int x =5;
System.out.println(x++);//
// Display var value + incrementing
// print 5 , x+1
// 5+1
// x=6

System.out.println(++x);//
// 1st increment + display var later
// x +1
// 6+1
// x=7, print 7
System.out.println(x--);//
// display var + decrementing later
// print 7 first , x-1
// 7-1
// x= 6
System.out.println(--x); //
// 1st decrementing + display var later
// x-1
// 6-1
// x= 5 diaplay x =5

HW write the o/p for the below program?

package OperatorsBasics;

public class USTWrittemExam2 {

public static void main(String[] args)


{
int x =3;
System.out.println(x++);//

System.out.println(x++);//

System.out.println(++x);//

System.out.println(++x); //

}
}

HW write the o/p for the below program?

package OperatorsBasics;

public class USTWrittemExam3 {

public static void main(String[] args)


{
int x =3;
System.out.println(x--);//

System.out.println(x--);//

System.out.println(--x);//

System.out.println(--x); //

Flow Control Statements:


--------------------------------
can be used to control the flow of Program execution

a = 20; // Assignment stmt

1.Conditional stmts:
--------------------

ex:

if() cond stmt

Switch - condi stmt

2. Loop stmts:
------------
For
while loop
do while loop

1.Conditional stmts:
----------------------
if() cond stmt

'if' is pre defined word (or) keyword in java


- can be used to write if cond stmt

syntax:
if (cond) note : there is no ; at the end of if stmt
{ // if block / beginning of if block
stmt2; // gets executed if cond is true only
stm3;
} // end of if block

stmt4;

if cond is true , it executes stmt2, stm3, stmt-4


false , it wont enter enter if block, will come out of if block.
executes all stmts after if block i.e
stmt4;

block : collection stmts which are enclosed in curly braces

ex:
{ // if block / beginning of 'if' block
stmt2;
stm3;
} // end of if block

Ex1: // Example 1: Checking if a number is greater than 10

package ConditionalStatements;

public class ifbasics1 {

public static void main(String[] args) {


// Ex1: // Example 1: Checking if a number is greater than 10

int num = 15;

if(num > 10)


{// 15 >10
// true - enters if block
System.out.println("Given number is > 10");
System.out.println("stmt-2");
System.out.println("stmt-3");
}

System.out.println("after if block");

o/p:
----
Given number is > 10
stmt-2
stmt-3
after if block
-ve :

package ConditionalStatements;

public class ifbasics1 {

public static void main(String[] args) {


// Ex1: // Example 1: Checking if a number is greater than 10

int num = 3;

if(num > 10)


{// 3 >10
// false - does not enter if block and control goes after if
block
System.out.println("Given number is > 10");
System.out.println("stmt-2");
System.out.println("stmt-3");
}

System.out.println("after if block");

o/p:
after if block

Ex2: // Example 1: Checking if a number is Less than 10

package ConditionalStatements;

public class ifbasics2 {

public static void main(String[] args) {

//Ex2: // Example 1: Check given number is Less than 10


int num = 5;

if(num<10)
{// 5 <10 true,enters if block
System.out.println("Given number is <10");//
}

System.out.println("after if block ");

o/p:
Given number is <10
after if block

-ve:
package ConditionalStatements;

public class ifbasics2 {

public static void main(String[] args) {

//Ex2: // Example 1: Check given number is Less than 10


// int num = 5;
int num = 30;

if(num<10)
{// 30 <10 false, does not enter if block, ctrl goes after if block
and executes all stmts
System.out.println("Given number is <10");//
}

System.out.println("after if block ");

}
o/p:
after if block

ex2: Write o/p for below program?


package ConditionalStatements;

public class ifbasics1 {

public static void main(String[] args) {

System.out.println("stmt-1");

if(true)
{
System.out.println("stmt-2");
System.out.println("stmt-3");
}

System.out.println("stmt-4");
}

o/p:
stmt-1
stmt-2
stmt-3
stmt-4

ex2: Write o/p for below program?


--------------------------------
package IFCondStmts;

public class ifbasics1 {


public static void main(String[] args) {

System.out.println("stmt-1");

if(false)
{
System.out.println("stmt-2");
System.out.println("stmt-3");
}

System.out.println("stmt-4");

}
o/p:

stmt-1
stmt-4

-----------------------
2. if else stmt

stmt1;

if(cond)
{
stmt -2; // gets executed if cond is true only
stmt -3;
}
else // else - k/w in java - can be used to define else block
{
stmt -4;
stmt -5;
} // end of if block

stmt6;// always gets executed if cond - true/ false

ex1: Write o/p for below program?

package IFCondStmts;

public class ifElsebasics1 {

public static void main(String[] args) {

System.out.println("stmt-1");

if(true)
{
System.out.println("stmt-2");// true
System.out.println("stmt-3");
}
else // if con- is false - else block gets executed
{
System.out.println("stmt-4");
System.out.println("stmt-5");
}

System.out.println("stmt-6");

o/p:
--------
stmt-1
stmt-2
stmt-3
stmt-6

ex2: Write o/p for below program?

package IFCondStmts;

public class ifElsebasics2 {

public static void main(String[] args) {

System.out.println("stmt-1");

if(false)
{
System.out.println("stmt-2");// true
System.out.println("stmt-3");
}
else // if con- is false - else block gets executed
{
System.out.println("stmt-4");
System.out.println("stmt-5");
}

System.out.println("stmt-6");

o/p:
-------
stmt-1
stmt-4
stmt-5
stmt-6

if ()

if else
ex: write a program to check the given Age is greater than 18.
If age is > 18, display msg “age is >18”
Else display msg “age is not >18 ”

package ConditionalStatements;

public class CheckAgeisGreaterThan18 {

public static void main(String[] args) {


// ex: write a program to check the given Age is greater than 18.
// If age is > 18, display msg “age is >18”
// Else display msg “age is not >18 ”

int age = 20;


if(age > 18)
{
System.out.println("age is >18");
}
else
{
System.out.println("age is not >18 ");
}

************************
21-Jul-2024
************************

ex: program to check given number is even number.


If it is even no, display “Given no is even no”
Else display msg “Given no is not even”

package ConditionalStatements;

public class EvenNo {

public static void main(String[] args) {


// Even no = check no is divisible by 2 = if we get remainder ==0 -
even no
// else not even no

int num = 4;
// int num = 5;

if(num%2 == 0)
{// 4 %2
// 0 == 0 true, it enters if block
System.out.println("It is Even no");
}
else
{
System.out.println("It is not Even no");
}
}

-ve :

ex2:
package IFCondStmts;

public class EvenNo {

public static void main(String[] args) {


// Even no
//
int num = 3;

if(num%2 == 0)
{// 3%2
// 1 == 0 false, it goes to else block
System.out.println("It is Even no");
}
else
{
System.out.println("It is not Even no");
}

o/p"
It is not Even no

--------------------------------

WAP to check given no is odd no or not

if no is odd no- display msg "It is odd no"


else display msg "It is not odd no"
package ConditionalStatements;

public class OddNo {

public static void main(String[] args) {


// Odd no - reminder value == 1
//
int num =3;

if(num%2 == 1)
{// 3%2
// 1 == 1 true, enters if block
System.out.println("It is Odd no");//
}
else
{
System.out.println("It is not Oddd no");
}
}

o/p:
It is Odd no

package ConditionalStatements;

public class OddNo {

public static void main(String[] args) {


// Odd no - reminder value == 1
//
// int num =3;
int num =4;

if(num%2 == 1)
{// 4%2
// 0 == 1, false, does not enter if block, ctrl goes to else part
and executes stmts inside the else block
System.out.println("It is Odd no");//
}
else
{
System.out.println("It is not Oddd no");
}

o/p:
----
It is not Oddd no

HW WAP if marks >=35 -Display msg "student passed"


else --> "Student failed"

HW WAP to check given salary is > =50000 -- display msg "Salary is >=50000"
else display msg "Salary is not > = 50,000

HW WAP to check Esal <= 50,000, display msg "Salary <= 50000"
else Salary is not <= 50000

HW WAP to check esal = 10,000 , display msg "esal=10000"


else display msg "esal is not equal 10000"

WAP to increment salary by 10000 for eid =10;

package ConditionalStatements;

public class IncrementSal {


public static void main(String[] args) {
// WAP increment salary by 10000 for eid =10;

int eid =10;


int empsal = 30000;
int incrementSalary = 10000;

if(eid == 10)
{// 10 == 10, true, enters if block
empsal = empsal + incrementSalary;
// 30000 + 10000
// 40000
//empsal = 40000

System.out.println("empsal incremented.empsal= "+empsal);


// 40000
}
else
{
System.out.println("No Increment ");
}

-ve:
package ConditionalStatements;

public class IncrementSal {

public static void main(String[] args) {


// WAP increment salary by 10000 for eid =10;

// int eid =10;


int eid =25;

int empsal = 30000;


int incrementSalary = 10000;

if(eid == 10)
{// 25 == 10, false,does not enters if block, ctrl goes to else block
empsal = empsal + incrementSalary;
// 30000 + 10000
// 40000
//empsal = 40000

System.out.println("empsal incremented.empsal= "+empsal);


// 40000
}
else
{
System.out.println("No Increment ");
}
}

o/p:
No Increment

HW WAP to check esal > 80000 , decrease sal by 5000

//WAP to check eid =100 and esal =50000?


package IFCondStmts;
package ConditionalStatements;

public class ifWithAnd {

public static void main(String[] args) {


// // WAP to check eid =100 and esal =50000?

int eid = 100;


int esal = 50000;

if(eid == 100 && esal == 50000)


{// 100 == 100 50000 == 50000
// true && true
// true
System.out.println("eid == 100 && esal == 50000");
}
else
{
System.out.println("not eid == 100 && esal == 50000");
}

-ve:
package ConditionalStatements;

public class ifWithAnd {

public static void main(String[] args) {


// // WAP to check eid =100 and esal =50000?

// int eid = 100;


int eid = 55;
int esal = 50000;

if(eid == 100 && esal == 50000)


{// 55 == 100 50000 == 50000
// false && true
// false, goes to else
System.out.println("eid == 100 && esal == 50000");
}
else
{
System.out.println("not eid == 100 && esal == 50000");
}

//HW WAP to check eid =100 or esal =50 000, display proper msg eid = 100 or
salary is 50000
else display msg "either eid is not = 100 or salary is not = 50000"
//note : use logical OR symbol
package ConditionalStatements;

public class ifWithOr {

public static void main(String[] args) {


//HW WAP to check eid =100 or esal =50 000, display proper msg eid =
100 or salary is 50000
// else display msg "either eid is not = 100 or salary is not = 50000"

int eid =100;


int esal = 50000;

if(eid == 100 || esal ==50000 )


{//100 == 100 || 50000 == 50000
// true || true
// true. enters if block
System.out.println("eid = 100 or salary is 50000");
}
else
{
System.out.println("either eid is not = 100 or salary is not =
50000");
}

-ve:
package ConditionalStatements;

public class ifWithOr {

public static void main(String[] args) {


//HW WAP to check eid =100 or esal =50 000, display proper msg eid =
100 or salary is 50000
// else display msg "either eid is not = 100 or salary is not = 50000"

int eid =200;


int esal = 70000;

if(eid == 100 || esal ==50000 )


{//200 == 100 || 70000 == 50000
// false || false
// false. does notenters if block
System.out.println("eid = 100 or salary is 50000");
}
else
{
System.out.println("either eid is not = 100 or salary is not =
50000");
}

HW WAP to check no is Divisible By 3

HW WAP to check given no divisible by 4

WAP to check given no is PositiveNo or not

10,20 -- = + Ve numbers num > 0 --> Positive no else it is not a +ve no


a = 10;

-1,-2,-3 -- are not Positive numbers -- -VE numbers

package ConditionalStatements;

public class PositiveNo {

public static void main(String[] args) {

// int num = 10;


int num = -2;
// 1,2,4 num >0 +ve no else it is not positive no

if(num >0)// 1
{// 10 >0, true,enters if blck
// -2 > 0, false,
System.out.println("Given no is +Ve no");
}
else
{
System.out.println("Given no is not a +Ve no");
}

---------------------------
3. if else if else if else if () -Multiple else if cond
-----------------
Syntax:

stmt-1;

if(cond)
{
stmts-2;
stmt-3;

else if(cond-2)
{
stmt-4;
stmt-5;
}
else if(cond-3)
{
stmt-6;
stmt-7;
}

stmt-8;

ex: o/p for below program?


-------------------------

package ConditionalStatements;

public class ifbasics3 {

public static void main(String[] args) {

System.out.println("stmt-1");

if(true)
{
System.out.println("stmt-2");// gtes executed if cond - true
System.out.println("stmt-3");
}
else if(true) // if con- is false - else block gets executed
{
System.out.println("stmt-4");
System.out.println("stmt-5");
}
else if(true)
{
System.out.println("stmt-6");
System.out.println("stmt-7");
}

System.out.println("stmt-8");
}

}
o/p:
-----
stmt-1
stmt-2
stmt-3
stmt-8

---------------------
o/p for below program?

package IFCondStmts;
public class ifbasics1 {

public static void main(String[] args) {

System.out.println("stmt-1");

if(false)
{
System.out.println("stmt-2");// gtes executed if cond - true
System.out.println("stmt-3");
}
else if(false) // if con- is false - else block gets executed
{
System.out.println("stmt-4");
System.out.println("stmt-5");
}
else if(false)
{
System.out.println("stmt-6");
System.out.println("stmt-7");
}

System.out.println("stmt-8");

o/p:
---------------
stmt-1
stmt-8

if all conditions are false -- cond-1, cond-2,cond-3 , it will go to out of if


block and execteues stmts after if block.

WAP
// marks > 85 and marks<=100 --> 1st class
// marks > 60 and marks <=85 --> 2nd class
// marks >=35 and marks <=60 --> 3rd class
// else --> Fail

package ConditionalStatements;

public class ifelseIF {

public static void main(String[] args) {

// marks > 85 and marks<=100 --> 1st class


// marks > 60 and marks <=85 --> 2nd class
// marks >=35 and marks <=60 --> 3rd class
// else --> Fail

// int marks = 90;


// int marks = 65;
// int marks = 50;
int marks = 10;

if(marks > 85 && marks <=100)


{// 10 >85 && 10 <=100
// false && true
// false
System.out.println("Student got 1st class");
}
else if(marks>60 && marks <=85)
{// 10 >60 && 10 <=85
// false && true
// false
System.out.println("Student got 2nd class");
}
else if(marks >=35 && marks <=60)
{// 10 >=35 && 10<=60
// fal;se && true
// false
System.out.println("Student got 3rd class");
}
else
{
System.out.println("Student failed");
}

------------------------------
Nested if :
------------
writing if cond stmt with in another if cond stmt- nested if stmt.

syntax:
--------------

if(cond-1)
{ //
if(cond-2)
{ // cond -1 is true and cond-2 is also true

}
else
{
if(cond-3) // cond-1 is false, cond-3 is true
{

}
}

ex1: program - to check the age is >=18, if age >=18, check weight > 50, display
msg "You are eligible to donate blood"

package ConditionalStatements;
public class NestedIfBasics1 {

public static void main(String[] args) {


// ex1: program - to check the age is >=18, if age >=18, check weight >
50,
// display msg "You are eligible to donate blood"

// int age = 20;


// int weight = 60;

// int age = 10;


// int weight = 60;

int age = 25;


int weight = 49;

if(age >=18)
{// 25 >=18, true
System.out.println("age is >=18");

if(weight > 50)


{// 49 >50, fale
System.out.println("You are eligible to donate blood ");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("You are not eligible to donate blood");
}

****************************
22-Jul-2024
****************************
-------------------------
Switch -Conditional stmts
-------------------------

if , else, else if , nested if

- switch - is k/w in java lang.

it executes one statement from multiple conditions

- can be used to check which condition (or) case is matched

syntax:
----------
switch(int val/var (or) char val /var (or) String val/var (or) expresion)
{ // // begining of switch block
case val1 :
stmt1;
break;
case val2:
stmt2;
break;

case val3:
stmt3;
break;

default :
stmt4;

} // // end of swicth block

stmt5;

..............

where there are multiple cases / options are available - we will go for Switch
statement

- is same as multple else if() ..

ex:Write a program to check given dayNo = 1 --> Sunday


2 --> Monday
3 --> TuesDay

package ConditionalStatements;

public class SwitchBasics1 {

public static void main(String[] args) {

// ex:Write a program to check given dayNo = 1 --> display


msg "Sunday"
// 2
--> display msg "Monday"
// 3 --
> display msg "TuesDay "
// else
--> display msg "No case is matched"

int dayNo = 3;
// int dayNo = 5;

switch(dayNo)
{ // 1 // begining of switch
case 1:
System.out.println("1-is Sunday");
break;// come out of switch block and ctrl goes after switch
block
case 2:
System.out.println("2-is Monday");
break;
case 3:
System.out.println("3-is Tuesday");
break;
default:
System.out.println("No case is matched");
}// ending of switch

System.out.println("after switch block");

ex2: if no case is matched


----------------------------

package ConditionalStatements;

public class SwitchBasics1 {

public static void main(String[] args) {

// ex:Write a program to check given dayNo = 1 --> display


msg "Sunday"
// 2
--> display msg "Monday"
// 3 --
> display msg "TuesDay "
// else
--> display msg "No case is matched"

// int dayNo = 3;
int dayNo = 5;

switch(dayNo)
{ // 1 // begining of switch
case 1:
System.out.println("1-is Sunday");
break;// come out of switch block and ctrl goes after switch
block
case 2:
System.out.println("2-is Monday");
break;
case 3:
System.out.println("3-is Tuesday");
break;
default:
System.out.println("No case is matched");
}// ending of switch

System.out.println("after switch block");

o/p:
---
No case is matched
after switch block

Break: is predefined word in java lang

syntax:
--------
break;

// can be used to come out of switch block../ for loop, while loop... etc

if there is no break stmt in case 1 : it goes to Case 2 even if it is not matched,


it executes case 2 stmts.
----
break,default are optional

default : gets executed, when none of case is matched

package IFCondStmts;

public class SwitchBasics1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
// dayNo = 1 -- Sunday
// 2 --> Monday
// 3 --> TuesDay

int dayNo = 1;

switch(dayNo)
{ // beginning of switch block
case 1:
System.out.println("Sunday");
// break;// if we dont write break,
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
// default:
// System.out.println("No case is matched");
} // end of swicth block

System.out.println("after switch block");

o/p:
----
Sunday
Monday
after swicth block
------------------
Note:
------
Duplicate case numbers are not allowed in Switch block
ex:
case 1:
System.out.println("Sunday");
break;
case 1: // Duplicate case are not allowed
System.out.println("Sunday");
break;
case 2:
case 3:
case 2:

package IFCondStmts;

public class SwitchBasics1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
// dayNo = 1 -- Sunday
// 2 --> Monday
// 3 --> TuesDay

int dayNo = 1;

switch(dayNo)
{ // begining of switch block
case 1:
System.out.println("Sunday");
break;
// Duplicate case are not allowed. if we write duplicate cases

case 1:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
// default:
// System.out.println("No case is matched");
} // end of swicth block

System.out.println("after swicth block");

switch(int val/var (or) char val /var (or) String val/var (or) expresion)

// We should not use float val/var or


double val/var or
boolean val/var in Switch Condi

ex: switch(2) -->


switch(int var) -->

switch('A') -->
switch(char var) -->

switch("RAM") -->
switch(String var) -->

switch(2.34f) -->
switch(float var) -->

switch(2.34d) -->
switch(double var) -->

switch(true) -->
switch(false) -->
switch(boolean var) -->

package ConditionalStatements;

public class InvalidSwitchBasics {

public static void main(String[] args) {

// check we can pass float val, double val, in switch()?


float f = 1.0f;
double d = 3.4;
char ch ='A';

// switch(f) // error
// switch(d)
switch(ch)
// Cannot switch on a value of type float. .
//Only convertible int values, strings or enum variables
are permitted
{
case 1.0f:
System.out.println("stmt-1");
break;
case 2.0f:
System.out.println("stmt-2");
break;

default:
System.out.println("default ");

System.out.println("after switch block");

}
}

ex: Switch (char val/var)


--------------------------

package ConditionalStatements;

public class SwitchBasicsByChar {

public static void main(String[] args) {


// A -- Apple
// B -- Ball

char ch ='B';

switch(ch)
// 'B'
{
case 'A': // not macthing
System.out.println("Apple -stmt-1");
break;

case 'B': // matching


System.out.println("-Ball -stmt-2");// yes
break;// can be used to come out of swicth cond

default:
System.out.println("default ");

} // end of switch block

System.out.println("after switch block");

ex: passing boolean values, String value in Switch ()


-----------------------------------------
package ConditionalStatements;

public class SwitchBasicsByBoolean {

public static void main(String[] args) {

// boolean b = true;

String s = "Ram";
// switch(b) // we cannot use boolean var val in switch ()
switch(s)
// Cannot switch on a value of type boolean. .
//Only convertible int values, strings or enum variables are permitted
{
case "Ram": // macthing
System.out.println("Ram - is king");
break;
case "Amar": // matching
System.out.println("-Amar -is normal person");// yes
break;// can be used to come out of swicth cond

default:
System.out.println("default ");

} // end of swicth block

System.out.println("after switch block");

--------------
Switch (String val/ var):
HW WAP "Mon" --> Monday
Tue ---> Tuesday

Note:
-----
Is is better to write break stmt in side each case block. else it executes next
case block also even if case val is not matched.

-----------------------
Revision:
-------
Note :
Switch() - accepts int/char/string val/var
but not float,double, bolean val/var

- Duplicate case values are not allowed


case 1:
case 1:

- break;
- default : block gets executed , if no case val is matched --(or) none of case is
matched

---------------------------
Loop statements:
----------------
execute group of stmts repeatedly

// System.out.println("stmt-1");
// System.out.println("stmt-2");
// System.out.println("stmt-3");
1.For Loop
2.While Loop
3. Do while

1.for Loop:
------------
syntax:

for(intialisation; condi; increment/Decrement operator)


{ 1 2 4

1. it performs initialisation step-1


2.it checks condition -in step -2
if cond is true, it goes inside the loop, executes stmts inside loop (step-3)
and goes to step-4 performs increment/decrement -- again it goes to step-2

if cond (step-2) is true,again it goes inside the loop, executes stmts inside
loop (step-3)
and goes to step-4 performs increment/decrement ---- again it goes to step-2

if cond (step-2) is true,again it goes inside the loop, executes stmts inside
loop (step-3)
and goes to step-4 performs increment/decrement ---- again it goes to step-2

if cond is false, control comes out of loop and goes after out of loop,
executes smts after loop

ex:
package LoopBasics;

public class ForLoop1 {

public static void main(String[] args) {

// System.out.println("stmt-1");
// System.out.println("stmt-2");
//
//
// System.out.println("stmt-1");
// System.out.println("stmt-2");
//
//
// System.out.println("stmt-1");
// System.out.println("stmt-2");

// execute above stmts for 3 times


for(int i=1;i<=3;i++)// i= 1, i+1= 1+1 =2, 2+1 =3, 3+1 =4
{// 1<=3, true, enters for loop, execute for loop stmts,next it
performs incremeting
// 2<=3, true , enters for loop,execute for loop stmts,next
it performs incremeting
// 3<=3 true, enters for loop,execute for loop stmts,next
it performs incremeting
// 4<=3, false, wiill not enter for loop, ctrl goes after
for loop, execute stmts after for loop
System.out.println("stmt-1");
System.out.println("stmt-2");
}// end of for loop

System.out.println("out of for loop");

//o/p:
//stmt-1
//stm-2

//stmt-1
//stm-2

//stmt-1
//stm-2
//out of for loop

o/p:
----

ex:// display numbers 1 to 3


1
2
3

package LoopBasics;

public class ForLoop1to3 {

public static void main(String[] args) {


//
// ex:// display numbers 1 to 3
// 1
// 2
// 3

for(int i=1;i<=3;i++)// i=1, 1+1 =2 +1 =3+1 =4


{// 1<=3 true, enters for loop,incremeting
// 2<=3 , true,enters for loop,
// 3<=3, trye, enters for loop,
// 4<=3 , false, wont enter for loop, ctrl goes after forl
oop

System.out.println(i);
// 1
// 2
// 3
}//
}

o/p:
----
i=1
i=2
i=3
out of for loop
-----------------

display numbers 1 to 5?
package LoopBasics;

public class ForLoop1to5 {

public static void main(String[] args) {


//
// ex:// display numbers 1 to 5
// 1
// 2
//
// 5

for(int i=1;i<=5;i++)// i=1, 1+1 =2, 2+1= 3, 3+1 =4, 4+1 =5, 5+1 =6
{// 1<=5 true, enters for loop,incremeting
// 2<=5 , true,enters for loop,
// 3<=5, true, enters for loop,
// 4<=5 , true, enters for loop,
// 5<=5 true
// 6<=5 false, wont enter for loop, ctrl goes fater for loop
System.out.println(i);
// 1
// 2
// 3
// 4
// 5
}// end of for loop

HW display numbers 1 to 10

HW display numbers 1 to 15

**********************************************
23-Jul-2024
**********************************************

Explain for loop with flow diagram?


Display numbers 2 to 5

package LoopBasics;

public class ForLoop2To5 {

public static void main(String[] args) {


// Display numbers 2 to 5
// 2 3 4 5

for(int i=2;i<=5;i++)//i=2, 2+1 =3, 3+1 =4, 4+1 =5, 5+1= 6


{// 2<=5 , true, enter forloop,
// 3<=5 , true,enter forloop,
// 4<=5 , true
// 5<=5 true
// 6<=5 false, wont enter for loop, ctrl goes after for loop
System.out.println(i);
// 2
// 3

// 4
// 5

}// end of for loop

System.out.println("out of for loop");

o/p:
----
i=2
i=3
i=4
i=5
out of for loop

ex: // Display numbers 3,2,1

package LoopBasics;

public class ForLoop3To1 {

public static void main(String[] args) {


// Display numbers 3,2,1

for(int i=3;i<=1;i++)// i=3


{// 3<=1 false, wont enter for loop, ctr
System.out.println(i);
}

System.out.println("out of for loop");

}
}

o/p:
out of for loop

------
o/p for below program:
----------------------

package LoopBasics;

public class ForLoop2 {

public static void main(String[] args) {

// Display numbers 3,2,1

for(int i=3;i>=1;i++) // i =
{//
//
//
// // cond is always true - will never become false --
loop - it goes to infinite loop
System.out.println(i); //
}

System.out.println("out of for loop");

o/p:
----
3
4
5
6
7
....inifnite looop - as condi is always true

ex:
package LoopBasics;

public class ForLoop3To1 {

public static void main(String[] args) {


// Display numbers 3,2,1 , <=, use >= and -- if you are decreasing
the values
// incrementing <=, ++
// Decrementing >=, --

for(int i=3;i>=1;i--)// i=3,i-1 = 3-1= 2, 2-1= 1, 1-1= 0


{// 3>=1 true, enters for loop
// 2>=1 true, enters for loop
// 1>=1 true, enters for loop
// 0>=1 false, wont enters for loop, ctrls goes after fro
loop
System.out.println(i);
// 3
// 2
// 1
}

System.out.println("out of for loop");

}
o/p:
---
3
2
1
out of for loop

Note :
------

1. in ascending order 1,2,3


i=1;i<=3;i++

while displaying numbers in reverse order - 3,2,1


i=3;i>=1;i--

1. change codition '<=' --> to '>='


2. use always Decrement operator -- dont use increment operator

ex: display numbers 5 ,4,3,2,1

package LoopBasics;

public class ForLoop5to1 {

public static void main(String[] args) {


// TODO Auto-generated method stub

// Display numbers 5,4 3,2,1

for(int i=5;i>=1;i--)// i=5 , 5-1 =4, 4-1 =3, 3-1 =2, 2-1 =1, 1-1 = 0
{// 5>=1 true, for loop
// 4>=1 true , for loop
// 3>=1 true, forl oop
// 2>=1 true
// 1>=1 true , for loop
// 0>=1, False , ctrl goes after for loop
System.out.println(i);
// 5
// 4
// 3
// 2
// 1

System.out.println("out of for loop");

HW display numbers 5 to 2

HW display numbers 10 to 5

Note:
We can write i--, --i or i=i-1 in for loop
and also we can write i = i+2
or i= i+3;..etc

ex: write o/p for below program?


package LoopBasics;

public class ForLoop1 {

public static void main(String[] args) {

for(int i=1;i<=3;i= i+2)// i=1,i+2, 1+2 =3, 3+2 =5


{// 1<=3 true, for loop
// 3<=3 true, for loop
// 5<=3 false, ctrl goes after for loop
System.out.println(i);//
// 1
// 3
}

System.out.println("out of for loop");

o/p:
-----
1
3
out of for loop
------------------------------

while loop:
----------
Syntax:
---------

// initialisation;
// while(condition)
// {
// stmt1;
// stm-2;

// Incre/Decre;
// }

package LoopBasics;

public class WhileLoop1 {

public static void main(String[] args) {


//

int i=1;
while(i<=3)
{ // 1<=3, true, enters while loop
// 2<=3 , true, enters while loop
// 3<=3 , true , enters while loop
// 4<=3 ,false , ctrl goes after while loop

System.out.println("stmt-1");
//stmt-1
// stmt-1
//stmt-1
i++;// i = i+1= 1+1=2 , 2+1 =3, 3+1 =4
}

System.out.println("after while loop");

o/p:
stmt-1
stmt-1
stmt-1
after while loop

ex:
package LoopBasics;

public class WhileLoop1to3 {

public static void main(String[] args) {


//

// display number 1 to 3 for(int i=1;i<=3;i++)

int i=1;
while(i<=3)
{ // 1<=3, true, enters while loop
// 2<= 3 , true , enters while loop
// 3<=3 true , enters while loop
// 4<=3 , false, ctrl goes after while loop
System.out.println(i);
// 1
// 2
// 3

i++;// i= i+1,1+1=2, 2+1=3, 3+1=4


}

System.out.println("after while loop");//

o/p:
----
1
2
3
after while loop

HW display number 1 to 5 using while loop

ex: // display number 2 to 5 incrementing numbers use <=


//
package LoopBasics;

public class WhileLoop2To5 {

public static void main(String[] args) {


//
// display number 2 to 5 incrementing numbers use <=
// Decrementing numbers , use >=
// 2 3 4 5 for(int i=2;i<=5;i++)

int i=2;

while(i<=5)
{
System.out.println(i);

i++;
}

System.out.println("after while loop");//

}
}

----------
HW Write o/p for below program?

package LoopBasics;

public class WhileLoop1 {

public static void main(String[] args) {

int i=3;
while(i<=5)
{ //
//
//
//

System.out.println(i);//
i++;// i =
}

System.out.println("after while loop");//

o/p:
---
3
4
5
after while loop

ex: Write o/p for below program?

package LoopBasics;

public class WhileLoop1 {

public static void main(String[] args) {

int i=3;
while(i>=5)
{ //

System.out.println(i);//
}

System.out.println("after while loop");//

}
o/p:
----
after while loop

HW Display numbers 3 to 1 using while loop

HW Display numbers 5 to 2 using while loop

// display number 3 to 1 reverse order 3,2,,, use >=, -- decrement operator


// in normal order 1,2,3,.. , use <= , and ++
increment operator

***********************************************************************************
*********************

***********************************************************************************
*********************

Display the o/p for below program?


-------------------------------

package LoopBasics;

public class WhileLoop2To5 {

public static void main(String[] args) {

// display 3 to 1
int i=3; // while reversing, we have to use decrement
while(i>=1)
{ // 3>=1 true, enters while loop
// 3>=1 true,enters while loop
// 3>=1 , true, enters while loop
// ...
//....

// / / 3>=1 -True it goes to infinite loop as condi is always


true and
//i=3 always (we are not incrementing/ decrementing i val)
System.out.println("i="+i); //
// i= 3
// i=3
// i=3

System.out.println("after while loop");

//Note :
--------
//while writing loop stmts, write (be careful about) proper increment/ decrement
operators- else it goes to infinite loop

// Display o/p for below program?

package LoopBasics;

public class WhileLoop2To5 {

public static void main(String[] args) {


// display 3 to 1
int i=3; // while reversing, we have to use decrement
while(i>=1)
{ // 3>=1 true, enters while loop
// 4>=1 true, enters while loop
// 5>=1 true, enters while loop

// / / 6>=1 -True it goes to infinite loop as condi is always


true
// ...
// ...
System.out.println("i="+i); //
// i= 3
// i =4

i++;// i=i+1=3+1 =4 , 4+1 =5


}

System.out.println("after while loop");

// Note :
// while writing loop stmts, write (be careful about) proper
increment/ decrement operators- else it goes to infinite loop

o/p:
-----
i =3
i =4
....
....

infinte loop

-----------------

ex: Display the o/p for below program?

package LoopBasics;

public class WhileLoop2To5 {


public static void main(String[] args) {
// display 3 to 1
int i=3; // while reversing, we have to use decrement
while(i>=1)
{
// 3>=1 true, enters while loop
// 2>=1 true, enters while loop
// 1>=1 true, enters while loop
// 0>=1 False- does not enter while loop and comes out of
while loop and goes after while loop
System.out.println("i="+i); //
// i= 3
// i =2
// i= 1

i--;// i = i-1, 3-1 =2, 2-1 =1 , 1-1= 0


}

System.out.println("after while loop");

// Note :
// while writing loop stmts, write (be careful about) proper
increment/ decrement operators- else it goes to infinite loop

}
o/p:
i=3
i=2
i=1
after while loop

-------------------------

HW Display o/p for below program?

package LoopBasics;

public class WhileLoop1 {

public static void main(String[] args) {

// display 3 to 1
int i= -1 ; // while reversing, we have to use decrement
System.out.println(-1>=1);// false
while(i>=1) //
{ // -

System.out.println("i="+i); //

i--;// i=
}

System.out.println("after while loop");

// Note :
// while writing loop stmts, write (be careful about) proper
increment/ decrement operators- else it goes to infinite loop

o/p:
----
false
after while loop
-----------------

HW Display numbers 5 to 1 using while loop


HW Display numbers 10 to 1 using while loop
HW Display numbers 5 to 2 using while loop
HW Display numbers 10 to 3 using while loop
HW Display numbers 10 to -2 using while loop

---------------------------------

HW Display the o/p for below program?

package LoopBasics;

public class WhileLoop1 {

public static void main(String[] args) {

int i=1;

while(i<=3)
{ //
//
//
System.out.println(i); //
i = i+2;// i=
}

System.out.println("after while loop");


}

o/p:
-----
1
3
after while loop

---------------------------
Do while loop:
------------

// do while
// do is predefined word (or) k/w in java language
// can be used to write do while loop stmt
// syntax:
-------------------------
// do
// {
// stmt-1;
// increment / Decrement operator;
// }
// while (condi); // Note : dont forget to write ; in do while loop
stmt

ex:
package LoopBasics;

public class dowhileLoopEx1 {

public static void main(String[] args) {

int i=1;

do
{
System.out.println("stmt1-");// these stmts gte executed
at least once
// stmt1-
// stmt1-
// stmt1-
i++;//i+1 =1+1 =2, 2+1 =3, 3+1 =4
}
while(i<=3);// at end we are checking condi
// 2<=3, true , enters do block
// 3<=3 ,true , enters do block
// 4<=3 false, ctrl goes after do while loop

System.out.println("after do while loop");


}

o/p:
----
stmt1-
stmt1-
stmt1-
after do while loop

package LoopBasics;

public class doWhileLoop1 {

public static void main(String[] args) {


int i=1;

do
{
System.out.println("i="+ i);// i= 1
// do block smts gets executed at least once even if cond is
false
i++;// i =
}
while(i>=3);
// 2>=3 False - it wont go do block
// - does not enter do block and goes after do while loop
System.out.println("after do while loop");

o/p:
-------
i=1
after do while loop

********************************
24-Jul-2024
********************************
Break, continue stmt:
-----------------------
in Switch con
switch()
{

case a:
stmt1;
break; // can be used to come out of switch block

}
------------------

// break: is predefined k/w in java lang


// can be used to come out of loop stmt i.e for loop, while loop, do -
while loop, Switch block also

write o/p for below program?

package LoopBasics;

public class break1 {

public static void main(String[] args) {


// for
int i;
for(i=1;i<=3;i++) // i=1 =1+1 =2
{ // 1<=3 , true, enters for loop
// 2<=3 , true, enters for loop
System.out.println("i="+ i);// i=1 , i=2
if(i==2)
{ //1== 2 , false
// 2==2, true, tt enters if block
break;// --> come out of for loop
// System.out.println("after break ");//
Unreachable code
// Note: dont write any stmts after break k/w
}
System.out.println("after break ");
} // end of for loop

System.out.println("after for loop");

o/p:
----------
i=1
after break
i=2
after for loop

-------------------
write o/p for below program?

package LoopBasics;

public class break1 {

public static void main(String[] args) {


// for
int i;
for(i=1;i<=3;i++) // i=1 =1+1 =2
{ // 1<=3 , true, enters for loop
//
System.out.println("i="+ i);// i=1
if(i==1)
{ //1== 1 , true , it enters if block
//
break;// --> come out of for loop
// System.out.println("after break ");//
Unreachable code
// Note: dont write any stmts after break k/w
}
System.out.println("after break ");
} // end of for loop

System.out.println("after for loop");

}
o/p:

i=1
after for loop

-------------------
break in while loop:
---------------------

package LoopBasics;
public class breakInsideWhileLoop {

public static void main(String[] args)


{
int i=1;
while(i<=3)// i=1
{ // 1<=3, true, enters while loop
// 2<=3, true, enters while loop
System.out.println("Enters loop");// Enters loop, Enters loop
if(i==2)
{ //1==2, false, ctrl goes after if block
//2==2 , true, enters if block
break;// come out of while loop
}

i++;// i = i+1, 1+1=2


} // end of while loop

System.out.println("after while loop");

o/p:
----------
Enters loop
Enters loop
after while loop
----------------
HW what is the o/p for below program?

int i=1;
while(i<=5)
{
if(i==3)
{
System.out.println("i="+ i);
break;
}
System.out.println("after if i="+i);
i++;
} // end of while loop

System.out.println("after while loop");

o/p:

----------------------------------------------------
HW Write 'break' stmt inside "do while" loop?

Note:
------
break can be used in switch, for , while , do while loop
Switch()
{

case val:
stmt1;
break;
case 2 :
stmt2;
break;

for()
{

break;

while()
{

break;

do

{
break;
}
while(cond);

continue:
--------
package LoopBasics;

public class continue1 {

public static void main(String[] args) {


//for loop
for(int i=1;i<=3;i++) // i =1, 1+1=2, 2+1 =3, 3+1 =4
{ // 1<=3, true, enters for loop
// 2<=3, true, enters for loop
// 3<=3, true, enters for loop
// 4<=3, false, ctrl goes after for loop
if(i==2)
{ // 1==2 false, ctrl goes after if block
// 2==2 , true , enters if block
// 3==2 false,ctrl goes after if block
//using continue statement
continue;//it will continue next i value (iteration) and
skip the rest of statements
} // end of if block

System.out.println(i); //1 3
} // end of for loop
System.out.println("after loop");

o.p:

1
3
after loop

--------
Write o/p for the below program ?
package LoopBasics;

public class continue1 {

public static void main(String[] args) {


int i;

for(i=1;i<=3;i++) // i=1, 1+1 = 2, 2+1 =3, 3+1 =4


{ // 1<=3 true, for loop
// 2<=3 true, for loop
// 3<=3 true, for loop
// 4<=3, false, ctrl goes after for loop
System.out.println("i="+ i);// i=1, i=2, i=3
if(i==1)
{ // 1==1 true , if block
//2 ==1 false, ctrl goes after if block
// 3 ==1 false,ctrl goes after if block
// break;// come out of loop // last executeable stmts
inside loop
continue;
// System.out.println("after break ");// error : Unreachable
code
// Note: dont write any stmts after break k/w
// Dont write any stmts after continue k/w
}
System.out.println("after break ");
}// end of for loop

System.out.println("after for loop");

}
o/p:
----
i=1
i=2
after break
i=3
after break
after for loop

---------------------
o Nested If, nested for loop

write o/p for below program?

package LoopBasics;

public class NestedIF2 {

public static void main(String[] args) {


int a= 50;
int b= 20;
int c= 30;

if(a>15) // outer if block


{// 50 >15, true, enters "outer if' block
System.out.println("a> 15");// a>15
if(b>10) // Nested If: writing if condi inside if stmt
{ //20 > 10 , true, it enters "inner if" block
System.out.println("b>10");// b>10
}
}

o/p:
-----------
a> 15
b>10

Nested For loop:


---------------
Def: writing for loop inside another for loop
----
ex:

for() // outer for loop


{
for() // inner for loop
{

package LoopBasics;
public class NestedForLoop {

public static void main(String[] args) {

for(int i=1;i<=3;i++) // outer for loop i=1 , 1+1 =2, 2+1= 3, 3+1 =4
{ // 1<=3, true, enters outer for loop
// 2<=3 , true enters outer for loop
// 3<=3 , true, enters outer for loop
// 4<=3 , false, ctrl goes after "outer for" loop
System.out.println("inside 1st for loop");// inside 1st for loop
for(int j=1;j<=2;j++) // inner for loop j=1,1+1 =2 , 2+1 =3
{ // 1<=2 , true, enters "inner for" loop
// 2<=2, true ,enters "inner for" loop
// 3 <=2, false, ctrl after inner for loop
System.out.println("i="+ i + ",j="+j);
// i = 1 , j= 1
// i= 1 , j =2
// i =2 . j=1
// i = 2 j =2
// i = 3 j =1
// i =3 j =2
}// end of inner loop

System.out.println("after inner loop");// gets executed

} // end of outer for loop

System.out.println("after outer loop");


}

----------------
inside 1st for loop
i=1,j=1
i=1,j=2
after inner loop
inside 1st for loop
i=2,j=1
i=2,j=2
after inner loop
inside 1st for loop
i=3,j=1
i=3,j=2
after inner loop
after outer loop
-----------------

write o/p for below program?

package LoopBasics;

public class NestedForLoop2 {

public static void main(String[] args) {

for(int i=2;i<=4;i++) // outer loop i=2, 2+1 = 3, 3+1 =4, 4+1 =5


{ // 2<=4 true , enters outer for loop
// 3<=4 true, enters outer for loop
// 4<=4 true, enters outer for loop
// 5<=4 false, ctrl goes after outer for loop
for(int j=1;j<=3;j++) // inner loop j=1,1+1 =2,2+1 =3, 3+1 =3
{// 1<=3, true , enters inner for loop
// 2<=3 , true , enters inner for loop
// 3<=3 ,true , enters inner for loop
// 4<=3 false, ctrl goes after "inner for" loop
System.out.println("i="+ i + ",j="+j);//
// 2 1
// 2 2
// 2 3

// 3 1
// 3 2
// 3 3

// 4 1
// 4 2
// 1 3

}// end of inner loop

} // end of "outer for" loop


System.out.println("after outer loop");

o/p:
---
i=2,j=1
i=2,j=2
i=2,j=3
i=3,j=1
i=3,j=2
i=3,j=3
i=4,j=1
i=4,j=2
i=4,j=3
after outer loop
------------------------

-----------------
HW write o/p for below program:

// nested for : writing for loop inside for loop

for(int i=1;i<=2;i++) // outer loop i=


{
for(int j=1;j<=3;j++) // inner loop j=
{
System.out.println("i="+ i + ",j="+j);//

}// end of inner loop


}
System.out.println("after outer loop");

o/p:

*************************************************

Revision:
---------
cond stmts- if(), if else, if .. else if() else if() , Switch

Loop : for loop


while
do while
break, continue

------------------------

Array:
------

int a1= 10;// only val at a time


int a2 = 20;//

// store 100 vals


// declare 100 variables
// ex: a1, a2 , a3.......a100
// ------------------

// Array : is collection of same values


// can be used to store collection of values of same data type
// store homogeneous values
= same type

// 10, 20, 30

// 1.1f, 2.1f, 4.3f

// 'A','B', 'C'

// "Ram", "Sita","Raju"

int a ;
float f;

// Declare/ define array :


----------------------------------------
// syntax :

// datatype varname [] = new datatype [size];


(or)
datatype [] varname = new datatype [size];

data type--> int , float, char.. etc


[] -- array
new - predefined key word in java language
can be used to create array
// size = represents how many values we can store in in array
2 , we can store 2 values in array
3, 3 "" ""

// declare int array with name i.e iarr and size of array = 3
int iarr [] = new int [3];

// declare float array with name i.e farr and size of array = 4
float farr [] = new float [4];

// declare char array with name i.e charr and size of array = 3
char charr [] = new char [3];

// declare "String" array with name i.e farr and size of array = 3
String sarr [] = new String[3];

in array, it stores the values in index no.


the first element of the array is stored at the indexno=0,
2nd element is stored at the indexno =1
............................... and so on.

Store/assign values in array:


-----------------------------
// store 10 val at index no =0

iarr [0] = 10 // 10 value is stored at index no =0 in


array

// store 20 val at index no =1


iarr [1] = 20;
// 20 val is stored at indexno =1 in array

// Access values from array based on index no = 0,1,2...etc


iarr[0] --> 10
iarr[1] --> 20

package ArraysBasics;

public class intArrayBasics {

public static void main(String[] args) {


// create array of int val's and size =3
// datatype arrNAme [] = new datatype [size];
int iarr [] = new int [3];
// store max 3 values only

// store 10 val at index no =0


iarr[0] = 10;
// 10 value is stored at index no =0 in array

// store 20 val at index no =1


iarr[1] = 20;
// 20 val is stored at indexno =1 in array

// store 30 val at index no =2


iarr[2] = 30;
// 30 val at index no =2
// store 40 val at index no =3 --> ???
// 4 th val size =3 max
// arr[4] = 40 ; // error : we dont have index no =
4 .
//.here arr size = 3 index from 0 to size-1 i.e 3-1 = 2
// iarr[4] = 40;

// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:


Index 4 out of bounds for length 3
// at ArraysBasics.intArray.main(intArray.java:62)
// arr [5] index no = 0 to 4
// arr [100] 0 to 99

// display / Access values from array


// display arr val at index no =0
System.out.println("array value at index no = 0-->"+ iarr[0] );
// 10
// display arr val at index no =1
System.out.println("array value at index no = 1-->"+ iarr[1] );
// 20
//// display arr val at index no =2

System.out.println("array value at index no = 1-->"+ iarr[2] );


// 30
}

o/p:
----
array value at index no = 0-->10
array value at index no = 1-->20
array value at index no = 1-->30

*********************************
25-Jul-2024
*********************************
package ArraysBasics;

public class floatArray {

public static void main(String[] args) {


// int arr[] = new int[3];
// Declare float array of size =3
float farr [] = new float [3];
// array name - fArr
// size of array = 3 - we can store max of 3 float values
// index no -always starts from 0 and ends with size of arr -1. i.e
3-1 =2
// index no varies from 0 to 2 - 0,1,2

// store some float values in array


// store 1.2f values in float array at indexno =0
farr[0] = 1.2f;
// store 2.2f values in float array at indexno =1
farr[1] = 2.2f;

// store 3.2f values in float array at indexno =2


farr[2] = 3.2f;

// display vals from float array


// 1.2 2.2 3.2
// 0 1 2 index no
System.out.println("float values in array at index no =0 i.e " +
farr[0]);
System.out.println("float values in array at index no =1 i.e " +
farr[1]);
System.out.println("float values in array at index no =2 i.e " +
farr[2]);

o/p:
float values in array at index no =0 i.e 1.2
float values in array at index no =1 i.e 2.2
float values in array at index no =2 i.e 3.2

HW Define double array and store double values and display it

HW define char array and store char values and display it

HW Define long array and store some values and display it

HW Define boolean array and store boolean values and display it

Note:
---------------------
iarr[0] = 3.2f;// Type mismatch: cannot convert from float to int
// int array - can be used store int values
// floar array - can be used store decimal numbers else it throws
error

2. In one array - We cannot store 1 float val + 1 double val + 1 char val + 1
boolean value
"" "" diff data
iarr[0] = 1.23f;
iarr[0] = 3.2;
iarr[0] = 'C';
iarr[0] = true;
iarr[0] = "Ram";

Display values from array using 'for' loop:


-----------------------------------------

package ArraysBasics;
public class intArrayBasics2 {

public static void main(String[] args) {

// int array : and store 3 values


int iarr [] = new int [3];

iarr [0] =10;


iarr [1] =20;
iarr [2] =30;

//Display each values from array using index no


System.out.println("value at index no =0 i.e "+ iarr[0]);
System.out.println("value at index no =1 i.e "+ iarr[1]);
System.out.println("value at index no =2 i.e "+ iarr[2]);
// .... 100 value

//Display values from array using "for loop":


for(int i=0;i<=2;i++)
{
System.out.println("values from array using for loop ="+
iarr[i]);
}

---------------------------------

Array length:
---------------

package ArraysBasics;

public class intArrayBasics2 {

public static void main(String[] args) {

// int array : and store 3 values


int iarr [] = new int [3];

iarr [0] =10; // index no - 0 to 2


iarr [1] =20;
iarr [2] =30;

//Display each values from array using index no


System.out.println("value at index no =0 i.e "+ iarr[0]);
System.out.println("value at index no =1 i.e "+ iarr[1]);
System.out.println("value at index no =2 i.e "+ iarr[2]);
// .... 100 value

// arr.length property - gives o/p - count of values in array


// syntax: arrName.length;
int count = iarr.length;
// 3
// count = 3
System.out.println("Array length ="+ count);
//Display values from array using "for loop":
// for(int i=0;i<=2;i++)
// for(int i=0;i<=iarr.length-1;i++)//
// 3 -1= 2
for(int i=0;i<=iarr.length;i++)// i =0, 0+1=1, 1+1 =2, 2+1 =3
{// 0<= 3 true , for
// 1<=3 tryue
// 2<= 3 true
// 3<=3 true
System.out.println("values from array using for loop ="+
iarr[i]);
// 10, 20 , 30 iarr[3]
// Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// at ArraysBasics.intArrayBasics2.main(intArrayBasics2.java:32)
}

------------------------------
Display values using for loop in float array:
-------------------------------------------
package ArraysBasics;

public class floatArray {

public static void main(String[] args) {


// int arr[] = new int[3];
// Declare float array and of size =4
float farr [] = new float [4];
// array name - fArr
// size of array = 4 - we can store max of 4 float values
// index no always starts from 0 and ends with size of arr -1. i.e 4-
1 =3
// index no varies from 0 to 3 - 0,1,2,3

// store some float values in array 1.2f,2.2f,3.2f,4.2f in indexno =


0,1,2,3
farr [0] = 1.2f;
farr [1] = 2.2f;
farr [2] = 3.2f;
farr [3] = 4.2f;
//HW Display val at index no =0,1,2

// display all vals from float arr using "for loop" and use length of
array
// length of arr
int lengthofArray = farr.length;
// 4
System.out.println("lengthofArray="+lengthofArray);
// 4
// for(int i=0;i<=3;i++)
for(int i=0;i<=lengthofArray-1;i++)
{// 4-1=3
System.out.println("vals from float array using for loop =" +
farr[i]);
}

o/p:
lengthofArray=4
vals from float array using for loop =1.2
vals from float array using for loop =2.2
vals from float array using for loop =3.2
vals from float array using for loop =4.2

------------------------------------

Note:
In array, we can store same data type of values
homogeneous values

int arr --> store only int vaues


float arr --> store only float values

In General array, we can not store 1 int val + 1 float + 1 double + 1 char
+ 1 boolean + 1 String

Note:
------
in float array, we can store int number and char value, as it converts int no to
float no and char value --> decimal no

fArr [0] = 10; // ok


// 10 --> 10.0f

fArr[1] = 'A';//ok no
// 65 --> 65.0

// fArr [2] = true;// Type mismatch: cannot convert from boolean to float
fArr [2] = "Ramu";// Type mismatch: cannot convert from String to float

HW define long array and store some values and display all values from arr using
"for" loop
HW define double array and store some values and display all values from arr
using "for" loop
HW define boolean array and store some values and display all values from arr
using "for" loop
HW define char array and store some values and display all values from arr using
"for" loop

--------------------------------
Default values in int array:
------------------------------
// if We dont store any vals in array, it will store 0 val based on array
type ie. int
package ArraysBasics;

public class intArrayDefaultValues {

public static void main(String[] args) {

int iarr [] = new int [3];

// if We dont store any vals in array, it will store 0 val


based on array type ie. int

// Display values from array

System.out.println("vals from arr =" + iarr[0]);


System.out.println("vals from arr =" + iarr[1]);

// vals from arr =0


// vals from arr =0
// vals from arr =0

// store some values 11,21 into arr[0] ,arr[1]


iarr[0] =11;
iarr[1] = 21;

// Display values from array


for(int i=0;i<=2;i++)
{
System.out.println("vals from array using for loop="+ iarr[i]);
}

System.out.println("ends here");

------------------
Default values in "float" array : --> 0.0
----------------------------
package ArraysBasics;

public class DefaultValuesinfloatArray {

public static void main(String[] args) {

float fArr[] = new float [4];


// inde no varies = 0 to 3
// if we dont store any vals in float arr, it stores 0.0 by default

// Display values from float array


for(int i=0;i<=fArr.length-1;i++)
{
System.out.println("vals from float array ="+ fArr[i]);
}
// vals from float array =0.0
// vals from float array =0.0
// vals from float array =0.0
// vals from float array =0.0

HW what is the default vals in char array ?


HW what is the default vals in boolean array ?
HW what is the default vals in String array ?

Way2 : Intialise values in integer array (or) Store Values in integer Array:
----------------------------------------------------------------------------

package ArraysBasics;

public class InitialseValsInArr {

public static void main(String[] args) {


// way 1: Declare int array and store 3 values
// int arr [] = new int [3];
//
// arr [0] =10;
// arr [1] =20 ;

// way 2: 10,20,30 with out using index no


// int iarr [] = {10,20,30};
int iarr [] = {10,20,30,40};

// vals at index 0 1 2
// display all vals from array using for loop
for(int i=0;i<=iarr.length-1;i++)
{
System.out.println("vals from array using for loop="+
iarr[i]);
}

}
--------------------
Way2 : Intialise values in float array (or) Store Values in float Array:
------------------------------------------------------------------------
package ArraysBasics;

public class InitialseValsInFloatArr2 {


public static void main(String[] args) {
// Initialise values in float array (or) Store Values in float Array:1.2f ,
2.2f, 3.3f
float farr [] = {1.2f,2.2f,3.3f};
// 0 1 2
// length of array = 3
System.out.println("length of array ="+ farr.length);

// display values from float array using length of array


for(int i=0;i<=farr.length-1;i++)
{// 3-1 =2
System.out.println("vals from float arr=" + farr[i]);
}
// vals from flat arr=1.2
// vals from flat arr=2.2
// vals from flat arr=3.3

HW define "long array" and store vals using 2nd way {120,12313,24214} and
display vals from arr
HW define "double" array and store vals using 2nd way and display vals from
arr
HW define "boolean" array and store vals using 2nd way and display vals from
arr
HW define "char" array and store vals using 2nd way and display vals from arr

Way2 : Intialise values in String array (or) Store Values in String Array:
---------------------------------------------------
package ArraysBasics;

public class StringArr {

public static void main(String[] args) {


// "ram" , "sita", "abc123" , "123" ,".* "

// 0 1 2

String sarr [] = {"ram", "sita", "abc123", "123"};


// 0 1 2 3

System.out.println("1st val =" + sarr[0]); // ram

// HW get all vals from string array using "for" loop

For loop without conidtion:


--------------------------
for(int i=1;i<=3;i++)
{

2. syntax :

for(;;) // if there is no condition in for loop, condi-is consideres always


true only
{

}
- it goes to infinite loop

----------------------------

package ArraysBasics;

public class ForLoopwithoutcondi {

public static void main(String[] args) {


for(;;)
{ // no cond- condi is always true - enters for loop
// no cond- condi is always true - enters for loop
// cond - true -- enters for loop
// ...
// .... infinite loop
System.out.println("stmt-1");
System.out.println("stmt-2");
}
}

o/p:
stmt-1
stmt-2
stmt-1
stmt-2
stmt-1
stmt-2
....
..... infinite loop

--------------------------
for Each loop:
-----------------
can be used to get vals from array / collection obj

syntax :
--------
for(datatype eachVal : arrName)
{

-------------------
Display Values from int Array using for each loop:
=================================================
package ArraysBasics;

public class ForEachLoopForIntarray {

public static void main(String[] args) {


// define int array
int arr [] = {11,22,33,44};

// display all vals using "for each" loop


// for(int val : arr) // ok
for(int x : arr)
{// // gets each val from arr and store each val in to
variable i.e val

// System.out.println("vals from array using for each loop="+


val);
System.out.println("vals from array using for each loop="+
x);
}

---------------
Display Values from float Array using for each loop:?
package ArraysBasics;

public class ForEachLoopForFloatArray {

public static void main(String[] args) {

float farr [] = {1.1f,2.1f,3.1f,4.1f};


// display all values "for each" loop

for(float eachVal : farr)


{
System.out.println("get all vals using for each loop="+ eachVal);

o/p:
-----

HW store some vals in "long" array and gets all vals using "for each" loop?
HW store some vals in "double" array and gets all vals using "for each" loop?
HW store some vals in "char" array and gets all vals using "for each" loop?
HW store some vals in "boolean" array and gets all vals using "for each" loop?
HW Display Values from "String" Array using "for each" loop:

*****************************************
26-Jul-2024
*****************************************

Note:
in 'for each' loop,
// we dont need to write any cond-- no cond
// to get vals from array using for each -loop - we dont need to use--
index no (no index no)
- always get vals in forward direction but not in reverse direction

--------------------
for loop with index :
--------------------
- We have to write cond in for loop
- to get values from array, we have to use index no ex: sarr[0], sarr[1]
- we can get vals in forward and also in reverse direction in for loop

package ArraysBasics;

public class StringgArrUsingForEachLoop {

public static void main(String[] args) {


// TODO Auto-generated method stub
String sarr [] = {"Ram", "Sita", "Raju","Shankar"};
// 0 1 2
//Display Values from String Array using "for each" loop:
for(String x : sarr)
{
System.out.println("gets vals from String array using for each
loop:" + x );
}

System.out.println("After for each loop");


// display values in reverse order
// for(int i=2;i>=0;i--)
for(int i=sarr.length-1;i>=0;i--)
{
System.out.println("vals from array in reverse direction using
for loop = "+ sarr[i]);
}

2 types of arrays:
----------------
1. single dimensional array :
2 . Multi Dim array

1. single dimensional array :


------------------------------

int arr[] = new int[3];


( or) int [] arr = new int [3];

2. 2 Dim array:
-----------

// Declare 2 dim array


data can be stored in the form of rows, columns m,n

----------------------
package ArraysBasics;

public class TwoDimArr {

public static void main(String[] args) {


// Declare 2 dim array and store 2 rows and 3 columns
// int iarr [] = new int[3];--> 1D array

int iarr [] [] = new int [2] [3];

// 4 index no varies from 0- 3

// m = no of rows - 2 respresents rows, index no varies from 0 -1


// n -no of columns- 3 -- columms , index - 0 to 2

// store some values


// 10 1 1 , 12
iarr[0][0] =10;
iarr[0][1] =11;
iarr[0][2] =12;

iarr[1] [0] = 13;


iarr[1] [1] = 14;
iarr[1] [2] = 15;

// display val at index 00


System.out.println("val at index 00 ="+ iarr[0] [0]);

//display val at index 01


System.out.println("val at index 01 ="+ iarr[0] [1]);

// display val at index 11


System.out.println("val at index 11 ="+ iarr[1] [1]);

// display val at index 12


System.out.println("val at index 12 ="+ iarr[1] [2]);

// index no -3
}

o/p:
val at index 00 =10
val at index 01 =11
val at index 11 =14
val at index 12 =15

HW define 2 dim float array- with 2 rows and 3 columns and store some float values
and display all values

HW define 2 dim char array- with 3 rows and 2 columns and store some char values
and display all values

------------------------
// get all values from 2 dimensional array
// 00 01 02
// 10 11 12

package ArraysBasics;

public class getAllValuesFromTwoDimArr {

public static void main(String[] args) {


// Declare 2 dim array
// data can be stored in the form of rows, columns
// int [] [] arr = new int[m] [n];

// or int arr [] [] = new int [m][n];

int arr[] [] = new int [2] [3]; // 4 index no varies from 0- 3

// m = no of rows - 2 respresents rows, index no varies from 0 -1


// n -no of columns- 3 -- columms , index - 0 to 2

// store some value


arr [0] [0] = 00;
arr [0] [1] = 01;
arr [0] [2] = 02;

// 10 1 1 , 12
arr [1] [0] = 10;
arr [1] [1] = 11;
arr [1] [2] = 12;

// get all values from 2 dimensional array using for loop


// 00 01 02
// 10 11 12

for(int i=0;i<=1;i++)// to vary row no i=0 // outer for loop i=0,


0+1=1, 1+1 =2
{// 0<=1 true, enters outer for loop
// 1<=1 true, enters outer for loop
// 2<=1 false, ctrl goes after outer for loop
for(int j=0;j<=2;j++)// to vary columns no // inner for loop j
=0, 0+1=1, 1+1 =2,2+1=3
{// 0<=2 true, inner for loop
// / 1<=2,true, inner for loop
// 2<=2 . true, inner for loop
// 3<=2 false, contr goes after nner for loop
System.out.println("get all vals from 2D array="+ arr[i]
[j]);
// arr[0]
[0]
// arr[0]
[1]
// arr[0]
[2]

// arr[1]
[0]
// arr[1]
[1]
// arr[1]
[2]

}// end of inner for loop

} // end of outer loop

o/p:
-----
vals from arry using for loop=0
vals from arry using for loop=1
vals from arry using for loop=2
vals from arry using for loop=10
vals from arry using for loop=11
vals from arry using for loop=12

---------------------

// HW Define 2 Dim float array of size 1 , 2 and store some values and display
all vals using for loop

// HW Define 2 Dim String aray of size 3 , 4 and store some values and display
all vals using for loop

get 2 Dim array Rows cnt and Columns cnt :


-------------------------------------

package ArraysBasics;
public class getAllValuesFromTwoDimArr {

public static void main(String[] args) {


// Declare 2 dim array
// data can be stored in the form of rows, columns
// int [] [] arr = new int[m] [n];

// or int arr [] [] = new int [m][n];

int arr[] [] = new int [2] [3]; // 4 index no varies from 0- 3

// rows cnt form 2 dim array


int rowsCnt = arr.length;
// 2
System.out.println("rowsCnt ="+ rowsCnt);
// rowsCnt = 2

// Columns cnt form 2 dim array


int colsCnt = arr[0].length;
// 3
// colsCnt = 3
System.out.println("colsCnt =" +colsCnt);
// 3

HW use rows cnt and columns cnt in for loop to display all values from 2 dim
array ?

for(int i=0;i<=1;i++)// to vary row no i=0 // outer for loop i=0,


0+1=1, 1+1 =2
{// 0<=1 true, enters outer for loop
// 1<=1 true, enters outer for loop
// 2<=1 false, ctrl goes after outer for loop
for(int j=0;j<=2;j++)// to vary columns no // inner for loop j
=0, 0+1=1, 1+1 =2,2+1=3
{// 0<=2 true, inner for loop
// /

------------------------------
FAQ SearchForGivenNoInArray :
------------------------

// check given no is exist in array or not


if no is not found in array , display msg "value is not found in array"

package ArraysBasics;

public class SeacrhForGivenNoInArray {


public static void main(String[] args) {
//// check given no is exist in array or not
// if no is not found in array , display msg "value is not found in array"
int iarr [] = {10,20,30};
// 0 1 2
// int searchNo =10;
// int searchNo =20;
// int searchNo =30;
int searchNo =25;
boolean valFound = false;

for(int i=0;i<=iarr.length-1;i++)// i= 0, 0+1=1


{// 0<=2, true ,
// 1<=2 , true
// 2<=2
/// 3<=2
// System.out.println(iarr[i]);// 10,20
if(iarr[i] == searchNo)
{// 10 == 25, false
// 20 == 25, false
// 30 == 25 false
System.out.println("Value ="+ searchNo + " found in
array");
// 10
valFound = true ;
break;
}
else
{
// System.out.println("Value ="+ searchNo + " is not found in
array");
// 20
}
}// end of for loop

if(valFound == false)
{// false == false
System.out.println("Value ="+ searchNo + " is not found in
array");
}

FAQ WAP to count of given character from char array ?


char chArr [] = { 'r' , 'a', 'm','a'}

'a' char count - 2 times


'r' -1 time

// Given char is not found , cnt =0

-------------
package ArraysBasics;

public class CharacterCntInArray {

public static void main(String[] args) {


// char chArr [] = { 'r' , 'a', 'm','a'}
//
// given char 'a' char count - 2 times
// 'r' -1 time
//
// // Given char 'z' is not found , cnt =0

char charr [] = {'r','a','m','a'};


// 0 1 2 3
// char ch ='r';
// char ch ='a';
char ch ='z';
int cnt = 0;

for(int i=0;i<=charr.length-1;i++)
{
// System.out.println(charr[i]);
if(charr[i] == ch) // if val is found in array , increase the cnt
by 1
{// 'r'
cnt = cnt +1;
}

System.out.println("Given char "+ ch + " count ="+ cnt + " times in


array");

-----------------------------

// WAP to get vowels count from char array ?


// Vowels : a e i o u

char chArr [] = { 'r' ,'a', 'm','a','e'}


// vowels cnt = 3 - aa e

package ArraysBasics;

public class VowelCntInArray2 {

public static void main(String[] args) {

// WAP to get vowels count from char array ?


// Vowels : a e i o u

char chArr [] = { 'r' ,'a', 'm','a','e'};


// 0 1 2 3 4
// vowels cnt = 3 - aa e

int vowelsCnt =0;

for(int i=0;i<=chArr.length-1;i++)// i=0,1,2, 3, 4


{// 0<=4, true , for loop
// 1<= 4
// 2<=4 , true
// 3<=4 trye
// 4<=4 try
// System.out.println(chArr[i]);
if(chArr[i] == 'a' || chArr[i] == 'e' || chArr[i] == 'i'||
chArr[i] == 'o' || chArr[i] == 'u')
{ // e a e e m i
m m
// f t f
f f
// t
vowelsCnt = vowelsCnt +1;
// 2 +1
// 3
//vowelsCnt =3
// display vowel
System.out.println("vowel ="+ chArr[i]);//a,a, e
}

System.out.println("vowelsCnt ="+vowelsCnt);

----------------

HW FAQ WAP to get consonants count from char array and display all consonants ?
r a m a

consonants cnt = 2

-----------------------------

HW same program use 'for each' loop ?

HW Same program use for loop and multiple if conditions


hint:
if(eachVal== 'a' )
{
vowelsCnt = vowelsCnt + 1 ;
}
if(eachVal== 'e' )
{
vowelsCnt = vowelsCnt + 1 ;
}
**************************************
27-Jul-2024
**************************************

TypeCasting:
-----------
def:
----

// type casting : converting one Data type to another data type

// 2 types:
// Widening Casting (automatically) - converting a smaller type to a
larger type size
// byte -> short -> char -> int -> long -> float -> double

//. It is also known as implicit conversion or casting down

// conversion is done by compiler automatically

//it is safe because there is no chance to lose data.

ex: convert int --> long , long --> float


package TypeCastingBasics;

public class ImplicitTypeCastingOrWidening {

public static void main(String[] args) {


// ex: convert int --> long , long --> float

int i1 =10;

long l1 = i1;
// int
// 8B 4B -- automatically conversion done by compiler
// 10 --> long 10

//automatically converts the integer type into long type

// ex2 long --> float


// 8B 4B -- Narrowing
long l2 = 50;
float f = l2;
// 50 --> 50.0
//
//automatically converts the long type into float type

System.out.println("Before conversion, int value "+i1);


//
10
System.out.println("After conversion, long value "+l1); // 10
System.out.println("After conversion, float value "+f); // 50.0

}
}

o/p:
---
Before conversion, int value 10
After conversion, long value 10
After conversion, float value 50.0

ex2 : convert int to float ?


package TypeCastingBasics;

public class ImplicitTypeCastingOrWidening2 {

public static void main(String[] args) {


// ex2 : convert int to float ?

// 1. Convert int to float value ---> widening- Compiler will do type


casting by default
// 4 -> 4.0 -- dont lose any data
int i1 = 4;
float f1 = i1;
// 4 --> 4.0
System.out.println("f= "+ f1);
// f= 4.0 but not 4

// Narrowing Casting (manually) - converting a larger type to a smaller


size type
// double -> float -> long -> int -> char -> short -> byte

//// conversion is done by programmer


//It is also known as explicit conversion or casting up.
If we do not perform casting then the compiler reports a compile-time error.

ex:// convert float value to int val?

package TypeCastingBasics;

public class Narrowing1 {

public static void main(String[] args) {


// convert float value to int val? --> narrowing
// 4.32f --> 4 -- lost of data i.e decimal part
value
float f1 = 4.32f;
// int i1 = f1;// Compiler throws error.Programmer- must
perform typecasting manually
// 4B 4Bytes
// Type mismatch: cannot convert from float to int
// i1 = 4.32 f

int i1 = (int) f1;


// (int) 4.32 --> 4 lost of data .32
// 4

// (int) 4.32f // Programmer


// i1= 4
System.out.println("i1="+i1);
// i1=4

// i = f1;// Type mismatch: cannot convert from float to int


// compile will now allow bigger Data type to smaller
// CE: programmer has to do type casting explicitly
i = (int) f1; //
// 3.5 --> remove decimal points 3
System.out.println("i="+ i);// 3 -- data lost

---------------------

// byte -> short -> char -> int -> long -> float -> double

// convert byte val to char


// 65 --> A

package TypeCastingBasics;

public class typeCasting3 {

public static void main(String[] args) {


// TODO Auto-generated method stub

// convert byte val to char


// 65 --> A

byte b = 65;
// char ch = b; //Type mismatch: cannot convert from byte to char
//

char ch = (char) b;
// 65
// ch= A 65 --> A
System.out.println("ch="+ ch);
// A
}

// double -> float -> long -> int -> char -> short -> byte
// convert char to int

package TypeCastingBasics;

public class typeCasting3 {

public static void main(String[] args) {


// convert char to int
char ch = 'A';
int i = 'A'; // A -65 compiler-has done. automatically-->
Implicit type casting
// 65
// i = 65

System.out.println("i="+ i); // 65 but not 'A'

// convert int val to boolean ---not valid

-----------------------
// convert int val to boolean ---not valid

package TypeCastingBasics;

public class typeCasting3 {

public static void main(String[] args) {


// convert int val to boolean ---not valid
// 10 --> true / false -->not possible
// 10 --> 10.0 -possible
// 4.57 --> 4 -possible

int i1 =10;
// boolean b1 = i1;
// 10
// true/ false only we cannnot store any other values 10, 3.45f

boolean b1 = (boolean) i1;// Cannot cast from int to boolean

// HW convert int to double value 5--> 5.0d


// HW convert double val to int 5.4 ---> 5
-------------------------------------------------------
FAQ :What is type casting?
FAQ Diff b/w Widening and narrowing?

*************************

Method/Function:
-----------------
Method :
---------

is Collection of stmts (or) block of stmts


can be used to perform specific task

ex: add -- need 2 numbers 10 + 20 =30

public static void main(String args[])


{ // args- is array name
// main is- method
stmt1;
stm2;
stmt3;
}

2 Types of methods:
-----------------
1. user defined method

2. Predefined method

1. user defined method:


------------------
if any method, which is defined by programmer is called user defined method.

Syntax for writing method:


-------------------------
Method with no arguments:
--------------------------

Accessspecifier nonAcessSpecifier returnType Methodname()// Method heading


{ // Beginning of method

stmt-1; // Method body


stmt-2;
stmt-3;

} // end of method

Access specifier --> public , private,protected, default


non AcessSpecifier --> static
Return type --> void, int , float, char, boolean,String, array..etc
nothing

public static void main(String args [])


{

}
write add method and return type = void?
// Method name : add
public static void add()// Add method with out args
{

stmt-1;
stmt-2;

Write substraction() and return type = void?

// sub
// Method name : substraction
public static void substraction()// Method heading
{

//write method name mul, return type: int

public static int multiplication()//


{

//write method name - Division, return type: float

public static float Division()


{

Method call:
------------
if we want to execute stmts inside the Method- we must call method by it's
name.

MethodName();

call add ()--> add();

call substraction() --> substraction();

HW ex: call Multiplication() -->

HW ex: call Division() -->

note: if we dont call method- it does not execute method statements


if we simply define/ write method, if we dont call method, it wont execute that
method statements
---------------------------------
ex: Addition:
-------------
Without calling method:
------------------
package MethodBasics;

public class MethodBasics1


{
// method is defined in side the class
// define add() and call below stmts
// System.out.println("performing addition - stmt-1");
// System.out.println("stmt-2");
public static void add()
{
System.out.println("inside add- method -stmt-1");
System.out.println("stmt-2");
}

public static void main(String[] args)


{
System.out.println("in main method");
// Call add method
// syntax: methodname();

System.out.println("after add -");

o/p:
in main method
after add -

Calling add():
------------------

-------------
package MethodBasics;

public class MethodBasics1


{
// method is defined in side the class
// define add() and call below stmts
// System.out.println("performing addition - stmt-1");
// System.out.println("stmt-2");
public static void add()
{
System.out.println("inside add- method -stmt-1");
System.out.println("stmt-2");
}

public static void main(String[] args)


{
System.out.println("in main method");
// Call add method
// syntax: methodname();
add();

System.out.println("after add -");

o/p:
in main method
inside add- method -stmt-1
stmt-2
after add -

Define M1() , M2() and Calling M1() , M2():


-----------------------------------------

package MethodBasics;

public class MethodBasics2


{

// Define Method name M1 () and return type = void and call below stmts
public static void M1()
{
System.out.println("inside M1- method .stmt-1");
System.out.println("stmt-2");
}

//Define Method - M2 and return type = void and call below stmts
public static void M2()
{
System.out.println("inside M2-method.stmt-3");
System.out.println("stmt-4");
}

public static void main(String[] args)


{
// If we want to execute any method stmts, we must call specific method
// with out calling method, we cannot execute method stmts

// call M1
M1();

// Call M2
M2();

o/p:
------
inside M1- method .stmt-1
stmt-2
inside M2-method.stmt-3
stmt-4

-We can define/ write any number of methods inside the class
M1(),M2(), M3()...

ex: Define add () and call it:


--------------------------------
package MethodBasics;

public class AddMethodWithOutArgs3 {

//ex: Define add () and return type -void ,perform addition and call it:

public static void add()


{
int a= 10;
int b =20;

int result = a+b;


// 10 + 20
// 30
//result =30
System.out.println("result="+ result);
// result= 30

public static void main(String[] args)


{
System.out.println("inside main()");

// Calling add()
add();

System.out.println("after add ()");


}

--------------------
ex3: Define Substraction() and call it?
------------------------------------------
package MethodBasics;

public class SubstractionMethodBasics {

//ex: Define substraction () and return type -void ,perform substraction and
call it:

public static void substraction()


{
int result = 20 -10;
// 10
// result =10
System.out.println("Result fo substrcation ="+ result);
// 10
}

public static void main(String[] args)


{
System.out.println("inside main()");

// call substraction()
substraction();

System.out.println("after sub ()");


}
}

o/p:
inside main()
Result fo substrcation =10
after sub ()

----------------------------------------

HW ex: Define Mult() , Division() and call it from main()


-------------------------------

********************************
28-Jul-2024
********************************
Note:
-----
We can define every method inside class only.
We can define multiple methods inside class

package MethodBasics;

public class AddMethodWithOutArgs3 {

//ex: Define add () and return type -void ,perform addition and call it:

public static void add()


{
int a= 10;
int b =20;

int result = a+b;


// 10 + 20
// 30
//result =30
System.out.println("result="+ result);
// result= 30
}

// Define Substraction() and call it?


public static void substraction()
{
int a =10;
int b=5;
int result = a-b;
// 10 - 5
// 5
// result =5
System.out.println("Result fo substrcation ="+result);
// 5
}

public static void Mul()


{
System.out.println("in mult method ");
}

public static void main(String[] args)


{
System.out.println("inside main()");

// Calling add()
add();

// call substraction()
substraction();

System.out.println("after add ()");

o/p:
inside main()
result=30
Result fo substrcation =5
after add ()

HW Define multiplication method and display o/p

HW Define Division method (get Quotient number - / )and display o/p ?

HW Define Remainder Method (get remainder value - % ) and display o/p?

Method with Input arguments:


--------------------------
Arguments : can be used to pass some i/p's / data to method --
are also called parameters
-
Syntax :
---------------
Method without args:
----------------
-- no args - if we dont pass any variables in side () -

Method with 1 int args:


--------------------

public static void M1(int a) // Method with 1 argument /1 parameter


{

public static void M2(float f)


{

Method with 2 args: 1 int arg , 1 int arg


--------------------
pubic static void M3(int a, int b) // Method with 2 arguments/ param
{
// arguments -- i/p's to method (or) declaring varible

ex: Defning M3 with 2 args i.e 1 float , 1 char arg


M3 (float f , char ch)// M3 with 2 arguments-
{

Method with 3 args:


-------------------
// pass any no of arguments / parameters- and any data type (int, float,double,
char,boolean.. etc)

ex:Define Method -M1 with 1 int arg, 1 float arg, 1 char arg
public static void M1(int a, float f, char ch) // M1 with 3 args
{

Pass 1 arguments / parameter in method heading


pass 2 arguments/ parameter in method heading
pass 3...
......
n no of args in method heading

------------------------------

Call Method with arguments / parameter:


--------------------------------------

M1(int a) // M1 () contains - 1 arg/parameter


{

method Call :--> M1(10); we must pass int value in method call
M1(); --invalid method call

ex2:
M2 (int a , int b ) // 2 args
{

method call --> M2(10, 20);

No of arguments /parameters in method heading = number of values in method call


must be same
if method has 2 args, in method call also, we must also pass 2 values...

M2(10);// invalid as we passed only one value but in method heading 2 args
if 2 args in method heading, we must pass 2 values in method call also.

ex3:
M3 (int a, float f, char ch) // 3 args
{

method Call --> M3(10, 2.45f,'A');

values in method call and arguments in method definition must be same type.

M3 ('A', 10, true ); // --> check valid /invalid-->


// VALUEs must match with data type

M3 ('A', 10, true ); // invalid

M3(10,2.3f, 'B',20);// invalid passing 4 vals , but method heading contai=ns 3


args- so we must pass 3 values only in method call but not 4 values

No of args in method heading and no of values in method call must be equal

ex:
Define Method Input arguments and call Method :
----------------------------------------------

package MethodBasics;
public class CallingM1With1Args {

// Method M2 with 1 int args


public static void M2(int a)
{// 20 val is copied to to 1st arg . so a =20
System.out.println("in M2");//
System.out.println("a= " + a);
// 20
}

public static void main(String[] args) {

// call method M2()


// M2();// error The method M2(int) in the type CallingM1With1Args
is not applicable for the arguments ()
M2(10);

// call method M2 any no of times


M2(20);

}
}

o/p:
in M2
a= 10
in M2
a= 20

***********************************************************************************
*********************

***********************************************************************************
*********************

Method call:
---------------------
M1(2.45f);//Error: invalid we should not pass float value / Decimal no in method
call as we have M1 (int a)
--> The method M2(int) in the type CallingM1With1Args is not applicable for the
arguments (float)

Method with 2 i/p arguments:


-----------------------------

ex:
package MethodBasics;

public class MethodWith2Args {


// Define/ write M1 with 2 args 1 int, 1 int arg
public static void M1(int a, int b)
{// 10 20 a =10 , b=20
System.out.println("M1 With 2 args");
System.out.println("a="+ a);// 10
System.out.println("b="+ b); // 20
}

public static void main(String[] args)


{
System.out.println("in main()");

// Call M1
M1(10,20);

System.out.println("after M1 ()");

o/p:
in main()
M1 With 2 args
a=10
b=20
after M1 ()

ex: Define 'add' method with 2 i/p arguments and call add()?
----------------------------------
package MethodBasics;

public class AddMethodWith2args {


// ex: Define 'add' method with 2 i/p arguments and call add()?
// ----------------------------------
// add() with 2 args
public static void add(int a, int b)
{ /// 10 20 so a =10, b =20
System.out.println("called add()");
int result = a+b;
// 10 + 20
// result = 30

System.out.println("Addition result ="+ result);


// 30

public static void main(String[] args) {

//call add() by passing 2 value


add(10,20);

o/p:
----------------
called add()
Addition result =30

WAP to define substraction and Pass 2 arguments and display result


----------------------
package MethodBasics;

public class SubStrWith2Args {

// / WAP to define substraction and Pass 2 arguments and display result

public static void substraction(int a, int b)


{
// 20 10 so a =20 b= 10

System.out.println("called Substarction()");
int result = a-b;
// 20 -10
// 10
// result = 10

System.out.println("Substraction results="+result);
// 10
}

public static void main(String[] args) {

// Call substraction
// substraction();// error we must pass 2 values

// call method substraction- passing 2 values


substraction(20,10);

o/p:
------
//called Substarction()
//Substraction results=10

HW WAP to define Multiplication and Pass 2 arguments and display result


2*3
HW WAP to define Multiplication and Pass 3 arguments and display result 2*3 *4

HW WAP to define Division and Pass 2 arguments and display result

*****************************************************
// add(3.5f,4);// Error : The method add(int, int) in the type
MethodWith2Args is not applicable for the
//arguments (float, int)
-----------------------------------------------

Method with return types :


-------------------------

syntax:
--------------
returntype M1()
{

return val/var/expre;
}

return type: void, int , float,char....

when we want to get some o/p from the method, then we have to write respective data
type in return type and write return stmt also.
return " ""

ex : if we want to get int o/p from the method, then we have to write int data
type in return type and also write return stmt (return 10;)

ex : if we want to get float o/p from the method, then we have to write float data
type in return type and also write return stmt (return 10.85f;)

// return : is pre-defined k/w in java


// can be used to get the o/p from method
// return some value from method
Syntax:
---------
// return val/var/expression;

// ex : return 10;-->
// ex: return a; -->
// ex3: return a+b; -->

Method return type and Return value must be same .

int M1()
{

return 10;
}

float M1()
{

return 10.45f;
}

char M1()
{

return 'B';
}

String M1()
{
return "Ram";
}

-----------------------------
// Define add() - pass 2 int -args -perform addition and return result ?

package MethodBasics;

public class AddWith2ArgsReturnResult {

// Define add() - pass 2 int -args, return type - void -perform addition and
return result ?
// public static void add(int a, int b)// void method cannot return any value
// int -- return int value
// float - return float
public static int add(int a, int b)
{// 2 3 so a =2, b=3
System.out.println("Called add()");
int result = a +b;
// 2 + 3
// 5
// result = 5
System.out.println("result = "+result);
// result = 5

return result;
// 5;
// return ;
}

public static void main(String[] args) {

// call add by passing 2,3 and store result into var i.e x
add(2,3);
// 5

int x = add(2,3);
// 5
// x= 5

System.out.println("after add. x= " + x);


// 5

o/p:
Called add()
result = 5
Called add()
result = 5
after add. x= 5
-------------
Return val :
-------------
package MethodBasics;

public class AddWith2ArgsReturnResult {

// Define add() - pass 2 int -args -perform addition and return result ?
public static int add(int a, int b)// void method cannot return any value
{
// 10 20 so a= 10 b= 20

System.out.println("Called add()");
int result = a +b;
// 10 + 20
// 30
// result = 30
System.out.println("result = "+ result);
// result = 30

// return result;
// 30
return 25 ;// returns o/p : 25
// dont write return stmt inside void method.
}

public static void main(String[] args) {

// call add
int x = add(10,20);
// x= 25
System.out.println("x= "+ x);// 25

System.out.println("after add ");

o/p:

Called add()
result = 30
x= 70
after add

--------------------
return val; --> return 10;
return var; --> return b;
// 20; --> returns 20 value
return expression;

return a+b; // gives int o/p, return type must be int


// 10 + 20
// 30
// return 30;
// if we are returning float o/p, return type must be float
// char o/p, char

return 2.45f; --> return type must be -float


return "ram"; --> return type must be -String

-------------------
Method ReturnType Float :
---------------------

package MethodBasics;

// Note : if Method return type is float, we must return float val/ float
var
// return type must be written just before the method name
// ex" void, int, float, char, boolean, String also

package MethodBasics;

public class MethodReturnTypeFloat {


// Define add () pass 2 float args and return type float
public static float add(float a , float b)
{ // 2.5f 1.5f so a = 2.5f b= 1.5f
float result = a +b;
// 2.5 + 1.5
// 4.0
//result = 4.0

System.out.println("result="+ result);
// 4.0

return result ;
// return 4.0;
}

public static void main(String[] args) {

// call add () - pass 2.5f and 1.5f


add(2.5f,1.5f);

// 4.0 we are not storing result into any var

// call add () - pass 2.5f and 1.5f and store into int var x
// int x = add(2.5f,1.5f);

// 4.0f error: Type mismatch: cannot convert from float


to int
//
// call add () - pass 2.5f and 1.5f and store into float var x
float x = add(2.5f,1.5f);
// x= 4.0
// display x
System.out.println("x="+ x);

}
}

o/p:

result=4.0
result=4.0
x=4.0

-----------------------------
Method Return Type Char :
-----------------------
package MethodBasics;

public class MethodReturnCharVal {

// Define add() and return type char and return 'A'


public static char add()// add method without args or add with no args
{
// Method with return type char - so method return char val o/p

System.out.println("in side add");

// return the result


return 'A';
// gives o/p : 'A'
}

public static void main(String[] args) {

// call add() and don't store result into var


add();
// 'A'

// call add() and store result into variable i.e ch


char ch = add();
//

// display result
System.out.println("ch ="+ ch);

o/p:
in side add
in side add
ch=A

------------------

public static char add() // Method with return type char - so method return
char val o/p
{
System.out.println("in side add");

return 'A';// gives o/p : 'A'


// Note : return stmt is the last executable stmt inside method
// System.out.println("after return stmt");//Unreachable code
// once we write return stmt, dont write any stmts after return stmt
// System.out.println("after return stmt-1");// Unreachable code
// System.out.println("after return stmt -2");//Unreachable code

/// 1 method must have 1 return stmt


// We cannot write multiple return stmts inside method
// return 'B';// Error :
}
----------------------------------

// return 10,20,30;// in valid


// return ch,res;// in valid

return val/var/expression:

return 10;
int b=20;
return b; return val of variable b
//
return a+b-2; // evaluates expression and result is returned

HW WAP to define method to perform subtsraction and return the o/p and and display
result, perofrm result + 100 in main()

HW WAP to define method to perform division and return the o/p and display result
in main()

HW WAP to define method to get Remainder val and return the o/p and display
result in main()

WAP to define method i.e checkEvenNo and pass argument as int no,
if it is even no, return boolean value i.e true,
else return false value and display the result in main()?

boolean checkEven(int no)


{

}
package MethodBasics;

public class EvenNo {


// WAP to define method i.e checkEvenNo and pass argument as int no,
// if it is even no, return boolean value i.e true,
// else return false value and display the result in main()?
public static boolean checkEvenNo(int num)
{// 3 so num =3
int rem = num%2;
// 3%2 = 1
// rem =1
if(rem == 0)
{// 1 ==0 true, ctrl goes
System.out.println("Given no="+ num + " is even no");
return true;// -> o/p - true, comes out of method and ctrl
goes to method call
}
else
{
System.out.println("Given no="+ num + " is not even no");
return false;// --> o/p false,comes out of method and ctrl goes
to method call
}
}

public static void main(String[] args) {


System.out.println("in side main ()");
// call checkEvenNumber pass -2
checkEvenNo(2);
// true 10 ,20

// call checkebenno () pass -2 and store result into some var result
boolean result = checkEvenNo(2);
// // result = true
// // this method gives o/p/ return o/p boolean value i.e
true

// // return value i.e true will be stored in left side


varible i.e result .So Result var contains true value

// display result
System.out.println("result="+result);
/// true

// call checkebenno () pass -3 and store result into some var result
result = checkEvenNo(3);
// result = false
// this method gives o/p/ return o/p boolean value i.e false
// return value i.e false will be stored in left side varible i.e
result .
// So Result var contains false value
// display the result
System.out.println("result="+result);
// false

// Note : if we dont know what method return value. move the mouse over
// on method call i.e checkOddNumber , dispays return type i.e char
// so left side , we must declare char var only but not int,
float,boolean

// Note 2: Go to method definition, Check return type i.e char


// so left side we must declare char var only but not int,
float,boolean
System.out.println("Method returns char value ="+result);
// 'N'
---------------------

HW WAP to define method to check given no is odd no and return some 'char' o/p
if it is odd no -- return char 'Y'
else 'N'

---------------------------------------
Return type String :
-------------------
HW WAP to define method i.e checkEvenNo and pass argument as int no,
//if it is even no, return "Yes" value
// else return "No" value and display the result in main()?
-------------------------

******************************************************
29-Jul-2023
******************************************************

void : nothing
void method -- > return nothing
no value
if method's return type is void, that method returns nothing i.e it does not
return any value.
void - predefined k/w in java
can be used before method name

when to use: when we dont want to get any o/p from method -- we will go for void
return any

package MethodBasics;

public class VoidMethodBasics {


//define void add() and pass 2 int args
public static void add(int a, int b)
{ //// a= 2 b=3
// void method
// cannot return any value // cannot give o/p
//
int result = a + b;
// 2 + 3;
// result = 5;
// display result
System.out.println("result =" + result);
// 5
// return the result
// return result; //CE: Void methods cannot return any value
// if method return type is void, Dont write return stmt inside void
method
}

public static void main(String[] args) {


// TODO Auto-generated method stub
//call add() pass 2,3
add(2,3);
// does not return any value

// call add() ,pass 2,3 and store result into some var i.e result
// int result = add(2,3);// CE
// void it does not return any value
//error : this method does not return any o/p. so dont store result
into left side var
// if method return type is void, dont store o/p into some var /
dont declare any var left side
// Type mismatch: cannot convert from void to int

// void v = add(2,3);//CE : void is an invalid type for the variable v


// int , float,char

System.out.println("ends");

-----------------------
o/p:
res=5
ends

Types of methods:
---------------------------
1. user defined method
2. Predefined method

1.1. user defined mtehod:


--------------------------
if method is defined by programmer -

add()// user defined method


{

sub() // / user defined method


{

checkEvenNumber( int number)


{

2.Predefined methods:
---------------------
method is already defined by programmer in java library

Math.min(), max(), sqrt();


min()
{

}
---------------
// Math -is predefined class in java
// which has some methods - to perform mathemtical operations
// sqrt , max , min

package PreDefinedMethods;

public class PredefineMethods1 {

public static void main(String[] args) {

// max() ;; max no = class.methodname();


int max = Math.max(2, 5);// returns max no out of given 2 numbers
// 5
// max = 5
System.out.println("result max="+max);
// 5
// Min () - pass 7,20
int min = Math.min(7, 20);//returns min no out of given 2 numbers
// 7
// min =7
//
System.out.println("min no ="+ min);
// 7
// square root of no -pass 4.0 --> 2.0
// 9.0 --> 3.0
/// sqrtNo =
double sqrt = Math.sqrt(4.0);
// 2.0
System.out.println("sqrt ="+ sqrt);
// 2.0
// int no= Math.sqrt(4.0);// error
// sqrt() return double value but left we declared int var..
// so we should declare double var left side
// Tip: how to know method return type : move mouse over on method
name-- left side some data type

// Note : open max() code -Press ctrl + move mouse over method name
i.e max() . + click open Delcaration
// it goes to max() - we can see method body

// Tip2: view all methods in class : ctrl + 0 -- and also we can


search for specific method name i.e min

}
o/p:
result max=5
min no =7
sqrt =2.0

-----------------------
WAP to square given no
squareNo(2); o/p ://4
2*2 = 4

package PreDefinedMethods;

public class SquareNo {

// WAP to square given no


// squareNo(2); o/p ://4
// 2*2 = 4
// return n*n; // this also fine

public static int SquareNo(int n)


{// 2 so n =2
// 2 * 2 =4
int result = n * n;
// 2 * 2
// 4
// result = 4

return result;
// 4 ---> returns 4 value
}

public static void main(String[] args) {

System.out.println("in main");
SquareNo(2);
// 4

int res = SquareNo(2);


// 4
// res = 4
System.out.println("resul="+ res);
// 4
System.out.println("ends ");

or
return n*n; // this also fine
We can write in this way also.
public static int SquareNo(int n)
{// 2 so n =2

return n*n;
// 2*2
// 4 ---> returns 4 value
}

---------------------------

HW square (2.0) // 4.0

HW square (2) // 4.0

****************************************

****************************************

Return type Casting:


---------------------

Write o/p for ?

package PreDefinedMethods;

public class ReturnTypCasting {

public static float add(int a, int b)


{// 2 3 so a =2 , b =3
int res= a+b;
// 2 +3
// 5
// int res= 5
return res;// returning int val
// return 5; returning int value ---> this val will be
typecssted/ converted to float val

// 5 --> 5.0 returns float val but not int val.


}

public static void main(String[] args)


{

// call add() pass 2,3


float f =add(2,3);
// 5.0
// but not 5

// Display the o/p


System.out.println("f="+ f);
// val 5.0

// Note: in println() also, we call call another method

System.out.println(add(2,3));
// 5.0 --> print 5.0
}

----------------------------

-------------------------
package PreDefinedMethods;

public class AddMethodWith2args {

public static int add(int a, int b)


{ // 2 3
// a=2 b =3
float res= a+b;
//
// float res= 5 // Implicit type casting
// conver int --> float
// 5 --> 5.0
System.out.println("res="+res);// 5.0
// return res;// type mismatch: cannot convert from float to int
return (int)res;// Explicit type casting
// (int) 5.0
// 5
// return (int) 5.0;
// 5
}

public static void main(String[] args)


{

int val= add(2,3);


// // 5

System.out.println("val ="+val);
// val =5
}

-----------------------
-------------------------
return 10;
return 3.45f;

if we want to return 2,3,4 values


aray - group og value
return val/var/express;
return arrname;// return multiple values using array name

Method returns array:


-----------------------
By using Method - we can return int val (or) int var
float val (or) float var
char val (or) char var
String val (or) String var

Array var name

return 10,20,30; // invalid


return a,b,c; // invalid

return val/ var/ expression;


return arrayName;
------------------
ex: Method returns array:
----------------------------

package PreDefinedMethods;

public class MethodReturnsIntArray {


//define M1() Method return int array
// method return type int[] - int array
public static int[] M1()
{
int a ;
int [] iarr = new int [3];

iarr [0] = 10;


iarr [1] = 20;
iarr [2] = 30;

// return arrayName;
return iarr; // 10 20 30
// Type mismatch: cannot convert from int[] to int
// [10,20,30]
}

public static void main(String[] args) {


// call M1()
int [] arr = M1();
// [10,20 ,30]
// int[] resArr =rturn array [10,20,30]
// 0 1 2 indexno
// display array values
for(int i=0;i<=arr.length-1;i++)
{
System.out.println(arr[i]);
}

-------------------------
// Ex
// public static float[] display()
// char []
// boolean []
{
// floar farr[]
// char charr[]
// boolean barr

}
}

o/p:

HW WAP to Define method and return float array and display array values in
main()
HW WAP to Define method and return char array and display array values in
main()
HW WAP to Define method and return String array and display array values in
main()

-----------------------------------------
30-Jul-2024
-----------------------------------------

// String :
------------
is collection of charcters
group of characters which must be enclosed in dbl quotes ""
//ex:
"abv123@#$", "123", "abc123"

// Declare String:
-------------------
Declare int var i.e a --> int a;
Declare float var i.e f --> float f
Declare String var i.e s --> String s;

String s;// String is predefined class in java


// usually it is used in the form data type

package StringBasics;

public class DefineString1 {

public static void main(String[] args) {


// Declare String var i.e s
String s;

// Assign / store "Rama" val into var s


s = "rama";

// display var val


System.out.println("s="+ s);
// S= rama

//Can we store int number in String var?

// s = 123;// CE: Type mismatch: cannot convert from int to String


// String value must be enlosed in ""

s= "123"; // Valid ,, we are writing the val into dbl quotes

// even though it looks like number . but it is string value "123"


System.out.println("String val =" + s); // 123

//Note:
// 123 - int no
// "123" -string value
// Decmial nos
// s = 1.45f;// CE: Type mismatch: cannot convert from
float to String

o/p:
s=rama
String val =123

-------------------
//HW Can we store double value into 's' String variable ?

//HW Can we store char value 's' into String variable ?

//HW Can we store boolean value (true/false) into String variable ?


// Note : true -- boolean value
// "true" -- string val

-------------------------
Important String class Methods:
-------------------------------

class String
{

int Length()
{

toUpperCase()
{

package StringBasics;

public class LengthOfString {

public static void main(String[] args) {


// Declare String String var and store "RaMa" val
String s = "RaMa";
// length of string i.e 4
int l = s.length();
// "RaMa".length()

// l= 4

// return / gives length of String i.e how many


character are there in String i.e 4
// value will be stored in left side var i.e l
// so l contains 4 value

// display length
System.out.println("length ="+ l);
// 4

// HW s = "Ram" ; length= 3 ?

// HW s= "Rama rao";// 8 count space char


also

//String toUppercase():
// convert the given String to Upper case
and return String value
// "RaMa" --> RAMA
// RAMA --> RAMA
String sUppercase = s.toUpperCase();
// "RaMa".--> RAMA

// sUppercase = RAMA"
System.out.println("upper case String="+ sUppercase);
//ucaseString == "RAMA"

// "RAMA"
String s2 = "RAMA";
String supperCase2 =s2.toUpperCase();
// "RAMA" --> RAMA
System.out.println("supperCase2="+supperCase2);
// RAMA
// HW s = "sita" convert into upper case?

// HW s = "Rama Rao" convert into upper case?

// s.toLowerCase()
s= "RaMa";
String sLowerCase = s.toLowerCase();
// "RaMa" --> rama
// sLowerCase = rama
System.out.println("sLowerCase="+sLowerCase);

// rama
// "RaMa" // covert the given String to
lower case

// HW s = "Rama Rao" convert into lower case?


//HW s = "Rama SITA" convert into lower case?

}
}

o/p:
length =4
upper case String=RAMA
supperCase2=RAMA
sLowerCase=rama

----------------------------------
charAt(int indexno) :
-----------------------
char charAt(int indexno)
{

is predefined method in java lang.


- can be used to get char val at given index no (0,1,2.. etc)
- return char val at given index no
-return type-char
-----------------

package StringBasics;

public class CharAtBasics {

public static void main(String[] args) {


String s = "RAM"; // length = 3
// 012 indexno

// get char at index no =0 i.e 'R'


char ch0 = s.charAt(0);
// 'R'
// ch0 = 'R'
System.out.println("ch0="+ ch0);
// 'R'

// get char at index no =1 i.e 'A'


char ch1 = s.charAt(1);
// ch1= 'A'
//
System.out.println("ch1="+ ch1);
// A

// HW get char at index no =2 i.e 'M'

// get char at index no =3 ????


// char ch3 =s.charAt(3);// // Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 3

// display char
// System.out.println("ch3="+ ch3);
// get each Char from String and display using 'for' loop
System.out.println("***************");
// for(int i=0;i<=2;i++) // using hard code value
for(int i=0;i<=s.length()-1;i++)
{// 3-1 =2
char ch = s.charAt(i);
// 0 1 2
System.out.println("get each char from String using
for loop="+ ch);
}

System.out.println("after for loop");


// ch=R
// ch=A
// ch=M

-----------------------------------
nested if - possible
nested for --possible
nested method - not possible --

package StringBasics;

public class TestNestedMethod {

// Define M2 inside M1()


public static void M1()
{
public static void M2()//CE: NEsted method isnot possible in java
{

public static void main(String[] args) {


// TODO Auto-generated method stub

2. Duplicate method with same data type args not allowed in java
Same method signature is not allowed .

Method signature --> Method name + parameter list

public static void main(String[] arr) { // always execution start from main ()
which has signature
i.e Main() + String array...

package StringBasics;

public class TestNestedMethod {

public static void main(String [] args) { // error

System.out.println("execution always start from main


and which has String array as arg");
}

// public static int main(String args[])// error


// {
// //
// }

public static int main(int args[])


{
//
return 10;
}

-----------------
indexOf():
---------------------

String s = "RAMA";
// 0123

get index no of given String i.e R


if given string is not there in main String , it returns -1.

package StringBasics;

public class indexOfBasics1 {

public static void main(String[] args) {


String s = "RAMA";
// 0123
//get index no of given String i.e R
int indexOfR = s.indexOf("R");
// 0
// int, char , String
// indexOfR = 0

// can be used to get index no of given String val i.e "R" - 0


System.out.println("indexOfR="+indexOfR);
// indexNoOfR = 0

// index no of given value "A"


int indexOfA = s.indexOf("A");
// // 1
// can be used to get index no of given String val 'A' i.e 1
System.out.println("indexOfA="+indexOfA);
// indexOfA = 1

// 1

//HW get index no of given String val 'M' i.e 2

// -ve if given String val is not there i.e "P" in main string, this
method return -1
int indexOfP = s.indexOf("P");
// -1
// indexOfP = -1
System.out.println("indexOfP="+indexOfP);
// -1

// Note : if duplicates characters are there in String i.e "A ", it always
gets the first matched index no

// indexOfA1 == 1

// 1

LastIndexOf():
---------------
gets last index no of given string

String s = "rama";
// 0123

// s.indexOf("a");
s.lastIndexOf("a");

package StringBasics;

public class LastIndexOf {

public static void main(String[] args) {


String s = "rama";
// 0123
// s.indexOf("a"); //
// returns /gives index no go given String "a" -- first matched index
no = 1

// get last index no of given String 'a'


int lastIndexOFA = s.lastIndexOf("a");
// 3

//

// Last index no of given String value 'a' =3


System.out.println("lastIndexOFA="+lastIndexOFA);

int lastIndexOFP = s.lastIndexOf("P");


// -1
System.out.println("lastIndexOFP="+lastIndexOFP);

---------------------------------------------
// substr() :
------------
can be used to get sub part or some part of string from given index no to till
last index no
String s = "RAMA";
// 0123

String s0 = s.substring(0);
// get string values from index no 0 to all

package StringBasics;

public class SubStringWith1Arg {

public static void main(String[] args) {


// substr() : can be used to get sub part or some part of string
from given index no to till last index no

String s = "RAMA";
// 0123
// substr(int index) : can be used to get sub part or some part of
string from given index no to till last index no
// get string values from index no 0 to all

// get string values from index no 0 to all


String s0 = s.substring(0) ;
// RAMA
// s0 = RAMA
System.out.println("s0="+s0);

// // get string values from index no = 1 to all


String s1 =s.substring(1);
// AMA
// s1= AMA
System.out.println("s1="+ s1);
//
//HW get string values from index no = 2 to all

// HW get string values from index no = 3 to all

// get string values from index no = 4 to all


String s4 = s.substring(4);
// empty value
System.out.println("s4= "+ s4);
// Note : it does not throw error
// it displays empty value subStr4=

------------------
Substring with 1 arg:
-----------------------------

substring(int startIndexNo)
substring(int startIndexNo , int endingindexNo)
------------------------------------------------
String s = "RAMA";
// 0123

// substring(0,n) --> get values from o to n-1 indexno i


// substring(0,1) --> get values from o to 0 indexno i.e R
// substring(0,2) --> get values from o to 1 indexno i.e RA
// substring(0,3) --> get values from o to 2 indexno i.e RAM

package StringBasics;

public class SubStringWith2Args {

public static void main(String[] args) {


String s = "RAMA";
// 0123

//get string values from index no =0 to 0 indexno i.e R


String s01 = s.substring(0, 1); //0,0
// s01= R get string values from index no =0 to n-1
indexno 1-1 =0
System.out.println("s01="+ s01);
//

// get string vals from index no =0 to 1 =


String s02=s.substring(0, 2);// get string vals from index no =0 to
2-1 = 1 -0,1
// RA
//
System.out.println("s02="+ s02);
// RA

//HW get all string values from 0 to 2 o/p: RAM

// HW get all String values from 0 to 3 o/p: RAMA

---------------

package StringBasics;

public class SubStringWith2Args2 {

public static void main(String[] args) {


String s = "RAMA";
// 0123
// subString( beginindex, end index)
// 1,n - values from 1 to n-1 indexno

String s12=s.substring(1, 2);// get string values from indexno =1 to


2-1 i.e 1,1

// A
System.out.println("s12="+s12);

String s13= s.substring(1, 3);//


// get string vals from index no =1 to 3-1 =2 1,2

// AM
System.out.println("s13="+s13);
//
String s11= s.substring(1, 1);// get string vals from indexno =1 to 1-
1 = 0 i.e 1,0 wont display AR
System.out.println("s11-= "+ s11);
// empty val ***

o/p:
----

----------------------
HW Write o/p for below program String s = "RAMA Rao"; display ?

s.substring(2, 3);
s.substring(2, 4);
s.substring(2, 5);

HW Write o/p for below program String s = "RAMA Rao"; display ?

s.substring(3, 6);
s.substring(3, 5);
s.substring(3, 4);

You might also like