Java Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

CORE-JAVA NOTES

• TABLE CONTAINTS
WAKAD
---------------------------------------------------------------------------------
NO. TOPIC PAGE NO.
1. Language Introduction 2
2. Platform dependent & Independent 5
3. Pre-programing 7
4. Introduction to full stack 10
5. Introduction to JDK, JVM & JRE 11
6. Command Prompt 12
7. Structure of Java Program 14
8. Tokens 17
9. Data-Type 21
10. Variables 22
11. Type-Casting 24
12. Operators 27
13. Dynamic Read 39
14. Decision Making Statement 42
15. Looping Statement 55
16. Methods 67
17. Static & Static Members 77

TILOTTAM ZOPE 1
CORE-JAVA NOTES
• LANGUAGE INTRODUCTION
WAKAD
---------------------------------------------------------------------------------
❖ LANGUAGE :-
• Language is a medium which is used to communicate with the other’s and to express
our feeling to other is known as language.

❖ WHAT IS PROGRAMMING LANGUAGE & WHY IT IS USED ?


• Programming language is a set of instruction , which is used to communicate with the
system perform some specific task.

❖ TYPES OF PROGRAMMING LANGUAGE :-


• Programming language are of three type ,
1. Low level language
2. Mid level language
3. High level language

1. Low level language :-


a) Low level language is also known as machine understandable language.
b) Low level language consists of 0’s &1’s which is known as binary language.
c) The binary language is very easier to understand for a machine.but, for a programmer it is very
difficult to instruct the machine in binary form.

2. Mid level language :-


a) Mid level language is also known as assembly level language.
b) It consists of some pre-defined words.
c) By using this pre-defined words we can perform the task.
d) These pre-defined words carry some specific operation.
e) These are classified as numenonics which are also known as instruction set.

ADD – Additiion
SUB – Substraction Assembler System
MUL – multiplication
Translator
binary(0’s & 1’s)

• In assembly level language there is a translator called as assembler which is used to covert
assembly level language to binary language(low level language).

NOTE :-
a) By using mid level language we can perform basic arithmatic operator.
b) We can’t develop huge application like flipkart, amazon, whatsapp, etc.
This is the biggest dis-advantages of mid level language.

TILOTTAM ZOPE 2
CORE-JAVA NOTES
• LANGUAGE INTRODUCTION
WAKAD
---------------------------------------------------------------------------------
3. High level language :-
a) It is very essier to understand to instruct the system using high level language.
b) For example of high level Language,
C, C++, Java, python , .net, C#, php, Js, etc.
Compiler Compiler/ Interpreter
Interpreter

NOTE :-
By using high Level Language we can develop any kind of application.

Source file Interpreter/ System


Compiler

Translator
Source file binary(0’s & 1’s)

c
Source file :-
Source file is a file which consists of instruction which are written using high level language.

Compiler :-
Compiler is a s/w which acts as a translator. Compilers is used to convert high level instruction
to machine understandable Language at once.

Interpreter :-
Interpreter is a s/w which acts as a translator. Interpreter is used to convert high Level instruction
to machine understandable Language line by line.

TILOTTAM ZOPE 3
CORE-JAVA NOTES
• LANGUAGE INTRODUCTION
WAKAD
---------------------------------------------------------------------------------
❖ HISTORY OF JAVA :-
1) Java was developed by James Goslin' in the year 1995 at sun microsystem.
2) James goslin Java started, in the year 1990's & finally the version-1 is released in the year 1995.
3) Java was actually developed for embaded system.
(embaded means the combination of h/w & s/w).
4) It is actually developed for controlling televisions, set of boxes, & other devices.
5) when the java was develop it is very advance language its can be used for internet programming.
6) when it is initially develop they name it as "OAK" which means symbol of strength.
7) They was already other company who has trademark of “OAK technologies”, that is a resion
why later it was named as "Java".
8) Java is a Island in indonesia where espescobean is cultivated.
9) when James goslin having a cup of coffee namely, it was Java.
10) Nowadays, Java is used over 5.5 billion devices. (5500 core)

❖ FEATURES OF JAVA :-
1) Simple & easy 2) Robrust 3) Platform independent
4) high performance 5) Secured 6) multi thraded
7) Portable 8) object oriented 9) Distributed

❖ JAVA IS MAINLY USED TO DEVELOP APPLICATION :-


1) web application
2) stand alone application
(The application which doesn't need any external application support or other third party
support) e.g. calculator.
3) Mobile application
4) Desktop application
5) Bussiness application (e-commerce application)

TILOTTAM ZOPE 4
CORE-JAVA NOTES
• Platform dependent & Independent
WAKAD
---------------------------------------------------------------------------------
❖ PLATFORM DEPENDENT :-
• If a source file is develop on a particular platform, when we give the source file as an input to
the compiler it generates and execute double file based on the system configuration in which
the source code is develop. That execute double file will be executed only on the Specified
configured system this we called it as platform dependent.

Os
Windows Source file Compiler Execute file
32 bit
translator (.exe)

Source file
System (c) (.c)
OS OS
Mac
Windows Windows
OS
64 bit 32 bit

• In the above case, the source file is develop using clanguage which is develop on the windows
32-bit os. when that source file is given as that i/p to the c-compiler it will generate one execute
double file whose configuration is same as the system configuration i.e. windows 32 bit. That
execute double file will be executed only on windows-32-bit system.

❖ PLATFORM INDEPENDENT :-
• If a Source file is develop on a specified platform we can make use of that source file or
application on any other platforms this we called it as platform independent.

Os
Windows Java Byte
Source file
32 bit Compiler code
.class

Source file
System (c) .java
OS OS
Mac
Windows Windows
OS
64 bit 32 bit

JRE JRE JRE

TILOTTAM ZOPE 5
CORE-JAVA NOTES
• Platform dependent & Independent
WAKAD
---------------------------------------------------------------------------------
• when the source file is develop on any configured system, that source file when it is given as i/p
to the Java compiler will generate one inter-midiate code called as bytecode.
• That bytecode will be generated irrespective of system configuration. that byte-code will be
executed on any of the system where JRE is installed that is called java platform independent.

NOTE :-
Java is platform independent but JRE is dependent.

Java-source-file :-
1) The file which is written in high level language using java is known as java -source-file.
2) Java-source file has an extension of “.java”

Java- C :-
1) Java-C stands for Java Compller.
2) when the source file is given as an i/p to the java-compiler it will generate one intermidiate code
(bytecode)

Byte-code :-
1) byte code is neither understable machine by the programer nor by the machine
2) byte code will be in the form of “.class” extension
3) byte-code will be understandable by the interpreter only

Interpreter :-
1) In Java, interpreter is used for converting byte code to machine understable Language
line by line.
2) Interpreter is present inside JRE (Java Runtime Environment).

TILOTTAM ZOPE 6
CORE-JAVA NOTES
• Pre Programing
WAKAD
---------------------------------------------------------------------------------
❖ PRE-PROGRAMMING :-
1) Swaping of two numbers using temparory variable.
a = 10
b = 20 swaping
c= a

a 10
c=a
b 20 a=b
b=c

Output:
a = 20
b = 10

2) Swaping of two numbers without using temparory variable.


Ex. 1 :-
a = 10 a= a+b
b = 20 10 + 20
30

b= a–b
30 – 20
10

a= a–b
30 – 20
10
Ex. 2 :-
a=7 output :-
b = 20 a = 27
condition ➔ a = 20 b=7
b=7 a = 20
a=a+b
7 + 20
27
b=a–b
27 – 20
7
a=a–b
27 – 7
20

TILOTTAM ZOPE 7
CORE-JAVA NOTES
• Pre Programing
WAKAD
---------------------------------------------------------------------------------
• Fibonacci series :-
1) In Fibonacci series the 1st two elements are fixed i.e. 0 & 1
2) 1st element is 0 and 2nd element is 1
3) If you want to find 3rd element then we should find the sum of previous two elements.
0, 1, 1, 2, 3, 5, 8, 13, 21, ........
1st element 2nd element
• Perfect number:-
The sum of factors of given number should be equal to the exact given number then we know as
perfect number.
Ex. 1. 1 2. 1 3. 1
6 2 2 2
3 28 4 128 4
6 7 8
6 is a perfect number 14 16
28 32
28 is a perfect number 64
128 is not a perfect number
• Strong number:-
The sum of factorial of individual digit of a given number should exactly match with given
number then we say the number is strong number.
Ex.
1. 145
1! + 4! + 5!
1 + (1*2*3*4) + (1*2*3*4*5)
1 + 24 + 120
145 It is strong number.

2. 123
1! + 2! + 3!
1 + (1*2) + (1*2*3)
1+2+6
9 It is not Strong number.

3. 40585
4! + 0! + 5! + 8! + 5!
(1*2*3*4) + 0 + (1*2*3*4*5) + (1*2*3*4*5*6*7*8) + (1*2*3*4*5)
24 + 120 + 40320 + 120
40585 It is strong number.

TILOTTAM ZOPE 8
CORE-JAVA NOTES
• Pre Programing
WAKAD
---------------------------------------------------------------------------------
• Xylem number:-
The sum of 1st and last digit of a number should be equal to the sum of mean digit of a number.
Ex.

1 2 3 4

5=5

First + Last == Sum of mean digit

• Spy number:-
The sum of individual digit of a number should be exactly same as the product individual
digits of a number.
Ex.
213
Sum = 2 + 1 + 3 = 6
Product = 2 * 1 * 3 = 6

Sum == Product

• Sunny number:-
If the given number is n we have to find n+1 number.
The n+1 number should be a perfect square root.
Ex.
n=8
n+1
8 +1
9 - squre root of 9 = 3
• Happy number:-
The sum of square of individual digit of a number should be finally equal to 1 is known as happy
number.
Ex.
13
12 + 32
1+9
10
12 + 02 = 1

TILOTTAM ZOPE 9
CORE-JAVA NOTES
• Introduction to full-stack
WAKAD
---------------------------------------------------------------------------------

URL – www.fb.com Web server


request
Username - _____ ------------ uname pass
Password - _____ respond ------------ Abc xyz
welcome Pqr abc
Login ------------ tilo pqr
-----------
Forgot password -----------
Welcome middle ware database

Home error
Java/python/.net/php mysql/ mongodb

Invalid
pass

Display
Front-end :-
1) The layer which the programmer of user is able to see the containt which is called as web pages
is nothing but a front-end.
2) Ex. Welcomepage, homepage and error page
3) The languages which are used to develop frond end – Java, HTML, CSS, JS, Bootstrap.

❖ Middle ware:-
1) It is a part of server side programming which is used to process the main execution of
application.
2) Middle ware is mainly develop using high level programming language.
Ex. Java, python, .net, php.
3) Middle ware is develop completely using programming logic.

❖ Back-end :-
1) Back-end consists of database which is collections of data.
2) All the details and information will be stored in the database.
3) By using middleware logics we can fetch the data or modify the data which is stored in the
database.
Ex. Mysql sql, mongodb

TILOTTAM ZOPE 10
CORE-JAVA NOTES
• JDK , JRE & JVM
WAKAD
---------------------------------------------------------------------------------
IMP INTERVIEW

❖ WHAT IS JDK, JRE & JVM ?


1. JDK :-
• JDK stands for Java Development Kit.
• Which is a complete package used to develop a source code and compile the source code.

Java C
+
JDK (Java Development Kit)
JRE

• JDK consist of JavaC along with JRE.


• JavaC stands for Java Compiler which is used to convert source byte to byte code.

2. JRE:-
• JRE stands for Java Runtime Enviornment.
• JRE used to execute the byte code.

JVM
+
Inbulit
JRE (Java Runtime Enviroment)
Librabry
function

• By using JRE we can’t develop any source file.


• JRE consists of JVM along with some inbuilt library functions.

3. JVM :-
• JVM stands for Java Virtual machine
• jvm is used to convert byte code to machine understandable language with the help of JIT
compliler (Just-in-time) which is also known as Interpreter
JIT-
Compiler
+
JVM (Java Vertiual Machine
Class
loader,etc

Class loadder it is used to load the class from hard disk to primary storage(RAM).

TILOTTAM ZOPE 11
CORE-JAVA NOTES
• Sorce Code & Command Prompt
WAKAD
---------------------------------------------------------------------------------
❖ HOW TO DEVELOP SOURCE CODE :-
• Source code we can develop by using dedicated platform.
• There are two types of platform ,
1. Editors
2. IDE(Integrated development environment).

1. Editors:-
a) Ex. Notepad, Notepad++, Editplus, etc.
b) Editors provide environment to develop the source code
c) Once the source code is develop we need command prompt to compile and run that byte code.
d) Without command prompt we cann’t compile or run the code develop by using editors.

2. IDE:-
a) Ex. Eclips, netbeans, intelJ, Greenfoat, VScode, sublime text etc.
b) By using IDE’s we can develop the source code and directly we can executed.

❖ COMMAND PROMPT :-
• Files structure in windows os :-
1) In windows operating system harddisk is divided into multiple portions,
each portion is known as drive.
2) Each drive has name known as drivename.

• User home directory :-


1) directory means folder.
2) The folder which is created with the name of username in C-drive is known as user home.
directory.
3) the foldername will be always with the name of username.
4) whenever will be open command prompt bydefault it's located at user home directory
ie. C-drive ; c://user/username

• path :-
1) path provides as the complete destination to the kind working folder.
2) with the help of path we can essaily come to know in which directory we are currently located.
3) There are two types of path
a) absolute path
b) Relative path

a) Absolute path :-
➢ the path which provides or starts with drivename is known as absolute path.
➢ Absolute path always depends on the current working directory.
Ex. D://WCCM14/Java

TILOTTAM ZOPE 12
CORE-JAVA NOTES
• Sorce Code & Command Prompt
WAKAD
---------------------------------------------------------------------------------
a) Relative Path :-
➢ The path which doesn't start with drive name is known as relative path.
➢ Relative path depends on current working directory
Ex. C://user/QSW
//WCCM14/java

• MD/MKDIR :-
1) MD or MKDIR stands for make directory, which is used to create new directory inside
carrent working directory.
2) For that command we should pass foldername as an i/p.

• CD :-
1) CD stands for change director which is used to change the directory.
2) for this CD command we should pass foldername to move in forward direction.
Ex. CD foldername
3) For the CD command if a pass ".." we can move in backward direction
Ex. “CD..”

• Java-C :-
1) It is used to invoke java compiler.
2) Java compiler is used to convert source code to byte code for execution.
3) for this JavaC command we should pass filename with extension as i/p.

• Java :-
1) Java is the command which is used to invoke interpriter present in JRE
2) Java command is used to execute the byte code which is generated by the compiler.
3) For this Java command we should pass classname as i/p

• Create, compile & execute :-


a) Create :-
➢ By Using editors we can easily create a source file.
(It should be in “.Java” extension)

b) Compile :-
➢ This command must be used in command prompt.

Syntax :- “JavaC Filename. Java"

Command

eg. JavaC Program1.Java


➢ once Source code is compiled, it will generate a byte code, whose name is same as
the classname. (It will exetension of “ .Class ”)

TILOTTAM ZOPE 13
CORE-JAVA NOTES
• Structure of java program
WAKAD
---------------------------------------------------------------------------------
c) Execute :-
Syntax :- Java class name.
Ex. Java Program1

❖ STRUCTURE OF JAVA PROGRAM :-


• Java instructions should always written, inside class block or class body, class implimentation.
Class cassname
{
Class body
}
• every class, java containts classname with classbody.
• Inside the class we can declare
a) Variables
b) Methods Members of the class
c) Initialigers

a) Variable :-
➢ variable is a small container which is used to store data.

b) Methods :-
➢ Methods is a block of instructions or set of instructions which are used to perform specific task.

a) Initialgers :-
➢ Initialigers are used to execute startup instructions.

NOTE :-
a) If any set of instructions which has to be executed, those instructions has to be
written inside main method
b) Because execution of a java program will always Starts from main method &
ends from main methods.
c) That the main method has to be declared inside class block.
d) we can create a class without main method. It is compile time successful,
but if we tried to executed then we get cannot exente
e) Without main method we con't execute any Java program.
‘d)’ AND ‘e)’ POINT IS IMP. FOR INTERVIEW

Syntax- public static void main(String[] args)


{
// (Instructions).
}

TILOTTAM ZOPE 14
CORE-JAVA NOTES
• Structure of java program
WAKAD
---------------------------------------------------------------------------------
Ex.1. with main method :-
class Demo1
{
public static void main(String[] args)
{
System.out.println("Good morning ");
}
}
Output :-
Good morning

Ex.2. without main method :-


class Demo2
{

}
// compile time successful but not possible to execute without main method

Ex.3.
class demo3
{
Public static void main(String[ Jargs) ·
{
System.out.print ("Hii");
System.out.println(" Ram!")
System.out.println("Good morning")
System.out print ("Bye!")
}
}

TILOTTAM ZOPE 15
CORE-JAVA NOTES
• Print & Println Statement
WAKAD
---------------------------------------------------------------------------------
❖ DIFFERNCE BETWEEN PRINT & PRINTLN STATEMENT :-
• Println :-
1. Println statement is used to print the data along with new line.
2. we can use printin statement without passing any data, it is compile time successful
Ex.1
class Program1
{
public static void main (String[] args)
{
System.out.println("Hello");
}
}

Output :- (i) Hello


(ii) _
Ex.2
class Program2
{
Public static void main(String[] args)
{
System.out.println(“Hello”);
System.out.println (“sheela”);
System.out.println (“How are u”);
}
}

Output :-(i) Hi
(ii) Sheela
(iii) How are u
(iv) _
Ex.3
System out. println();

Output (i) _
(ii)_

NOTE :-
It is compile time succed successhil without any data.

TILOTTAM ZOPE 16
CORE-JAVA NOTES
• Tokens
WAKAD
---------------------------------------------------------------------------------
• Print :-
1. Print statement is used to print the data & cursor remains in same line. no new line will be
Printed
2. without passing any data to the print statement , we can't use it still if we tried to used without
passing data to the print statement we get compile time error
Ex.1
class Program3
{
Public static void main(String[] args)
{
System. out. print ("Hi");
System.out.print ("Laila");
}
}

Output :- (i) HiLaila

Ex.2
System.out.print ();
//Compile time error

❖ TOKENS :-
• Tokens are the smallest individual unit of program language.
• Tokens are classified into 3 types
1. keywords
2. Indentifiers
3. Literals

1. Keywords :-
a) keywords are the predefined words, which are used to perform a task.
b) Every keyword in java is assigned with a specific task.
c) As a programer,we can make use of those Keywords but we aren't Suppose to change
task assigned for keyword.
Ex.class, public, static, void, etc.

NOTE :-
a) There are 50+ keywords in java.
b) All the keywords in java should be represented in lower case.
c) keywords can be eassily understandable by the compiler

TILOTTAM ZOPE 17
CORE-JAVA NOTES
• Tokens
WAKAD
---------------------------------------------------------------------------------
2. Identifiers :-
a) It is the name which is given for the components of Java program is known as Identifiers
b) List of components :-
variables, methods, class, packages, interfaces etc
c) Rules of an Identifier –
1) Identifier should never stort with a number
2) Special characters are not allowed for an identifier except ‘$’ & ‘_’
3) Character space is not allowed between identifier.
4) Keywords can't be use as an identifier

NOTE :-
If a program fails to follow the rules then compiler throws error

Conventions :-
1. Conventions for an Identifiers –
The coding standards or Industrial standard where all the programers will follow throughout
the word is known as conventions

2. Conventions for class name!. =


a) Single word :-
➢ If a class name is represented in single word then always the starting Lateral of the word
should be in upper case & the rest of the laters should be in lower case.

Ex. Addition, Demo, Factorial, etc.

b) Multi-word :-
➢ If a Classname should be represented in multi-word then the starting Later of every word
should be in upper cas & the rest of the laters should be in lower case.

Ex. SquareRoot, PowerOfDigit, atc

NOTE :-
a) Compiler will not valided any conventions.
b) If a programmers fails to follow proper conventions then the compiler is not
going to throw Compile time error.
c) But it is highly recommended for to follow proper conventions

TILOTTAM ZOPE 18
CORE-JAVA NOTES
• Tokens
WAKAD
---------------------------------------------------------------------------------
3. Literals
• The data or values which are used in Java Program is known as Literals
• Literals are classified into 2 types
1. Primitive Laterials
2. Non- Primitive Literals

1. Primitive Literals (single value)


a) All the single value value data is considered as primitive Literals.
b) Primitive Literals are of 3 types,
➢ Number
➢ Character
➢ Booleans Number

➢ Numbers
Numbers are of two types, i.e.Integer & Decimal
Ex. for integer (-10, -3, -8, 0, 1, 2, 3, 4)
Ex. for decimal (-10.897) -4.243, 0. 0.567)

➢ Character
any thing which is enclose with in single queots (‘_’) is known as character.
Ex. ‘A’, ‘a’, ‘b’, ‘7’, ‘#’

➢ Boolean –
Boolean data are of two types, i.e. true or false.

2. Non primitive Literals - (Multi-value)


 The multi-valued data is known as non Primitive Literals.

• string
Any thing which is enclosed with in double queots (“_”) is known as string.
Ex. “sheela”

TILOTTAM ZOPE 19
CORE-JAVA NOTES
• Tokens
WAKAD
---------------------------------------------------------------------------------
 WAJP. To print details of an employee.
class Details1
{
Public static void main(String[] args)
{
System.out.println("sheela ");
System. aut println (34);
system out print in ('9');
System.out.println (False);
System.out println ( “xyz123@gmail.com ”);
System.out.println (25000.34);
}
}

 WAJP. To print your name, stream, degree, %, Roll no, marital status, email, contact number, DOB,
print the details.
class Details2
{
Public static void main(String[] args)
{
System.out.println("Tilottam");
System.out.println("Mechanical");
System.out.println(" B.Tech");
System.out.println (83.55);
System.out.println (21);
System.out.println (false);
System.out.println(“tilottamzope1999@gmail.com”);
System.out.println (7798495977)
System.out.println (DD/MM/YY) (“1/07/1999”);
System.out.println ('T');
}
}

NOTE :-
In java, if you want to create a variable before that we have to specified data types

TILOTTAM ZOPE 20
CORE-JAVA NOTES
• Data-Types
WAKAD
---------------------------------------------------------------------------------
❖ DATA-TYPES :-
• Data type is used to create a variable of specific type.
Data-types

Primitive Non-primitive

Number data decimal data String all the classname


Byte double
Short character
Int boolean
Long
Float

• Data-tpes are of two types,


1. Primitive
2. Non-primitive

1. Primitive data-type :-
a) It is used to create primitive variables

Primitive data-type Size Default value


Byte 1 byte 0
Short 2 byte 0
Int 4 byte 0
Long 8 byte 0L
Float 4 byte 0.0f
Double 8 byte 0.0d
/µ0000
Char 2 byte

Boolean 1byte false

b) Number data-type in incresing order.


Byte<short<int<long<float<double

NOTE :-
All the primitive data-types are the keywords in java

TILOTTAM ZOPE 21
CORE-JAVA NOTES
• Variables
WAKAD
---------------------------------------------------------------------------------
2. Non primitive data-type :-
a) default value is null
b) It is used to create non-primitive variable
Ex.
1) string
2) all the class name in java or considered as non primitive data-type

❖ VARIABLES :-
• Variable, is a small container which is used to store the data
• Variables are of two types,
1. Primitive variables
2. Non-primitive variables

1. Primitive variables :-
• Primitive variables are used to stored primitive data like number, character, boolean

Syntax :- datatype variables name = data/values;

Ex.
Int b= 20;
Char ch= ‘C’
Boolean a= true
Double d= 3.14;

2. Non primitive variables :-


• Non primitive variables are used to stored primitive data like Strings & objects refrence

Syntax :- data-type reference variable = data

Ex.1 for string ,


String name = “Ram”;
Ex.2 for object refrence
Student s = new student();

Non primitive Non primitive object constructor


Data-type or reference variable

NOTE :-
a) Non primitive variables are also known as referance variable, in which refernance
of an object is stored.
b) The default value for non primitive data-type is null.

TILOTTAM ZOPE 22
CORE-JAVA NOTES
• Variables
WAKAD
---------------------------------------------------------------------------------
 WAJP. To store your name, string, degree, age, contact numer, dob, salary, percentage, Print it.
class Details3
{
Public static void main(String[] args)
{
String name = “Laila”;
String string = “Mech”;
String degree = “B.tech”;
Int age =90;
Long contact number = 987654321;
String dob = “05/07/1995”
Double salary = 25000.25
Double percentage =82.5
}
}

❖ SCOPE OF VARIABLE :-
• The Visibility of a variable is known as scope Variable
• based on the visibility the variables are classified into three types :-
1. Local Variable
2. Static Variable
3. Non-static variable (Instance Variable)

1. Local variables:
a) variable is declare inside Method or block then we can say the Variable is local variable.
b) characteristics of Local variable:-
➢ If a local variable is declared but not-initialise then we are not Suppose to use that
local variable.
➢ If a tried to used that Local variable without initializing data then we get compile time error.
Because default values are not applicable for Local variables.
➢ That is the reason why before using Local variable we must initialize data to it.
➢ If a local varible is declared, then that Local variable will be nested inside only that
particular method or a block where it is declared.
➢ we can't access Local variables outside the block or method in which it is declared.

int a = 10;

(declaration) (Initialization)

TILOTTAM ZOPE 23
CORE-JAVA NOTES
• Type Casting
WAKAD
---------------------------------------------------------------------------------
Ex.
class LocalVariable
{
public static void main(String[] args)
{
int a ;
System.out.Println(a); //compile time error
}
}
output: compile time error (A local Variable might not be initialized)

❖ TYPE CASTING :-
Type casting

Primitive Non-primitive

Widening Narrowing Up casting Down casting


(Auto) (explicitly)

• The process of converting one type of data to another type of data is known as type casting.
• Type casting is classified into two types,
1. Primitive typecasting.
2. non-primitive type casting.

1. Primitive type-casting
a) It is a process of converting one type of primitive data into another type of primitive data
b) Primitive type casting is further classified into 2 type
➢ Auto widening
➢ Explicitly narrowing

➢ Auto-widening :-
• The process of converting smaller range data to higher range data is known as widening.
• Widening can be done implicitly or automatically by the compiler hence it is also-known
auto-widening
• in widening process, there is no-change of data- loss i.e.why our compiler will perform
widening automatically.

TILOTTAM ZOPE 24
CORE-JAVA NOTES
• Type Casting
WAKAD
---------------------------------------------------------------------------------
 WAJP. To convert smaller range data to higher range data.
class Widening1
{
public static void main(String[] args)
{
char ch= ‘A’;
int a= ch; // Widening
System.out.println(a);
}
}

NOTE :-
ASCII value :- American standard code Information Interchange

NOTE :-
a) we can convert int to decimal number & decimal to integer number.
b) In the same way, we can convert number to char & char to number.
c) But we can’t covert other type of data boolean & boolean to other type of data.

 WAJP. To conver short to float.


class Widening2
{
public static void main(String[] args)
{
Short s=12;
Float a=s;
System.out.println(s);
System.out.println(a);
}
}
 WAJP. To convert boolean to int & boolean to double.
class Widening3
{
public static void main(String[] args)
{
boolean b=true;
int a=b;
System.out.println(b);
System.out.println(a);
}
}

TILOTTAM ZOPE 25
CORE-JAVA NOTES
• Type Casting
WAKAD
---------------------------------------------------------------------------------
 WAJP. To conver byte to short ,byte to int byte to long byte to double & byte to char.
class Widening4
{
public static void main(String[] args)
{
byte b= ‘38’;
short s= ‘b’;
int a= ‘b’;
long l= ‘b’;
double d= ‘b’;
char ch= (char)b;
System.out.println(s);
System.out.println(a);
System.out.println(l);
System.out.println(d);
System.out.println(ch);
}
}
➢ Explicitly narrowing :-
• The process of converting higher range type datatype to lower range datatype is known
as narrowing.
• Norrowing can't be done implicitly by the compiler because there is chance of data loss
• If we want to perform narrowing explicitly then we have to use type cast operator
Ex.1 case-1
class Narrowing1
{
public static void main(String[] args)
{
double d= 24;
int a= (int)d;
System.out.println(d);
System.out.println(a);
}
}

NOTE :-
In the above progrom there is no data loss.

Ex.2 case-2
class Narrowing2
{
public static void main(string [] args)
{

TILOTTAM ZOPE 26
CORE-JAVA NOTES
• Type Cast Operator & Operators
WAKAD
---------------------------------------------------------------------------------
double d=24.56;
int a=(int)d;
System.out.println(d);
System.out.println(a);
}
}

NOTE :-
In the above program there is data loss.

❖ TYPE CAST OPERATOR :-


• It is unary operator.
• It is used to convert higher range data to Lower range data the explicity by the programmer.
• We use type cast operator for performing widening also.

❖ OPERATORS :-
• Operators are the special symbols which are used to perform specific task on the given data
operators.
Ex. Operators

10 + 20 = 30

Data

• The data which is given as the operator is an input to the operator is known as operand.
• Each & every operator in Java is assigned with a specific task
• Based on the operance the operators are further classified into 3 types,
1. Unary operator
2. Binary operator
3. Ternary operator

1. Unary operator :-
• The operator which accepts one operands as input
Ex. Type cast operators

2. Binary operator :-
• The operator which accept two operands as input
Ex. Logical operators

3. Ternary operator :-
• The operator which accepts three operands as input
Ex. Dynamic read, conditional operator

TILOTTAM ZOPE 27
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
• Operators are classifeid into different types :-
1. Arithmatic operator
2. Assignment operator
3. Logical operator
4. Increment / Decrement operator
5. Bitwise operator
6. Conditional operator
7. Relational operator

1. Arithmatic operator :-
arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act
as basic mathematical operations.

Operator Operation

+ Addition

- Substraction

* multiplication

% Modulus divison

/ Division
Ex.1
class Arithmatic
{
Public static void main(String[] args)
{
int a =10;
int b =20;
int c =a+b;
System.out.println(c);
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(b/a);
System.out.println(a%b);
System.out.println(b%a);
}
}

TILOTTAM ZOPE 28
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
❖ WAJP. To calculate total amount when the principle amount is 1500 & rate of intrest is 4%.
class Interest
{
public static void main(String[] args)
{
double amount =1500.0;
int roi = 4%
double total amount =((roi/100.0*amount)+amount);
System.out.println(total amount);
}
}

2. Assignment operator :-
Java assignment operator is one of the most common operators. It is used to assign the value on
its right to the operand on its left.
Expanded
Operator Example Operation
form
Perform the addition and
+= a+ = b a=a+b
assign the data
Perform the subsract and
-= a- = b a=a-b
assign the data
Perform the multiply and
*= a* = b a=a*b
assign the data
Perform the divide and
/= a/ = b a=a/b
assign the data
Perform the modulus
%= a% = b a=a%b
division and assign the data
Perform the addition and
= a=b a=b
assign the data
Ex. 1
class Assignment1
{
public static void main(String[] args)
{
int a =15;
int b =20;
System.out.println(a);
a + =b;
System.out.println(a);
System.out.println(b);
}
}

TILOTTAM ZOPE 29
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
Ex. 2
class Assignment2
{
public static void main(String[] args)
{
int a =10;
int b =20;
System.out.println(a + = b);
System.out.println(a - = b);
System.out.println(a * = b);
System.out.println(a / = b);
System.out.println(a % = b);
System.out.println(a);
System.out.println(b);
}
}

3. Increment / Decrement operator :-


• Increment operator is represented with (++) &
• Decrement operator is represented with (--)
• Increment operator is used to increase the value by ‘1’
• Decrement operator is used to decrease the value by ‘2’.
• Increment / Decrement operator are classified into two types i.e. pre & post.

Increment / Decrement

Pre post
++a pre-increment a-- post-increment
--a pre-decrement a++ post-decrement

1. Pre-increment or decrement :-
• First data stored in variable will be incremented & then the imcremented data will be
substituted.
• In case of pre incremented or deremented there are three steps has to be followed,
a) Update
b) Substitute
c) Use the substituted value

TILOTTAM ZOPE 30
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
Ex.1
class PreIncrementDecrement1
{
public static void main(String[] args)
{
int a=5;
++a;
++a;
++a;
System.out.println(++a);
System.out.println(a);
}
}

Ex.2
class PreIncrementDecrement2
{
public static void main(String[] args)
{
int a=15;
++a;
System.out.println(++a);
++a;
a- -;
a- -;
System.out.println(a- -);
System.out.println(a);
}
}

Ex.3
class PreIncrementDecrement3
{
public static void main(String[] args)
{
int a=13;
- - a;
- -a;
System.out.println(- -a);
System.out.println(- -a);
System.out.println(a);
}
}

TILOTTAM ZOPE 31
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
Ex.4
class PreIncrementDecrement4
{
public static void main(String[] args)
{
int a=7;
int b=12;
int c=(++a)-(--b)+(- -a)+(- -a)+(- -b);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}

Ex.5
class PreIncrementDecrement5
{
public static void main(String[] args)
{
int a=3;
int b= -5;
int c=12;
int k= (++b)-(- -a)-(++c)+(++b)-(- -c)+(- -a)+(++b);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(k);
}
}

2. Post-increment or decrement :-
• In case of post incremented or deremented there are three steps has to be followed,
a) Substitute
b) Update
c) Use the sustituted values

Ex.1
class PostIncrementDecrement1
{
public static void main(String[] args)
{
int a=10;
a++;

TILOTTAM ZOPE 32
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
a++;
a++;
System.out.println(a++);
System.out.println(a);
}
}

Ex.2
class PostIncrementDecrement2
{
public static void main(String[] args)
{
int l=6;
int m=9;
int n=13;
int k=(++l)-(m- -)+(++n)+(m- -)+(l++)+(n++)+(++m);
System.out.println(k- -);
System.out.println(l);
System.out.println(m);
System.out.println(n);
System.out.println(k);
}
}

Ex.3
class PostIncrementDecrement3
{
public static void main(String[] args)
{
int a=19;
a = ++a;
a = ++a;
a = ++a;
System.out.println(a);
}
}

Ex.4
class PostIncrementDecrement4
{
public static void main(String[] args)
{
int a=5;

TILOTTAM ZOPE 33
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
a = a++;
a = a++;
a = a++;
System.out.println(a);
}
}

Ex.5
class PostIncrementDecrement5
{
public static void main(String[] args)
{
int a=19;
int b=12;
int c=14;
int k=(a--)+(++c)-(b--)+(- -a)-(++b)+(--c)+(b++)-(c--);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(k);
}
}

4. Relational operator :-
• Relational operator are used to compare the data.
• Return type of relational operator is boolean.
• Types of relational operator,
(<) less than
(>) greater than
(<=) less than equals to
(>=) greater than equals to
(==) double equals to
(!=) not equals to

NOTE :-
Relational operator are mainly used as condition in decision making statements &
looping statements

TILOTTAM ZOPE 34
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
Ex.1
class Relational1
{
public static void main(String[] args)
{
int a=5;
int b=10;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a>=b);
System.out.println(a<=b);
System.out.println(a!=b);
System.out.println(a==b);
}
}

Ex.2
class Relational2
{
public static void main(String[] args)
{
int a=13;
int b=7;
System.out.println(a-->++b);
System.out.println(++a<b++);
System.out.println(a++>= --b);
System.out.println(b++>=a--);
System.out.println(b++! = --a);
System.out.println(--a ==b--);
System.out.println(a);
System.out.println(b);
}
}

Ex.3
class Relational3
{
public static void main(String[] args)
{
int a= -4;
int b=6;
System.out.println(b--<++a);
System.out.println(--b>a++);

TILOTTAM ZOPE 35
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
System.out.println(b++<=--a);
System.out.println(a++<=b--);
System.out.println(++b!= --a);
System.out.println(a-- ==b++);
System.out.println(a);
System.out.println(b);
}
}

5. Logical operator :-
Operators Operations
&& And
|| Or
! Not

a) Logical And :-
A B &&
True True True
True False False
False True False
False False False

b) Logical Or :-
A B ||
True True True
True False True
False True True
False False False

c) Logical Not:-
A !
True False
False True

NOTE :-
a) Logical operator is an example of binary operator,which accepts two
operants are i/p
b) The values which we pass as input to the logical operators should return boolean.

TILOTTAM ZOPE 36
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
Ex.1
class Logical1
{
public static void main(String[] args)
{
int a =10;
int b =15;
System.out.println(a<b && b>a);
System.out.println(a>b && b>a);
System.out.println(b>a && a>b);
System.out.println(a>b && b<a);
System.out.println(!(a>b));
}
}

Ex.2
class Logical2
{
public static void main(String[] args)
{
int a =10;
int b =15;
System.out.println(a++<=--b && --b>=++a);
System.out.println(a--<= ++b&& b--<=a++);
System.out.println(!(++a<=--b) && a++<=b--);
System.out.println(a);
System.out.println(b);
}
}

Ex.3
class Logical3
{
public static void main(String[] args)
{
int a =14;
int b =8;
System.out.println(a-- >= ++b &&!(b++>=--a) );
System.out.println(++a<=b++ && --b>=a--);
System.out.println(a-- >=b++ &&!(a++>= --b) );
System.out.println(b++>=++a && --a<=b++);
System.out.println(a);
System.out.println(b); }}

TILOTTAM ZOPE 37
CORE-JAVA NOTES
• Operators
WAKAD
---------------------------------------------------------------------------------
6. Conditional operator :-
• Conditional operator is an example for ternary operator.
• Operator (which accepts 3 operands as input).

Syntax :- operand1 ? operand2 : operand3

Ex. Condition ? statement1 : statement2


• In ternary operator, operand1 should always be a condition.
(which should return true or false )
• If condition returns true then statement1 will get executed.
• If condition returns false then statement2 will get executed.
• The return type of condition operator is depends on statement1& statement2

 WAJP. To find the greatest of two numbers using conditional operator.


class Conditional1
{
public static void main(String[] args)
{
int a =15;
int b =20;
System.out.println(b>a ?b:a);
}
}

Ex.1
class Conditional2
{
public static void main(String[] args)
{
int a =14;
int b =7;
String res=a>b? “a is greater : b is greater” ;
System.out.println(res);
}
}

 WAJP. To find the greatest of three number using conditonal operator.


class Conditional3
{
public static void main(String[] args)
{
int a =5;
int b =9;

TILOTTAM ZOPE 38
CORE-JAVA NOTES
• Dynamic Read
WAKAD
---------------------------------------------------------------------------------
int c =4;
int res= a>b ? (a>c & a:c) : (b>c?b:c);
System.out.println(res);
}
}

V.Imp Interview

❖ DYNAMIC READ :-
• The process of reading data from the user during execution of a program is known as
dynamic Read.
• There are three imp steps as to be follow
• Step. 1-Import Scanner class from Java.util package
Ex. import java.util.Scanner ;
• Step. 2- After importing create object for scanner class.
Ex. Scanner s = new scamer (system.in);
(Referance variable)
• Step. 3- using refernce variable call the respective method of Scanner class to store data.
• Methods :-
byte = nextByte();
short = nextShort();
int = nextInt();
long = nextLong();
float = nextFloat();
double = nextDouble();
string = next(); //used to muted to read single word.
= nextline(); //used to read entire line.
char = next().charAt(0);
boolean = nextBoolean();

Ex.
import java.util.Scanner ;
class Dynamic1
{
public static void main(String[] args
{
Scanner s = new Scanner (system.in);
byte b = s.nextbyte();
System.out.println(“Enter byte value”);
Short sh = s.nextshort();
System.out.println(“Enter short value”);
int i = s.nextint();
System.out.println(“Enter int value”);.

TILOTTAM ZOPE 39
CORE-JAVA NOTES
• Dynamic Read
WAKAD
---------------------------------------------------------------------------------
long l = s.nextlong();
System.out.println(“Enter long value”);
float f = s.nextfloat();
System.out.println(“Enter float value”);
double d = s.nextdouble();
System.out.println(“Enter double value”);
string s1 = s.next();
System.out.println(“Enter a word”);
string s2 = s.nextline();
System.out.println(“Enter a sentence”);
Char ch = s.next().charAt(0);
System.out.println(b);
System.out.println(sh);
System.out.println(i);
System.out.println(f);
System.out.println(d);
System.out.println(s1);
System.out.println(s2);
System.out.println(ch);
}
}

 WAJP.To read the data from the user and calculate the sum of two numbers
import java.util.Scanner ;
class Dynamic2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int a = s.nextint();
int b = s.nextint();
System.out.println(“Enter a”);
int res = a+b ;
System.out.println(res);
}
}

 WAJP To Read Emp Name, EmpID, Emp salary, and print it.
import Java, util Scanner ;
class Dynamic3
{
public static void main (String[] args)
{

TILOTTAM ZOPE 40
CORE-JAVA NOTES
• Dynamic Read
WAKAD
---------------------------------------------------------------------------------
Scanner s = new Scanner (System.in);
System.out.println(Enter ename);
String name = s.next();
int id = s.nextInt();
System.out.println(Enter ID);
System.out.println(Enter salary);
double sal = s. next Double();
System.out.println(name);
System.out.println(ID);
System.out.println(sal);
}
}

➢ CONCAT:-
Ex.1 ssss
class Concat1
{
public static void main(String[] args)
{
System.out.println(10 +20);
System.out.println(3.5 +2);
System.out.println(‘a’+3);
System.out.println(“100” +20);
System.out.println(“Sheela” + “Laila”);
System.out.println(“Kamala” +420);
System.out.println(true + “200”);
System.out.println(“Ram”+ ‘a’);
System.out.println(10+30 + “Hello”+40);
System.out.println(“Hi”+20+30);
System.out.println(10 +“Laila” + (400+20));
}
}
Ex.2
class Concat2
{
public static void main(String[] args)
{
String name= “sheela”;
int id = 420;
double Sal = 12000;
System.out.println(“My name is” + name);
System.out.println(“Id is” + Id);
System.out.println(“Salary is” +sal); }}

TILOTTAM ZOPE 41
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
❖ DECISION MAKING STATEMENTS :-
• Decision making Statement. programer instructions to seep skip Help block of
• They are classified into four type:-
1. If
2. If-else
3. If-else - if ladder
4. Switch

1. If :-
flow chart of if statement
Start

Condition

True
Statement False

End

• Work flow :-
✓ when control reaches if blocks, first condition will be checks, if the condition
is true then if block will get executed.
✓ if Condition is false then if blocks will be skip.

Ex.1
class If
{
public static void main(String[] args)
{
System.out.println(“from main()”);
If (true)
{
System.out.println(“If-block gets executed”);
}
System.out.println(“End main()”);
}
}

TILOTTAM ZOPE 42
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
2. If-else :-
flow chart of if else statement,

Start

False
Condition

True
Statement Statement
if block else block

End

• Work flow :-
✓ If the condition in if block writtens true, if block will get executed and else block will be skip.
✓ In case, If the condition in if block writtens false, if block will be skip and else block
will get executed without any condition.

Ex.1
class IfElse1
{
public static void main(String[] args)
{
System.out.println(“from main()”) ;
If (true)
{
System.out.println(“if block”);
}
Else
{
System.out.println(“else bock”);
}
System.out.println(“end main()”) ;
}
}

TILOTTAM ZOPE 43
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
 WAJP To find whether the given number is odd or even by taking input from the user.
import java.util.Scanner ;
class EvenOrOdd
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter a number”);
int num=s.nextInt();
if(num%2==0)
{
System.out.println(num+ “is even”);
}
Else
{
System.out.println(num+ “is odd”);
}
}
}

 WAJP To age from the user & check whether the user is eligible for voting or not.
import java.util.Scanner ;
class IfElse2
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter your age”);
int age=s.nextInt();
if (age>=18)
{
System.out.println(“Eligible for voting”);
}
Else
{
System.out.println(“Not eligible for voting”);
}
}
}

TILOTTAM ZOPE 44
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
3. If-else-if-ladder :-
flow chart of if else statement,

start

False False
condition-1 condition-2 condition-3 condition-nth

True True True


statement-1 statement-2 statement-3 statement-nth

End

• Work flow :-
✓ The execution in if-else-if-ladder will happen step by step,

✓ Step-1 the control go and check in if block condition, if the condition in if block
is true, then if block get executed & other block will be skip.
✓ In case, if block condition is skip then if block will be skip & control will
Reach immediately else-if block condition.

✓ Step-2 now it will check the condition in else-if block, if the condition in else-if
Block is true then statement-2 will get executed & others block will be skip
✓ In case, if the condition writtens false then the control will reach immidiate
Else-if block.
✓ If non of the if block & else-if block are satisfied at finally else block will get
Executed.

TILOTTAM ZOPE 45
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
 WAJP.To whether the user external number is positive or negative or zero.
import java.util.Scanner ;
class PositiveNegativeZero
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter a number”);
int num=s.nextInt();
if (num>0)
{
System.out.println(num+ “is positive”);
}
Else (if num<0)
{
System.out.println(num+ “is negative”);
}
Else if(num==0)
{
System.out.println(num+ “is zero”);
}
}
}

 WAJP.To read age from the user & based on the below mentioned condition check whether
is match found or not.
a. If age is between (18 to 30)
Your match is found
b. If age is between (31 to 45)
Hard…! But still you can have hope.
c. If age above 46
Better luck ! next life
d. If age below 18
First grow , then come

import java.util.Scanner ;
class Matrimoni
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter your age”);
int age=s.nextInt();

TILOTTAM ZOPE 46
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
if (age>=18 && age<=30)
{
System.out.println(“Your match is found”);
}
Else if (age>=31 && age<=5)
{
System.out.println(“Hard…! But still you can have hope”);
}
Else if (age>=46)
{
System.out.println(“Better luck ! next life”);
}
Else if (age<18)
{
System.out.println(“First grow , then come”);
}
}
}

 WAJP.To read marks from the user & display whether the student is first class or distinction or pass
or fail based on the below given condition
a. If your marks is between (80 to 100)
Distinction
b. If your marks is between (60 to 79)
First class
c. If your marks is between (35 to 59)
Pass
d. If your marks below 35
Fail

import java.util.Scanner ;
class Marks
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter your marks”);
int marks=s.nextInt();
if (marks>=80 && marks<=100)
{
System.out.println(“Distinction ”);
}

TILOTTAM ZOPE 47
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
Else if (marks>=60 && marks<=79)
{
System.out.println(“First class”);
}
Else if (marks>=35 && marks<=59)
{
System.out.println(“pass”);
}
Else if (marks<35)
{
System.out.println(“Fail”);
}
}
}

 WAJP.To read a character from the user & check whether the character is in upper case,lower case
Digit or a special character.
import java.util.Scanner ;
class Character
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter a character”);
Char ch=s.next().charAt(0);
if (ch>= ‘A’ && ch<= ‘Z’)
{
System.out.println(char+ “Uppercase”);
}
Else if (ch>= ‘a’ && ch<= ‘z’)
{
System.out.println(char+ “Lowercase”);
}
Else if (ch>= ‘0’ && ch<= ‘9’)
{
System.out.println(char+ “Digit”);
}
Else
{
System.out.println(char+ “Special character”);
}
}
}

TILOTTAM ZOPE 48
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
4. Switch :-
Flow chart of switch statement,

Start

Condition-1 Statement-1
Break ;

Condition -2 Statement-2
Break ;

Condition-3 Statement-3 End


Break ;

Condition-nth Statement-nth
Break ;

Default Default
Statement

• Work flow :-
✓ For a switch, we can pass value or expression or variables. But for a case block We can pass
only value or expression , if we try to pass variables for a case block then, we get compile time
error.
✓ If we don’t want to achive grouping then make use of break statement for every case block.
✓ Except long, boolean, float, & double we can pass any type of data to a switch.

• Advantages of switch :-
a. The biggest advantages of switch is grouping
b. We can execute multiple casew block at a same time this is known as grouping.
c. We can achieve grouping by removing break keyword

Break :-
a. Brak is a keyword it is a control transfer statement.
b. We can use break statement inside switch block & grouping statement
c. Whenever control riches break statement the execution of the particular block will get trminated.

TILOTTAM ZOPE 49
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
Ex.1.
class Switch1
{
public static void main(String[] args)
{
Switch(2)
{
Case1:
{
System.out.println(“case1”);
}
Case 2:
{
System.out.println(“case2”);
}
Case 3:
{
System.out.println(“case3”);
}
Default :
{
System.out.println(“from default”);
}
}
}
}

Ex.2.
class Switch 2
{
public static void main(String[] args)
{
int a=3
Switch(a)
{
Case1:
{
System.out.println(“case1”);
}
Break ;
Case 2:
{

TILOTTAM ZOPE 50
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
System.out.println(“case2”);
}
Break ;
Case 3:
{
System.out.println(“case3”);
}
Break ;
Default :
{
System.out.println(“from default”);
}
}
}
}

 WAJP.To read a day from the user & according to that display which sports has to be played based
on the following timetable.
a. Monday – tennis
b. Tuesday – cricket
c. Wednesday – hocky
d. Thursday – cricket
e. Friday – football
f. Saturday – tennis
g. Sunday – holiday

import java.util.Scanner ;
class Character
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter a day”);
String day=s.next();
Switch (day)
{
Case “Saturday” :
Case “Monday” :
{
System.out.println(tennis);
}
Break ;

TILOTTAM ZOPE 51
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
Case “wednesday” :
{
System.out.println(“hoky”);
}
Break ;
Case “Tuesday” :
Case “Thursday” :
{
System.out.println(“cricket”);
}
Break ;
Case “”Friday” :
{
System.out.println(“football”);
}
Break ;
Default :
{
System.out.println(“holiday”);
}
}
}
}

 WAJP.To read a month & year from the user. & display how many days present in that particular
Month.
a. Jan (1) – 31 days
b. Mar (3) – 31 days
c. May (5) – 31 days
d. Jully (7) – 31 days
e. Aug (8) – 31 days
f. Oct (10) – 31 days
g. Dec (12) – 31 days
h. Apr (4) – 30 days
i. Jun (6) – 30 days
j. Sep (9) – 30 days
k. Nov (11) – 30 days
l. Feb (2) – 29 days (leap year) & 28 days not leap year

TILOTTAM ZOPE 52
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
import java.util.Scanner ;
class MonthYear
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter a month”);
int month=s.nextInt();
Switch (month)
{
Case 1:
Case 3:
Case 5:
Case 7:
Case 8:
Case 10:
Case 12:
{
System.out.println(“31 days”);
}
Break ;
Case 4:
Case 6:
Case 9:
Case 11:
{
System.out.println(“30 days”);
}
Break ;
Case 2
{
System.out.println(“enter the year”);
int year=s.nextInt();
if (year%400==0 || year%4==0 && year%100!=0)
{
System.out.println(“29 days”);
}
Else
{
System.out.println(“28 days”);
}
}
Break ;

TILOTTAM ZOPE 53
CORE-JAVA NOTES
• Decision Making Statements
WAKAD
---------------------------------------------------------------------------------
Default :
{
System.out.println(“invalid day”);
}
}
}
}

TILOTTAM ZOPE 54
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
❖ LOOPING STATEMENTS :-
• If any set of instructions which has to be executed repeatedly, then we can make used of
looping statements.
• There are 4 different types of looping statement,
1. While loop
2. Do-while loop
3. For loop
4. For-each/Advance for /Enhance for loop

1. While loop :-
Flowchart of while loop,

Start

Condition

True

Statement False

Exit loop

End
• Work flow :-
✓ Case 1:-
If condition is true,

While(true)
{
//statements;
}

➢ When the control reaches while loop directily it will check the condition If the condition is true,
then the control is transfer inside the while block.
➢ The statement written inside while block will get executed & again control goes to the condition
written inside while block.

TILOTTAM ZOPE 55
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
➢ Still if the condition remains true, The statement will get executed repeatedly.
➢ When the condition becomes false, The control will come outside of the while loop.

✓ Case 2 :-
If the condition is false,

While(false)
{
//statements;
}

End

➢ When the control reaches while loop straight away, it check the condition.
➢ If the condition is false, control eill never transfer inside while block.
➢ The statement written inside while block will never get executed,when the condition is initially
false.

NOTE :-
a. As a programmer we are not suppose to make the condition false using boolean
keyword false .
b. If we tried to do that we get compile time error state in that unreachable statement
c. For a looping statement initialization, condition & updation is mandatory/compulsory.
If we tried to skip either of one then it goes to the infinite loop.

Ex.1.
class WhileLoop1
{
public static void main(String[] args)
{
System.out.println(“from main()”);
int a=1;
int b=5; //initialization
while(a<b) //condition
{
System.out.println(“hello world…!”);
a++; //updation
}
System.out.println(“end of main()”);
}
}

TILOTTAM ZOPE 56
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
Ex.2.
class WhileLoop2
{
public static void main(String[] args)
{
System.out.println(“from main()”);
int a=1;
int b=5; //initialization
while(a<=5) //condition
{
System.out.println(a);
a++; //updation
}
}
}

Ex.3.
class WhileLoop3
{
public static void main(String[] args)
{
System.out.println(“from main()”);
int a=1;
int b=5; //initialization
while(a<=b) //condition
{
if(a%2==0)
{
System.out.println(a);
}
a++; //updation
}
}
}

TILOTTAM ZOPE 57
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
Ex.4.
class WhileLoop4
{
public static void main(String[] args)
{
System.out.println(“from main()”);
int a=1;
int b=5; //initialization
int count=0;
while(a<=b) //condition
{
If(a%2==1)
{
Count ++
}
a++; //updation
}
System.out.println(count);
}
}

 WAJP.To print the number from the user enter the range.
import java.util.Scanner ;
class WhileLoop5
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the starting number”);
int strat=s.nextInt();
System.out.println(“Enter the ending number”);
int end=s.nextInt();
while(start<=end)
{
System.out.println(start);
start ++
}
}
}

TILOTTAM ZOPE 58
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
 WAJP.To read a starting number & ending number from the user & print the number which are
divisible by 3 & 5.
import java.util.Scanner ;
class WhileLoop6
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the starting number”);
int strat=s.nextInt();
System.out.println(“Enter the ending number”);
int end=s.nextInt();
while(start<=end)
{
If(start%3==0 && start%5==0)
{
System.out.println(starting);
}
start ++
}
}
}

TILOTTAM ZOPE 59
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
2. Do-while loop :-
Flowchart of Do-while loop,

Start

Do-while

Statement

True

Condtion

False

Exit Do-while loop

End

• Work flow :-
✓ Case 1 :-
If the condition is true,
Do
{
// statements;
}
While condition is true;

➢ When the control reaches Do-block, it will enter inside Do-block & execute the statement
Then, it will check the condition written inside while.
➢ If the condition remains true, control will enter inside Do-block & execute the statement
Writte inside Do-block.
➢ After executing, control checks the condition written inside while.
➢ This will be in a loop until & unless the condition becomes false,
➢ Once the condition becomes false then, control will come out of the Do-block.

TILOTTAM ZOPE 60
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
✓ Case 2 :-
If condition is false,
Do
{
//statements;
}
While condition is false;

➢ When control reaches Do-block the statement writtens inside Do-block will be executed.
➢ After executing the control will transfer to while & it checks the condition.
➢ If the condition is false, the control will just come out of the Do-while loop.

❖ WHAT IS DIFFERNCE BETWEEN WHILE & DO WHILE LOOP?


No. While Do-while
1. First the condition will be check & First the loop block will get executed
then the loop block will get & then it checks for the condition.
executed.
2. The minimum literation of while The minimum literation of Do-while
loop is zero. loop is one.
3. Ex. Ex.
int a=1; int a=1;
int b=5; int b=5;
int literation=0; int literation=0;
while(a>=b) do
{ {
literation ++ ; literation ++ ;
} }
System.out.println(literation); //0 While(a>=b);
System.out.println(literation); //1

 WAJP.To print number from 1 to 5 using do-while loop.


class DoWhile1
{
public static void main(String[] args)
{
int a=1;
int b=5;
do
{ }
System.out.println(a); }
a++
}
While(a<=b)

TILOTTAM ZOPE 61
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
3. For loop :-
Flowchart of for loop,

Start

Initialize

Condition

True

Statement False

Update

Exit for loop

End

• Work flow :-
➢ When control reaches for block, imidiatley it will jump into initialization path, once the data got
Initialized then control will go & check for the condition.
➢ If the condition is true, the statement written inside loop block will get executed & imidiatley the
control goes to updation path.
➢ Once the data is updated imidiatley it checks for the condtion.
➢ If condition is true, the statement written inside loop block will get executed.
➢ This will be in a loop until& unless the condition becones false.

VIMP

NOTE :-
a. In for loop, we can skip initialization, condition & updationall the three
statements ae optional.
b. If we skip the condition, by default it is consider as true

TILOTTAM ZOPE 62
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
 WAJP.To print numbers from 1 to 5 using for loop.
class ForLoop1
{
public static void main(String[] args)
{
for(int=1;i<=5;i++)
{
System.out.println(i);
}
}
}

 WAJP.To read a starting number & ending number from the user & count the number whuch are
divisible by 7.
import java.util.Scanner ;
class ForLoop2
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the starting number”);
int strat=s.nextInt();
System.out.println(“Enter the ending number”);
int end=s.nextInt();
int count=0;
for(int i=start; i<=end; i++)
{
If(i%7==0)
{
count++;
}
}
System.out.println(count);
}
}

 WAJP.To read range from the user & print the count of odd number present in between the range
import java.util.Scanner ;
class ForLoop3
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);

TILOTTAM ZOPE 63
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
System.out.println(“Enter the starting number”);
int strat=s.nextInt();
System.out.println(“Enter the ending number”);
int end=s.nextInt();
int count=0;
for(int i=start; i<=end; i++)
{
if(i%2==1)
{
count++;
}
}
System.out.println(count);
}
}

 WAJP.To find factorial of a given number.


class ForLoop4
{
public static void main(String[] args)
{
int num=5
int fact=1
for(int i=start; i<=end; i++)
{
fact=fact*i;
}
System.out.println(fact);
}
}

 WAJP.To read number from the user & count the digits present in that number
import java.util.Scanner ;
class ForLoop5
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the number”);
int num=s.nextInt();
int count=0;
for(int i=start; i!=0; i/10)
{

TILOTTAM ZOPE 64
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
count++;
}
System.out.println(“The number of digits are”+count);
}
}

 WAJP.To read number from the user & calculate the sum of digit of a number.
import java.util.Scanner ;
class ForLoop6
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the number”);
int num=s.nextInt();
int sum=0;
for(int i=num; i!=0; i/10)
{
int rem=i%10
sum=sum+rem;
}
System.out.println(“The sum of digits is”+sum);
}
}

 WAJP.To read number from the user & find factors of a given number.
import java.util.Scanner ;
class ForLoop7
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the number”);
int num=s.nextInt();
int sum=0;
for(int i=1; i<=num; i++)
{
if(num%i==0)
{
System.out.println(i);
}
}
}/}

TILOTTAM ZOPE 65
CORE-JAVA NOTES
• Looping Statements
WAKAD
---------------------------------------------------------------------------------
 WAJP.To read number from the user & check whether the number is prime or not.
import java.util.Scanner ;
class ForLoop8
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the number”);
int num=s.nextInt();
int count=0;
for(int i=1; i<=num; i++)
{
if(num%i==0)
{
count++;
}
}
if (count<=2)
{
System.out.println(num+ “is a prime number”);
}
else
{
System.out.println(num+ “is not aprime number”);
}
}
}

TILOTTAM ZOPE 66
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
❖ METHODS :-
• It is a set of instructions or block of instructions which of are used to perform specific task.

Syntax :-
[Access Modifire] [modifire] Returntupe MethodName ([formal Arguments])

Ex.
method body/ {
body/ //statement ;
implimentation }

❖ TERMINOLOGIES :-
• Method Name + formal Arguments = Method Signature
• Acress modifire + modifire + Returntype + Method Signature = method dicleration
• Method dicleration + method implementation. = Method defination

Acress Modifire :-
• Access modifires are used to change the accesibility of a member.
• There are four types of access modifier,
a. public
b. privect
c. protected
d. default

Modifire :-
• The modifire are used to change the characteristics of a member.
• Ex. Static, non-static, final, abstract, volatile and syncronized, etc.

Returntype defination :-
• The method after execution will return some data back to the caller.
• In order to return data from a method we need to specify what tupe of data has to be returned.
• We can specify the data type by macking use of returntype
• There are three types of Returntype :-
a. We can return primitive data from the method.
b. We can return non-primitive data from the method.
c. If we don't want to return anything then make the Return type of void.

Methodname :-
• The name given to the method known as method name.

TILOTTAM ZOPE 67
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
❖ CONVENSIONS FOR A METHODNAME :-
• Single-word :-
If method name has to be in single word, Then represent all the laters in lower case.
Ex. main(), add(), remove(), factorial() etc.

• Multi-word :-
If methodname is multiword then we can represent the starting word in lower case and
next word starting latter should be in upper case It is also called as camel case convensions.
Ex. primeNumber(), sumOfNumbers(), etc.

• Method call statements :-


Method call statement is used to call method explicitly.

Syntax :- methodName ([ Actual Arguments]) ;

NOTE :-
a. A method will get executed only when it is called
b. We can call method using method call statement.

Ex.1.
class Method1
{
public static void main(String[] args)
{
System.out.println(“From main()”);
m1(); //method call statement
System.out.println(“End of main()”);
}
public static void m1()
{
System.out.println(“from m1()”); Block will be remove
} JRE after execution
}
SOPln(“From main()”);

m1(); SOPln(“from m1()”);

SOPln(“End of main()”);

Control back to
The JRE
main() m1()

TILOTTAM ZOPE 68
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
❖ METHOD CALL FLOW :-
• Whenever java program is compiled & executed during execution of pregram our JRE
will call only main method for execution.
• When JRE calls main method for execution it provide the control of main method,
• Now main method start executing , whenever control reaches method called statement
the execution of caller or calling method will be pause & the control is immediately
transfer to the called method.
• Once the execution of called method is done, then control is immediately transer back
to the caller.
• Now, caller method contine its execution.

❖ CALLING METHOD VS CALLED METHOD :-


• Calling method :-
The method which is calling another method called as calling or caller method.
• Called method :-
The method being called by some other method is known as called method.

NOTE :-
a. For a method declaration access modifiers, modifiers & formal arguments are
optional.
b. If we don't specified access modifier then by default It is consider as default, if we
don't specified modifier then by default it is considered as non-static.
c. If we don't specified formal argument then it becomes no argument method.

Ex.2.
class Method2
{
public static void main(String[] args)
{
System.out.println(“From main()”);
test();
System.out.println(“End of main()”);
}
public static void test()
{
System.out.println(“From test()”);
m1();
}
public static void m1()
{
System.out.println(“From m1()”);
}
}

TILOTTAM ZOPE 69
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
JRE

SOPln(“From main()”);

test(); SOPln(“From test()”); SOPln(“From m1()”);

SOPln(“End of main()”); m1();

main() test() m1()


❖ MAIN METHOD :-
• Purpose of Main method :-
a. Execution starts from main method.
b. controll the flow of execution.
c. Execution ends from main method.

❖ TYPES OF METHODS :-
• There are two types of methods :-
1. No argument method
2. Parameterised method.

1. No arguments method :-
a. A method which doesn't containt any formal arguments is known as No argument method.
Ex.
public static void main(String[] args)
{

2. Parameterised method :-
a. The method which accepts formal arguments is known as parameterised method.
b. parameterised methods are used to accept the data from method called statement.

Formal arguments :-
• The variables which are declared inside method declaration statements is known formal
arguments.

Actual arguments :-
• The data which are passed in method called Statement is known as actual argument.

Rules to called parameterised method :-


• The number of formal arguments and actual arguments should match.

TILOTTAM ZOPE 70
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
• The type of formal & actual arguments Should match. If not our compiler tries to perform type
promotion. If type promotion is not possible then we get compile time error.

Ex.3.
class Method3
{
public static void main(String[] args)
{
add(10,20);
add(40,50);
add( ‘a’, ‘b’); // type promotion is possible
// add(2.45,5.78); //compile time error
}
public static void add()
{
int c=a+b;
System.out.println(c);
}
}

❖ RETURN STATEMENT :-
• The method after execution will return a data back to the caller with the help of return keyword.

Return :-
• Return is keyword & it is control transfer statement.
• when the control reaches return keyword immediately, the control will be transfered to caller
along with data.

Ex.4.
class Method4
{
public static void main(String[] args)
{
int res=add(10,20);
System.out.println(res);
}
public static int add(int a, int b)
{
int c=a+b;
return c ;
}
}

TILOTTAM ZOPE 71
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
int res=add(10,20); int c=a+b;

SOPln(res); return c ;

main() add(int a, int b)


Ex.5.
class Method5
{
public static void main(String[] args)
{
System.out.println(“From main()”);
ram();
System.out.println(“End of main()”);
}
public static void ram()
{
System.out.println(“From ram…Hi sheela”);
int res=sheela(1000);
System.out.println(res); //500
}
public static int sheela(int money)
{
System.out.println(“Hello ram”);
System.out.println(“sheela starts executing…!”);
return 500;
}
}

TILOTTAM ZOPE 72
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
 ACTIVITY 1 :-
1. create a method which accept int argument & return nothing.
class Method1
{
public static void main(String[]args)
{
m1(10);
}
public static void m1(int a)
{
System.out.println(a);
}
}

2. create a method which accept int float argument & return nothing.
class Method2
{
public static void main(String[]args)
{
m1(10, 2.34f);
}
public static void m1(int a, floatb)
{
System.out.println(a);
System.out.println(b);
}
}

3. create a method that should accept 2 int values & returns nothing & print that sum of two
numbers.
class Method3
{
public static void main(String[]args)
{
int a=20;
int b=50;
c=a+b;
}
public static void m1(int a, intb)
{
System.out.println(c);
}
}

TILOTTAM ZOPE 73
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
4. create a method Boolean, float, double & returns nothing.
class Method4
{
public static void main(String[]args)
{
m1(true, 10.5f, 22.78);
}
public static void m1(Boolean a, float b, double c)
{
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}

5. create a method which accepts int, int, float, double & returns nothing.
class Method5
{
public static void main(String[]args)
{
m1(22, 10, 22.78f, 10.000);
}
public static void m1(int a, int b, float c, double d)
{
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}

6. create a method that should accept a data or number from the user & print the multiplication
table of that number take input from the user.
import java.util.Scanner
class Method6
{
public static void main(String[]args)
{
Scanner s=new Scanner (System.in);
System.out.println("Enter a number");
int sum=s.nextInt();
test(num);
}

TILOTTAM ZOPE 74
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
public static void test(int a)
{
for (int i=1; i<=10; i++)
{
System.out.println(a+"*" + i '=' + (a*i));
}
}
}

NOTE :-
a. we can access a method from outside of a class. If the method is static then, by using
class name we can access anywhere from the class or outside of the class
b. inside a class we can access static method directly with its name. but outside of a class,
if we want to access we have to use class name.

 ACTIVITY 2 :-
1. create a method which accepts int argument & return square of int.
class Method7
{
public static void main(String[]args)
{
System.out.println("square of number"+M1(4));
}
public static int m1(int num)
{
int res=num*num;
return res;
}
}

2. create a method which accept int & float argument & return boolean.
class Method8
{
public static void main(String[]args)
{
m1(10, 7.34f);. Or boolean res=M1(10,7.34f);
} System.out.println(res);
public static boolean m1(int a, floatb)
{
return false;
}
}

TILOTTAM ZOPE 75
CORE-JAVA NOTES
• Methods
WAKAD
---------------------------------------------------------------------------------
3. create a method which accepts boolean, float, double & return char
class Method9
{
public static void main(String[]args)
{
char res=M1(True, 10,7.34f, 25.54);
System.out.println(res);
}
public static char m1(boolean a, float b, double d)
{
return 'd' ;
}
}

4. create a method which accepts int, int, float, double & return string.
class Method10
{
public static void main(String[]args)
{
String res=M1(10, 20, 7.34f, 25.54);
System.out.println(res);
}
public static String m1(int a, int b, float c, double d)
{
return "Sheela" ;
}
}

TILOTTAM ZOPE 76
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
❖ STATIC & STATIC MEMBERS :-
➢ Static :-
• Static is a keyword & it is a modifier
• If any member of a class is prefixed with static keyword then it is known as static member
of that class.
• static members are also known as class members because it belongs to the class.

NOTE :-
a) static keyword can only be prefixed for members of the class.

➢ Static members of the class :-


1. static variables.
2. static methods.
3. static initializers.

❖ JAVA RUNTIME ENVIRONMENT / MEMORY (JRE) :-


• When a Java program is executed, at that time of execution our JRE will request ram(random
access memory) to provide some block of memory for execution.
• In that block of memory there are further classified into 4 blocks.
1. Method block/area
2. static pool/class static area
3. stack area
4. Heap area
JRE JRE will request to provide
some memory to ram

RAM

Method Area Static pool/ Stack Area Heap Area


Class static area

TILOTTAM ZOPE 77
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
Method area :-
• A block of memory will be created for а method of a class along with its signature / address

Static pool/Class Static Area :-


• For every class didicated block of memory will be created inside static pool with the name of
class name.
• That block of memory which is alocated inside static pool is also known as class static area.
• All the static members of the class will get Loaded inside class static area along with its
signature & address.

Stack and Area :-


• For execution of every method a frame will get created inside stuck area.
• The frames will get created by following the principle called as (Last in 1st out)
• stack area is only used for only execution purpose once the execution of method or block is
done, then the frame will be removed from the stack area.

Heap area :-
• In heap area, a block of memory will get created for instance of a class which is also known as
object.
• All the objects will be created with the help of reference.
• We can access the members stored inside the object by making use of reference / address.
• All the non-static members of a class will get loaded inside object.

1. Static Method :-
• A method which is prefixed with static modifer is known as static method. It is a member of
the class
• characteristics :-
a) For static method block of memory will get created inside method area along with address. ar
reference. and That reference will be stored inside class static area.
b) Hence, we can access static method using class name or using object reference.
c) within the same class we can access a static method by using class name by using directly the
method name.
d) But outside of a class, if we want to access static method, we need to make use of class name.

Ex.1
class Demo1
{
public static void test()
{
System.out.printlin("From test()");
}
public static void main(String[]args)

TILOTTAM ZOPE 78
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
{
test(); // Directly by using method name
Demo d1=new Demo();
d1.test(); // Accessing the static method using object reference
}
}

Ex.2
class Demo2
{
public static void main(String[]args)
{
System.out.printlin("From Demo2class");
// test();. // Compile time error
Demo.test(); // Accessing the test() of Demo class from outside of a class using with the
help of class name
Demo d= new Demo();
d.test();. // We can accessing with the help of object reference also from outside of a class.
}
}

2. Static variable :-
• A variable which is declared inside a class block & prefixed with static modifire is known as
static variable.
• Characteristics :-
a) It is a member of the class.
b) Static variables are assigned with default values hence without initializing static variables we can
access them.
c) static variables are global in nature. hence we can access static variable anywhere from the class
and outside of the class.
d) From a class we can access static variables directly with its name, using class name & using
object reference also.
e) The memory for static variables is alocated inside class static area.

Ex.1
class A
{
static int k=20; or k;
o/p :- (default values) 0,0,0
public static void main(String[]args)
{
System.out.printlin(k); // Accessing directly with its name from the class
System.out.printlin(A.k); // Accessing with the help class name

TILOTTAM ZOPE 79
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
A.a1=newA();
System.out.printlin(A1.k); // using object reference
}
}

Ex.2
class B
{
public static void main(String[]args)
{
System.out.printlin("From class B");
System.out.printlin(A.k);
A.a1=new A();
System.out.printlin(a1.k);
}
}

Ex.3
class StaticMethod1
{
public static void main(String[]args)
{
System.out.printlin("Hello world...!");
}
}

TILOTTAM ZOPE 80
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
Ex.4
class StaticMethod2
{
public static void main(String[]args)
{
System.out.printlin("From main() StaticMethod2 class");
test();
System.out.printlin("End of main()");
}
public static void test()
{
System.out.printlin("From test() StaticMethod2 c");
}
}

Ex.5
class StaticMethod3
{
static int a;
static int b;
public static void main(String[]args)
{
System.out.printlin(a);
System.out.printlin(b);
a=20

TILOTTAM ZOPE 81
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
m1();
}
public static void m1()
{
System.out.printlin(a);
}

Ex.6
class A1
{
static int k;
public static void main(String[]args)
{
System.out.printlin("From main() class A1");
test();
System.out.printlin("End of main()");
}
public static void test()
{
System.out.printlin(B1.l);
}
}

TILOTTAM ZOPE 82
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------

Ex.7
class B1
{
static int l;
public static void main(String[]args)
{
System.out.printlin("From main() class B1");
System.out.printlin(l);
}
}

TILOTTAM ZOPE 83
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
NOTE :-
a) when a local variable & static variable names are same then always first preference
will be given to local variable first.
b) We can differentiate local variable & static variable with the help of class name

Ex.
class C
{
static int i; // static variable
public static void main(String[]args)
{
int i=10; // local variable
System.out.printlin(i); //10
System.out.printlin(c.i);. //0
}
}
3. Static Initializers :-
• static Initializers are of two types,
1. Single Line initializers
2. Multi Line initializers

1. Single Line initializers :-

Syntax :- static datatype variableName = Data;

Ex: static int a = 30;

2. Multi-Line initializers :

Syntax :-
static
{
//instructions;
}

• Characteristics of static Initializers :-


a) static initializers will get executed implicitely during Loading process of a class
b) A class can have any number of static initializers which gets executed from top to bottom.

• Purpose of static Initializers :-


a) static initializers are instructions. used to execute startup instructions
b) The static initializers will be executed before the execution of main method.

TILOTTAM ZOPE 84
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
❖ CLASS LOADING PROCESS :-
a) During execution, A dedicated block of memory will get created for a class inside static pool
which can access with the help of class name.

b) All the method defination & blocks of that particular class will get Loaded inside method area &
the reference of static members will get Loaded inside class static area or static pool. along with
its signature & address

c) Now, static variables will get Loaded inside class static area & assigned with default values.

d) Then, the static initializers will get executed from top to bottom. once the static initializers
execution is done then can say the class loading process is completed

e) Now, the JRE will call main method for execution and the actual execution of program begins.
Ex.1
class StaticInt1
{
static int a;
static int b=20;
static
{
System.out.println(“From Multi-Line Static Initializers”);
}
public static void main(String[] args)
{
System.out.println(“From main()”);
System.out.println(a);
System.out.println(b);
System.out.println(“End of main()”);
}
}

TILOTTAM ZOPE 85
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------

Ex.2
class StaticInt2
{
static int k=10;
static int l;
static
{
System.out.println(k);
k=30;
l=50;
}
static int c;
static
{
System.out.println(l);
}
public static void main(String[] args)
{
System.out.println(k);
System.out.println(l);
System.out.println(c);
}
static
{
System.out.println(l);
l=20;
}
}

TILOTTAM ZOPE 86
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------

Ex.3.1
class A
{
static
{
System.out.println(“From Multi-Line Static Initializers of class A”);
}
public static void main(String[] args)
{
System.out.println(“From main() of class A”);
System.out.println(B.l);
}
}
Ex.3.2
class B
{
static
{
System.out.println(“From Multi-Line Static Initializers of class B”);
}
static int l=40;
public static void main(String[] args)

TILOTTAM ZOPE 87
CORE-JAVA NOTES
• Static & Static Members
WAKAD
---------------------------------------------------------------------------------
{
System.out.println(“From main() of class B”);
}
}

TILOTTAM ZOPE 88

You might also like