SlideShare a Scribd company logo
Lesson:
Java Variables and Data types
Cracking the Coding Interview in JAVA - Foundation
List of Concepts Involved:
Topic: Variables
Variables
Identifiers
Data types
Sample output program
How does a program work


A computer program/code consists of various components viz. variables, data types, identifiers, keywords, etc
which help us to build a successful program. Let us learn each one of them in detail and then move to our first
program.
A variable is the title of a reserved region allocated in memory. In other words, it may be referred to as the
name of a memory location.

It is a container that holds the value while the Java program is executed.

Each variable should be given a unique name to indicate the storage area.

A variable is assigned with a data type(we will learn about it after this topic).


Syntax for Declaring a Variable:

Type variable_name [= value];

The variable_name is the name of a variable. We can initialize the variable by specifying an equal sign and a
value (initialization i.e. assigning an initial value, is optional). However, the compiler never assigns a default
value to an uninitialized local variable in Java.
int rate = 40;
datatype variable_name
RAM
Reserved Memory for variable
value
40
Here, rate is an int data type variable with the value 40 assigned to it.

In the example above, the variable can only hold integer values, as indicated by the int data type.

Here, we assigned a value to the variable during the declaration process. However, as stated before, it is
optional.

Variables can be declared and assigned separately. Example,

int rate;

rate = 40;
Cracking the Coding Interview in JAVA - Foundation
Topic 3: Identifiers
Changing values of variables



Interestingly, a variable's value can also be changed in the program. Look at the example below :

int rate = 50;

System.out.println(rate); // 50

rate = 60;

System.out.println(rate); // 60

Initially, the value of rate was 50 but it has changed to 60 after the last updation, rate=60.



Naming Conventions for variables in Java

Like us, all java components are identified with their names. There are a few points to remember while naming
the variable. They are as follows -
Variable names should not begin with a number. For example 

int 2var; 

Whitespaces are not permitted in variable names. For example,

int cricket score;
There is a gap/whitespace between cricket and score.

A java keyword (reserved word) cannot be used as a variable name. For example, int float; is an invalid
expression as float is a pre-defined as a keyword(we will learn about them) in java.

As per the latest coding practices, for variable names with more than one word the first word has all
lowercase letters and the first letter of subsequent words are capitalized. For example, cricketScore,
codePracticeProgram etc. This type of format is called camel case
While creating variables, it's preferable to give them meaningful names like- ‘age’, ‘earning’, ‘value’ etc. for
instance, makes much more sense than variable names like a, e, and v.

We use all lowercase letters when creating a one-word variable name. It's preferable(and in practice) to use
physics rather than PHYSICS or pHYSICS.

// 2var is an invalid variable .
// invalid variables.

An identifier is a name given to a package, class, interface, method, or variable. All identifiers must have
different names.


In Java, there are a few points to remember while dealing with identifiers :
Rule 1 − All identifiers should begin with a letter (A to Z or a to z), $ and _ and must be unique.
Rule 2 − After the first character/letter, identifiers can have any combination of characters.
Rule 3 − A keyword cannot be used as an identifier.
Rule 4 − The identifiers are case-sensitive.
Rule 5 – Whitespaces are not permitted.
Examples of legal identifiers: rank, $name, _rate, __2_mark.
Examples of illegal identifiers: 102pqr, -name.
Cracking the Coding Interview in JAVA - Foundation
Topic: Data Types
These variables, identifiers etc. consume memory units. Before proceeding ahead, let us have a look at the
memory unit concept too. Here, we will only focus on the relevant concept of memory.





Basic Memory units:

It refers to the amount of memory or storage used to measure data.

Basic memory units are:


1.Bit

A bit (binary digit 0 or 1) is the smallest unit of data that a computer can process and store.

Symbols 0 and 1 are known as bits.Here, 0 indicates the passive state of signal and 1 indicates the active state
of signal.

At a time, a bit can store only one value i.e 0 or 1. To have a greater range of value, we combine multiple bits.



2.Byte

A byte is a unit of memory/data that is equal to 8 bits.

You may think of a byte as one letter. For example, the letter 'f' is one byte or eight bits.



The bigger units are :



3.Kilobyte

A Kilobyte is a unit of memory data equal to 1024 bytes.



4.Megabyte

A Megabyte is a unit of memory data equal to 1024 kilobytes.



5.Gigabyte

A Gigabyte is a unit of memory data equal to 1024 Megabytes.





Lets us now move to the most important concept - data type
Data types specify the different sizes and values that can be stored in the variable. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the reserved memory.
Hence, by assigning different data types to variables, we can store integers, decimals, or characters in these
variables.


There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Strings,Interfaces, and Arrays.
Cracking the Coding Interview in JAVA - Foundation
Primitive data types
A primitive type is predefined by the language and is named by a reserved keyword.


1. Boolean Typ
The Boolean data type can have two values– true or false and hence are typically used in true/false
situations.


For example,

Boolean flag=true;


2. Byte Typ
Values for the byte data type range from -128 to 127 (8-bit signed two's complement integer, you will
know more about it once we move to programs and applications).
A byte type is used in place of an int to save memory when it is certain that the value of a variable will be
between -128 and 127.


For example,

byte range=105;
Java Data Types
Primitive
Integer
short double
float
Char boolean
String
Array
Classes
Etc
byte
int
long
Characters Boolean
Floating-Point Number
Non-Primitive
Cracking the Coding Interview in JAVA - Foundation
3. Short Typ
The short data type can have values ranging from -32768 to 32767 (16-bit signed two's complement
integer).
If the value of a variable is certain to be between -32768 and 32767, short is used in place of other integer
data types (int, long).


For example,

short loss=-50;


4. Int Typ
Values for the int data type range from -231
to 231
-1(32-bit signed two's complement integer, you will know
about it as we move to programs)
In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a
minimum value of 0 and a maximum value of 232
-1.


For example, 

int profit=5000;


5. Long Typ
Values for the long data type range from - 263
to 263
-1 (64-bit signed two's complement integer).
You can use an unsigned 64-bit integer with a minimum value of 0 and a maximum value of 264
-1, if
you're using Java 8 or later.


For example:

long profit=455559990;


6. Double Typ
The double data type is a 64-bit floating-point data type with double precision.
It should never be used for exact values like currency.


For example:

double height=12.5;


7. Float Typ
The float data type is a 32-bit single-precision floating-point value. If you're curious, you can learn more
about single-precision and double-precision floating-point.
It should never be used for precise values like money.


For example:

float depth=-32.3f;


8. Char Typ
It's a Unicode (an international character encoding standard that provides a unique number for every
character across languages and scripts) 16-bit character.
The char data type has a minimum value of 'u0000' (0) and a maximum value of 'uffff'.


For example:

char temp=’a’;
Cracking the Coding Interview in JAVA - Foundation
Topic: Java Output/Display Program
How Does this program Work?
The non-primitive data types are a little advanced concepts which we will cover once we have mastered the
primitives and are well versed with the programming principles of Java.





Now that we have learned all the relevant concepts, let us go ahead and write our very first program!
Let us take a look at how the Java ‘HelloWorldJava’ program works.




class HelloWorldJava {

public static void main(String[] args) 

{

System.out.println("Hello World Program in Java");

}}


Output

Hello World Program in Java
// First Program
Compiler:- In computing, a compiler is a computer program that is primarily used to translate source code
from a high-level programming language to a lower-level language to create an executable program.


1. // First Program

Any line that begins with // is a comment. Comments are intended to help users reading the code  

understand the program's intent and functionality. The Java compiler completely disregards it.


2. class HelloWorldJava

Every Java application starts with a class definition. The class in the program is called HelloWorldJava, and  

its definition is as follows:


class HelloWorldJava {

…..

}


We have to keep in mind that every Java application has a class definition, and the class name should  

match the name of the file in Java.


3. Public static void main(String[] args) { ... }

This is the most widely used method. The main method is required in every Java application. All Java 

programs begin execution by calling the main() function.

Let’s understand the key terms:
Cracking the Coding Interview in JAVA - Foundation
Public: This is a visibility/access specifier that defines the component's visibility. The term ‘public’ refers to
a parameter or component that is visible to everyone.
Static: The keyword ‘static’ indicates that the method/ object/ variable that follows this keyword is static
and can be invoked/called without the object or the dot (.) operator. The presence of the static keyword
before the main method indicates that the main method is static
Void: The keyword ‘void’ indicates that the method returns nothing
Main: The keyword ‘main’ denotes the main method, which is the starting point for any Java program. As
mentioned before, a Java program's execution begins with the main method. The curly braces {}
indicate start and end of main.
String[] args: The command line arguments are stored in the string array args.


4. System.out.println (IMPORTANT)

System.out.println() function is used to print messages on the screen. In Java, the system is a class. The 

PrintStream class is represented by the parameters "out" and "println." Println is a method, whereas "out" is an 

object.

The built-in method print() is used to display the string which is passed to it. 

This output string is not followed by a newline, i.e. the next output will start on the same line.The built-in  

method println() is similar to print(), except that println() prints the output in a newline after each call.


Example Code: 


public static void main(String[] args) {

System.out.println("Hello World");

System.out.println(“Welcome to Physics Wallah"); 	

} 



Output:

Hello World 

Welcome to Physics Wallah





Run these examples on your system and check for outputs.



Congratulations! You are officially a programmer now !
Cracking the Coding Interview in JAVA - Foundation
MCQs
1. Compiler assigns a default value to uninitialized local variables in Java Programming. 

This statement is true or false ?
True
False


Ans b) false


Explanation:

In java, it's mandatory to initialize any local variable before using it because compilers don't assign any default
value to variables.


2. Which of the following data type can store the longest decimal number ?

Options:
boolean
double
float
long

Ans : b) double



Explanation:

Out of all given options, only float and double can hold decimal numbers and double is the longest data type
with 64-bit defined by Java to store floating-point values.



3. Which of the following cannot be stored in character data type?

Options
Special symbols
Letter
String
Digit

Ans c) String



Explanation:

String is a collection of characters and is stored in a variable of String data type.
Upcoming Class Teasers
Taking input from the user

More Related Content

Similar to 2.Lesson Plan - Java Variables and Data types.pdf.pdf

OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
İbrahim Kürce
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
ssuser2963071
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
Vijay Perepa
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
sunny khan
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Java (1).ppt seminar topics engineering
Java (1).ppt  seminar topics engineeringJava (1).ppt  seminar topics engineering
Java (1).ppt seminar topics engineering
4MU21CS023
 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
SURBHI SAROHA
 
Java Tokens
Java  TokensJava  Tokens
java handout.doc
java handout.docjava handout.doc
java handout.doc
SOMOSCO1
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
AssignmentjsnsnshshusjdnsnshhzudjdndndjdAssignmentjsnsnshshusjdnsnshhzudjdndndjd
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
tusharjain613841
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
Concepts of core java
Concepts of core javaConcepts of core java
Concepts of core java
AkshitaMangrulkar
 
OOP Poster Presentation
OOP Poster PresentationOOP Poster Presentation
OOP Poster Presentation
Md Mofijul Haque
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
Rakesh Madugula
 
Java platform
Java platformJava platform
Java platform
Visithan
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
sandeshjadhav28
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
Shipra Swati
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
rishi ram khanal
 

Similar to 2.Lesson Plan - Java Variables and Data types.pdf.pdf (20)

OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Java (1).ppt seminar topics engineering
Java (1).ppt  seminar topics engineeringJava (1).ppt  seminar topics engineering
Java (1).ppt seminar topics engineering
 
Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
java handout.doc
java handout.docjava handout.doc
java handout.doc
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
AssignmentjsnsnshshusjdnsnshhzudjdndndjdAssignmentjsnsnshshusjdnsnshhzudjdndndjd
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
 
Concepts of core java
Concepts of core javaConcepts of core java
Concepts of core java
 
OOP Poster Presentation
OOP Poster PresentationOOP Poster Presentation
OOP Poster Presentation
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Java platform
Java platformJava platform
Java platform
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Recently uploaded

Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 

Recently uploaded (20)

Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 

2.Lesson Plan - Java Variables and Data types.pdf.pdf

  • 2. Cracking the Coding Interview in JAVA - Foundation List of Concepts Involved: Topic: Variables Variables Identifiers Data types Sample output program How does a program work A computer program/code consists of various components viz. variables, data types, identifiers, keywords, etc which help us to build a successful program. Let us learn each one of them in detail and then move to our first program. A variable is the title of a reserved region allocated in memory. In other words, it may be referred to as the name of a memory location. It is a container that holds the value while the Java program is executed. Each variable should be given a unique name to indicate the storage area. A variable is assigned with a data type(we will learn about it after this topic). Syntax for Declaring a Variable: Type variable_name [= value]; The variable_name is the name of a variable. We can initialize the variable by specifying an equal sign and a value (initialization i.e. assigning an initial value, is optional). However, the compiler never assigns a default value to an uninitialized local variable in Java. int rate = 40; datatype variable_name RAM Reserved Memory for variable value 40 Here, rate is an int data type variable with the value 40 assigned to it. In the example above, the variable can only hold integer values, as indicated by the int data type. Here, we assigned a value to the variable during the declaration process. However, as stated before, it is optional. Variables can be declared and assigned separately. Example, int rate; rate = 40;
  • 3. Cracking the Coding Interview in JAVA - Foundation Topic 3: Identifiers Changing values of variables Interestingly, a variable's value can also be changed in the program. Look at the example below : int rate = 50; System.out.println(rate); // 50 rate = 60; System.out.println(rate); // 60 Initially, the value of rate was 50 but it has changed to 60 after the last updation, rate=60. Naming Conventions for variables in Java Like us, all java components are identified with their names. There are a few points to remember while naming the variable. They are as follows - Variable names should not begin with a number. For example int 2var; Whitespaces are not permitted in variable names. For example, int cricket score; There is a gap/whitespace between cricket and score. A java keyword (reserved word) cannot be used as a variable name. For example, int float; is an invalid expression as float is a pre-defined as a keyword(we will learn about them) in java. As per the latest coding practices, for variable names with more than one word the first word has all lowercase letters and the first letter of subsequent words are capitalized. For example, cricketScore, codePracticeProgram etc. This type of format is called camel case While creating variables, it's preferable to give them meaningful names like- ‘age’, ‘earning’, ‘value’ etc. for instance, makes much more sense than variable names like a, e, and v. We use all lowercase letters when creating a one-word variable name. It's preferable(and in practice) to use physics rather than PHYSICS or pHYSICS. // 2var is an invalid variable . // invalid variables. An identifier is a name given to a package, class, interface, method, or variable. All identifiers must have different names. In Java, there are a few points to remember while dealing with identifiers : Rule 1 − All identifiers should begin with a letter (A to Z or a to z), $ and _ and must be unique. Rule 2 − After the first character/letter, identifiers can have any combination of characters. Rule 3 − A keyword cannot be used as an identifier. Rule 4 − The identifiers are case-sensitive. Rule 5 – Whitespaces are not permitted. Examples of legal identifiers: rank, $name, _rate, __2_mark. Examples of illegal identifiers: 102pqr, -name.
  • 4. Cracking the Coding Interview in JAVA - Foundation Topic: Data Types These variables, identifiers etc. consume memory units. Before proceeding ahead, let us have a look at the memory unit concept too. Here, we will only focus on the relevant concept of memory. Basic Memory units: It refers to the amount of memory or storage used to measure data. Basic memory units are: 1.Bit A bit (binary digit 0 or 1) is the smallest unit of data that a computer can process and store. Symbols 0 and 1 are known as bits.Here, 0 indicates the passive state of signal and 1 indicates the active state of signal. At a time, a bit can store only one value i.e 0 or 1. To have a greater range of value, we combine multiple bits. 2.Byte A byte is a unit of memory/data that is equal to 8 bits. You may think of a byte as one letter. For example, the letter 'f' is one byte or eight bits. The bigger units are : 3.Kilobyte A Kilobyte is a unit of memory data equal to 1024 bytes. 4.Megabyte A Megabyte is a unit of memory data equal to 1024 kilobytes. 5.Gigabyte A Gigabyte is a unit of memory data equal to 1024 Megabytes. Lets us now move to the most important concept - data type Data types specify the different sizes and values that can be stored in the variable. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Hence, by assigning different data types to variables, we can store integers, decimals, or characters in these variables. There are two types of data types in Java: Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. Non-primitive data types: The non-primitive data types include Classes, Strings,Interfaces, and Arrays.
  • 5. Cracking the Coding Interview in JAVA - Foundation Primitive data types A primitive type is predefined by the language and is named by a reserved keyword. 1. Boolean Typ The Boolean data type can have two values– true or false and hence are typically used in true/false situations. For example, Boolean flag=true; 2. Byte Typ Values for the byte data type range from -128 to 127 (8-bit signed two's complement integer, you will know more about it once we move to programs and applications). A byte type is used in place of an int to save memory when it is certain that the value of a variable will be between -128 and 127. For example, byte range=105; Java Data Types Primitive Integer short double float Char boolean String Array Classes Etc byte int long Characters Boolean Floating-Point Number Non-Primitive
  • 6. Cracking the Coding Interview in JAVA - Foundation 3. Short Typ The short data type can have values ranging from -32768 to 32767 (16-bit signed two's complement integer). If the value of a variable is certain to be between -32768 and 32767, short is used in place of other integer data types (int, long). For example, short loss=-50; 4. Int Typ Values for the int data type range from -231 to 231 -1(32-bit signed two's complement integer, you will know about it as we move to programs) In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232 -1. For example, int profit=5000; 5. Long Typ Values for the long data type range from - 263 to 263 -1 (64-bit signed two's complement integer). You can use an unsigned 64-bit integer with a minimum value of 0 and a maximum value of 264 -1, if you're using Java 8 or later. For example: long profit=455559990; 6. Double Typ The double data type is a 64-bit floating-point data type with double precision. It should never be used for exact values like currency. For example: double height=12.5; 7. Float Typ The float data type is a 32-bit single-precision floating-point value. If you're curious, you can learn more about single-precision and double-precision floating-point. It should never be used for precise values like money. For example: float depth=-32.3f; 8. Char Typ It's a Unicode (an international character encoding standard that provides a unique number for every character across languages and scripts) 16-bit character. The char data type has a minimum value of 'u0000' (0) and a maximum value of 'uffff'. For example: char temp=’a’;
  • 7. Cracking the Coding Interview in JAVA - Foundation Topic: Java Output/Display Program How Does this program Work? The non-primitive data types are a little advanced concepts which we will cover once we have mastered the primitives and are well versed with the programming principles of Java. Now that we have learned all the relevant concepts, let us go ahead and write our very first program! Let us take a look at how the Java ‘HelloWorldJava’ program works. class HelloWorldJava { public static void main(String[] args) { System.out.println("Hello World Program in Java"); }} Output Hello World Program in Java // First Program Compiler:- In computing, a compiler is a computer program that is primarily used to translate source code from a high-level programming language to a lower-level language to create an executable program. 1. // First Program Any line that begins with // is a comment. Comments are intended to help users reading the code understand the program's intent and functionality. The Java compiler completely disregards it. 2. class HelloWorldJava Every Java application starts with a class definition. The class in the program is called HelloWorldJava, and its definition is as follows: class HelloWorldJava { ….. } We have to keep in mind that every Java application has a class definition, and the class name should match the name of the file in Java. 3. Public static void main(String[] args) { ... } This is the most widely used method. The main method is required in every Java application. All Java programs begin execution by calling the main() function. Let’s understand the key terms:
  • 8. Cracking the Coding Interview in JAVA - Foundation Public: This is a visibility/access specifier that defines the component's visibility. The term ‘public’ refers to a parameter or component that is visible to everyone. Static: The keyword ‘static’ indicates that the method/ object/ variable that follows this keyword is static and can be invoked/called without the object or the dot (.) operator. The presence of the static keyword before the main method indicates that the main method is static Void: The keyword ‘void’ indicates that the method returns nothing Main: The keyword ‘main’ denotes the main method, which is the starting point for any Java program. As mentioned before, a Java program's execution begins with the main method. The curly braces {} indicate start and end of main. String[] args: The command line arguments are stored in the string array args. 4. System.out.println (IMPORTANT) System.out.println() function is used to print messages on the screen. In Java, the system is a class. The PrintStream class is represented by the parameters "out" and "println." Println is a method, whereas "out" is an object. The built-in method print() is used to display the string which is passed to it. This output string is not followed by a newline, i.e. the next output will start on the same line.The built-in method println() is similar to print(), except that println() prints the output in a newline after each call. Example Code: public static void main(String[] args) { System.out.println("Hello World"); System.out.println(“Welcome to Physics Wallah"); } Output: Hello World Welcome to Physics Wallah Run these examples on your system and check for outputs. Congratulations! You are officially a programmer now !
  • 9. Cracking the Coding Interview in JAVA - Foundation MCQs 1. Compiler assigns a default value to uninitialized local variables in Java Programming. This statement is true or false ? True False Ans b) false Explanation: In java, it's mandatory to initialize any local variable before using it because compilers don't assign any default value to variables. 2. Which of the following data type can store the longest decimal number ? Options: boolean double float long Ans : b) double Explanation: Out of all given options, only float and double can hold decimal numbers and double is the longest data type with 64-bit defined by Java to store floating-point values. 3. Which of the following cannot be stored in character data type? Options Special symbols Letter String Digit Ans c) String Explanation: String is a collection of characters and is stored in a variable of String data type. Upcoming Class Teasers Taking input from the user