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

Java Identifiers Lesson

The document provides an overview of Java identifiers, variable declaration, and types of variables, including local, instance, static, and parameter variables. It outlines the rules for naming identifiers, the syntax for declaring and initializing variables, and demonstrates examples of variable usage in Java programs. Additionally, it covers input and output in Java using the Scanner class and includes practice exercises for users to apply their knowledge.

Uploaded by

piyoy15878
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Identifiers Lesson

The document provides an overview of Java identifiers, variable declaration, and types of variables, including local, instance, static, and parameter variables. It outlines the rules for naming identifiers, the syntax for declaring and initializing variables, and demonstrates examples of variable usage in Java programs. Additionally, it covers input and output in Java using the Scanner class and includes practice exercises for users to apply their knowledge.

Uploaded by

piyoy15878
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Java Identifiers

What are Identifiers?


• All Java components require names.
• Names used for classes, variables, arrays, and methods are called
identifiers.
• There exists some rules that are followed when naming identifiers in
Java Programming language
• The rules include:
Rules of naming Identifiers in Java
• All identifiers should begin with a letter (A to Z or a to z), currency
character ($) or an underscore (_).
• After the first character, identifiers can have any combination of characters.
• It must be less than 255 characters
• No spacing is allowed
• A key word cannot be used as an identifier.
• The same name cannot be repeated within the same scope
• Most importantly, identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value.
• Examples of illegal identifiers: 123abc, -salary.
Variable declaration
• A variable is a name given to a storage unit in a program
• All variables must be declared before they are used
• General syntax:
Data type variable_name= value
Data type:
• it’s a property of a variable that holds the type of data to be stored in
that variable
• they are used to define a variable before its’ use.
• They include basic datatypes such as int, char, double, float, Boolean.
Cont.
Variable name:
• This the name that you want to give a variable.
• These names are defined by you the programmer. The name you choose
should not be a keyword in Java.
• You must adhere to the rules of naming variables discussed in slide 3
above.
Example.
• If you want to write a program to multiply two numbers you can name your
variables as.
• Num1- to represent first number
• Num2- to represent second number
• Others would just use (a, b) or (x,y) etc.
Initializing variables

To initialize a variable is to assign a value to a variable.


Syntax:
Datatype variable_name=value
e.g
int marks=76
int is the datatype, marks is the variable_name, 76 is the value
This means that marks now stores a value which is 76. so if you output
marks it will give you 76. check example below
Cont.
• There are two ways of declaring variables.
1. You can first declare the variable then initialize it later
Example: check Example 1 below
2. You can declare the variable and initialize it in the same line or at the
same time.
Example; check example 2 below
Example1: declare the initialize later
package java101;

public class Java101 {


public static void main(String[] args) {

double n;
n=10;
System.out.println(n);
}

}
Example 2:Declare and initialize at the same
time
package java101;

public class Java101 {

public static void main(String[] args) {

double n =10;

System.out.println(n);
}

}
Declaring multiple variables
• This refers to declaring more than one variables. You can use two
approaches.
1. Declare all the variables in the same line without initializing and then
initialize later.
2. Declare each variable in its own line and initialize them later
3. Declare each variable in its own line initialize them immediately.
Example:
Think of a program that is supposed to subtract discount from price and
output totalcost
Ideally here we have three variables namely (discount, price, totalcost)
Example using approach 1
package java101;
public class Java101 {
public static void main(String[] args) {

double price, total_cost, discount;


price=1000;
discount=50;
total_cost=price-discount;
System.out.println(total_cost);
}
}
Example using approach 2
package java101;
public class Java101 {
public static void main(String[] args) {

double price;
double total_cost;
double discount;
price=1000;
discount=50;
total_cost=price-discount;
System.out.println(total_cost);
}
}
Example using approach 3
package java101;
public class Java101 {

public static void main(String[] args) {

double price=1000;
double discount=50;
double total_cost=price-discount;
System.out.println(total_cost);
}
}
Types of Variables in Java
• Local Variables
• A variable defined within a block or method or constructor is called a local
variable.
• These variables are created when the block is entered, or the function is
called and destroyed after exiting from the block or when the call returns
from the function.
• The scope of these variables exists only within the block in which the
variable is declared. i.e., we can access these variables only within that
block.
• Initialization of the local variable is mandatory before using it in the
defined scope.
Types of Variables in Java
• Instance Variables
• Instance variables are non-static variables and are declared in a class
outside any method, constructor, or block.
• As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
• Unlike local variables, we may use access specifiers, for instance, variables.
If we do not specify any access specifier, then the default access specifier
will be used.
• Initialization of Instance Variable is not Mandatory. Its default value is 0
• Instance Variable can be accessed only by creating objects.
Types of Variables in Java
• Static Variables
• Static variables are also known as Class variables.
• These variables are declared similarly as instance variables. The difference is that static variables
are declared using the static keyword within a class outside any method constructor or block.
• Unlike instance variables, we can only have one copy of a static variable per class irrespective of
how many objects we create.
• Static variables are created at the start of program execution and destroyed automatically when
execution ends.
• Initialization of Static Variable is not Mandatory. Its default value is 0
• If we access the static variable like the Instance variable (through an object), the interpreter will
show the warning message, which won’t halt the program. The interpreter will replace the object
name with the class name automatically.
• If we access the static variable without the class name, the interpreter will automatically append
the class name.
Parameter Variables
• Variables that are passed to methods, constructors, or blocks. They
represent the values given to the method or constructor when called.
• They are accessible only within the method or constructor in which
they are declared.
• They exist only during the execution of the method or constructor.

public void greet(String name) { // 'name' is a parameter variable


System.out.println("Hello, " + name);
}
Practice Exercise
• Write a Java program that adds two numbers and prints their sum.
• Create a java program that calculates the area of a circle given that
pie is 3.142 and the diameter is 14 cm.
• Write a Java program to find the total marks for a student using the
following formula Total_marks=(cat1+cat2+Assignment)/3
+Exam_marks.
Input and output in Java
• So far we have been dealing with programs that do not require the
user to input anything from the keyboard.
• We have also seen that System.out.println() is used to output a line in
Java.
• So how do we input in java.
• We need to use the Scanner package which is found within the
java.util package.
• So you start by importing the package as follows
• import java.util.Scanner
• Then in the main method you create an instance of this package.
Cont.
• The instance is created as follows:
• Scanner sc=new Scanner (System.in)
• So sc here now represents an instance of Scanner whose role is to accept
inputs as defined by System.in
• This format of importing packages before using them is very common
among powerful programming languages such as python, R, and Java.
• Python is especially prone to importing third party libraries.
• This is so because majority of the powerful libraries are stored as
third party libraries.
Example in a program
package java101; • In this program we have imported the
scanner package.
import java.util.Scanner; • We have also created an instance of it in
the main method. In this case the
instance is sc.
public class Java101 { • We have then assigned that instance to
variable x.
public static void main(String[] args) {
• So whenever x is called the value of sc
Scanner sc= new Scanner(System.in); (what the user inputted is considered)
System.out.println("Enter a number"); • So when the user runs the program, they
double x= sc.nextDouble(); will get a message “Enter a number”
System.out.println(x); • Then they type one number e.g 10 then
the program will output the number the
} user inputted.
}
Example 2
• Think of a program that prompts the user to enter two numbers then
calculates the sum of the two numbers, then outputs the sum of the
two numbers.
• Check next slide for the solution
Example 2: Solution
package java101; System.out.println("Enter second
import java.util.Scanner; Number");
public class Java101 { Scanner sc2=new Scanner
(System.in);
public static void main(String[]
args) { double y= sc2.nextDouble();
Scanner sc= new double sum=(x+y);
Scanner(System.in); System.out.println("The sum of
System.out.println("Enter first the two numbers your entered
Number"); is:"+sum);
double x= sc.nextDouble(); }
}
Example 2: Cont.
• So example 2 is an advancement of example 1 since this one now
deals with two numbers.
• Here we have created two instances of Scanner namely sc for the first
number and Sc2 for the second number.
• We have also assigned these instances of Scanner to variables x and y
to represent the first and second numbers respectively.
• So the number of Scanner instances you create is directly determined
by the number of values you wish to input from the keyboard.
Practice Exercise
• Write a Java program that prompts the user to enter two numbers
then finds the average of the two numbers and outputs the value of
the average.
• Create a java program that calculates the area of a circle. The program
should allow the user to input the values of pie and radius from the
keyboard.
• Write a Java program to find the total marks for a student using the
following formula Total_marks=(cat1+cat2+Assignment)/3
+Exam_marks. The program should allow the user to input the values
from the keyboard.
Practice Exercise Continued
• Write a java program that prompts the user to enter principal
amount, interest rate, and time period then the program computes a
simple interest using the formula:
• Simple interest=(principal*rate*time)/100
• Write a Java program that accepts the principal amount, interest rate,
and time period as inputs from the user. Then computes the
compound interest using the formula:
The End

You might also like