You are on page 1of 40

CHAPTER 4-JAVA LANGUAGE

FUNDAMENTALS
 JAVA TOKENS AND IDENTIFIERS
 KEYWORDS AND LITERALS
 SEPARATORS AND COMMENTS
 JAVA STATEMENTS
 DATA TYPES AND VARIABLES
 SYMBOLIC CONSTANTS
 READING INPUT AND WRITING DATA
 TYPE CASTING
JAVA TOKENS
 TOKENS ARE THE BASIC BULDING BLOCKS OF JAVA LANGUAGE
 A token is the smallest element of a program that is meaningful to the compiler. Tokens can
be classified as follows:
 Keywords
 Identifiers
 Constants or Literals
 Special Symbols-Separators
 Operators
IDENIFIERS
 Identifiers are used as the general terminology for naming of variables, functions ,classes and
packages.
 Identifiers are case sensitive
VALID IDENTIFIERS
MyVariable
MYVARIABLE
myvariable
X
I
x1
i1
_myvariable
$myvariable
sum_of_array
INVALID IDENTIFIERS
My Variable // contains a space

123variable // Begins with a digit

a+c // plus sign is not an alphanumeric character

variable-2 // hyphen is not an alphanumeric character

sum_&_difference // ampersand is not an alphanumeric character


KEYWORDS
 Keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program
 Since keywords are referred names for a compiler, they can’t be used as variable names
because by doing so, we are trying to assign a new meaning to the keyword which is not
allowed.
JAVA LANGUAGE SUPPORTS
FOLLOWING KEYWORDS:
 Data Declaration : Boolean, byte, char, double, float int long
 Modifier and Access : final new private protected public static
 Looping : break continue do for while
 Conditional : case else if switch
 Exception : catch finally throw try
 Structure : abstract class default extends implements interface
 Misc : import package return super
LITERALS (CONSTANTS)
 Constants are also like normal variables. But, the only difference is, their values can not be
modified by the program once they are defined. Constants refer to fixed values. They are also
called as literals.
 Integer Literals
 Floating Point Literals
 Boolean Literals
 Character Literals – ‘a’ ‘*’
 String Literals- “a” “oop”
SEPARATORS
1. Parentheses – ( ) Ex: public void calc ()
2. Brackets – [] E x : int[] my array = new myarray[10];
3. Curly braces – { } public void calc(){….}
4. Semicolons - system.out.println(“..”);
5. Commas – int a,b,c;
6. Periods - . Ex: System.out.println(“..”);
Comments
• Provide internal documentation to explain program
• Provide external documentation with javadoc
• Helps programmers understand code--including
their own
• There
// on one are three
line, or type of comments

/*
between slash star and star slash
you can mash lines down real far, or
*/

/**
* javadoc comments for external documentation
* @return The square root of x
*/
public static double sqrt(double x)
JAVA STATEMENTS
 A statement, made up of tokens, is code that causes something to happen while
the program runs
1. PACKAGE STATEMENT - package animal
2. IMPORT STATEMENT – import java.util.*;
3. LABELLED STATEMENT – outer : while(i<10)
4. EXPRESSION STATEMENT – int a = 3+2
5. SELECTION STATEMENT – if()…else ( )
6. ITERATION STATEMENT – while(i<10)
JAVA STATEMENTS
1. JUMP STATEMENTS – return , break;
2. SYNCHRONIZATION STATEMENT – synchronized(this)
3. EXCEPTION HANDLING STATEMENT - try { } . Catch { }
4. ASSIGNMENT STATEMENT – int a = 10;
DATA TYPES IN JAVA
 There are majorly two types of languages.
 First one is Statically typed language where each variable and expression type is already
known at compile time. Once a variable is declared to be of a certain data type, it cannot hold
values of other data types.
Example: C, C++, Java.
 The other is Dynamically typed languages. These languages can receive different data types
over time.
Example: Ruby, Python
 Java is statically typed and also a strongly typed language because in Java, each type of
data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as
part of the programming language and all constants or variables defined for a given program
must be described with one of the data types.
DATA TYPES IN JAVA
 Java has two categories of data:
 Primitive Data Type: such as boolean, char, int, short, byte, long, float and double
 Non-Primitive Data Type or Object Data type: such as String, Array, etc.
Data Type Default Value Default size

boolean false 1 bit


char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
DATA TYPES IN JAVA
 In java everything is classes and objects except primitive data types
 Primitive data types can be converted to objects using WRAPPER CLASS
 In java the number of bits used in data type is same across all platform
 In C and C++ ,the number of bits used depends on compiler used in that platform
DATA TYPES – UNICODE IN
JAVA
 Unicode is a 16-bit character encoding standard and is capable to represent almost every character of
well-known languages of the world.
 Before Unicode, there were multiple standards to represent character encoding −
 ASCII - for the United States.
 ISO 8859-1 for Western European Language.
 KOI-8 for Russian.
 GB18030 and BIG-5 for Chinese.
 So to support multinational application codes, some character was using single byte, some two. An
even same code may represent a different character in one language and may represent other
characters in another language.
 To overcome above shortcoming, the unicode system was developed where each character is
represented by 2 bytes.
VARIABLES IN JAVA
A variable is an identifier whose value will be changed during execution of the program
Rules for writing variables
 First letter must be an alphabet.
 The length of the variable should not exceed more than 32 characters.
 No special symbols are allowed except underscore.
 No keywords should use as variable names.
VARIABLES IN JAVA
DECLARING VARIABLE :
1. Int a;
2. Boolen flag;
3. Float var1,var2,var3;
INTIALIZING VARIABLE :
<datatype><variable name> = value;
4. Int a = 5;
5. String var = “Hello”;
6. Char c = ‘A’;
7. Float f = 12.345f;
TYPES OR SCOPES OF
VARIABLE IN JAVA
1. Local Variable
2. Instance Variable
3. Class/Static Variable
SCOPE – LOCAL VARIABLE
 A variable defined within a block or method or constructor is called local variable.These
variable are created when the block in 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 variable only within that block.
 Initilisation of Local Variable is Mandatory.
LOCAL VARIABLE - EX
 public class StudentDetails {
 public void StudentAge()
 { // local variable age
 int age = 0;
 age = age + 5;
 System.out.println("Student age is : " + age);
 }
 public static void main(String args[])
 {
 StudentDetails obj = new StudentDetails();
 obj.StudentAge();
 System.out.println (“Student age is “ + age);
 }
 }
SCOPE : INSTANCE VARIABLE
 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.
 Initilisation of Instance Variable is not Mandatory. Its default value is 0
 Instance Variable can be accessed only by creating objects.
INSTANCE VARIABLE - EX
 import java.io.*;

 class Marks {
 int engMarks; // These variables are instance variables.
 int mathsMarks; // These variables are in a class
 int phyMarks; // and are not inside any function
 }
 class MarksDemo {
 public static void main(String args[])
 { // first object
 Marks obj1 = new Marks();
 obj1.engMarks = 50;
 obj1.mathsMarks = 80;
 obj1.phyMarks = 90;

 // displaying marks for first object
 System.out.println("Marks for first object:");
 System.out.println(obj1.engMarks);
 System.out.println(obj1.mathsMarks);
 System.out.println(obj1.phyMarks);

 }
 }
SCOPE : CLASS/STATIC
VARIABLE
 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.
 Initilisation of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like Instance variable (through an object), the compiler will show the
warning message and it won’t halt the program. The compiler will replace the object name to class name
automatically.
 If we access the static variable without the class name, Compiler will automatically append the class name.
 To access static variables, we need not create an object of that class, we can simply access the variable as
 import java.io.*;
 class Emp {
 // static variable salary
 public static double salary;
 public static String name = "Harsh";
 }
 public class EmpDemo {
 public static void main(String args[])
 { // accessing static variable without object
 Emp.salary = 1000;
 System.out.println(Emp.name + "'s average salary:"
 + Emp.salary);
 }
 }
DEFAULT VALUE OF
VARIABLE
 import java.io.*;

 class Emp {

 // static variable salary


 public static double salary;
 public static String name = "Harsh";
 }

 public class EmpDemo {

 public static void main(String args[])


 { int a;
 System.out.println(Emp.name + "'s average salary:"+ Emp.salary);
System.out.println(“The default value of a :” + a);
 }
 }
SYMBOLIC CONSTANTS

To define a variable as a constant,


we just need to add the keyword “final” in front of the variable declaration.
Syntax
final float pi = 3.14f;
READING INPUT FROM
KEYBOARD
1. Stream – Flow of data from one place to another
1. In stream – Receive data (incoming – example incoming data from keyboard)
2. Out Stream – Write data (outgoing – example outgoing data to monitor)

2. System.out: Represents Console


3. System.in: Represents Keyboard
STREAMS
InputStream byte
Class
Host Machine These classes are Java Program
ASCII? tailored to a specific Using Bytes
EBCDIC? host machine.
byte
OutputStream
Class
READING INPUT FROM
KEYBOARD Reader Class
Reader and Writer class
InputStream
Class char

Host Machine
Java Program
ASCII?
Using Unicode
EBCDIC?
Writer Class
char

OutputStream
Class
READING INPUT FROM KEYBOARD
Step 1 – InputStreamReader is = new InputStreamReader( System.in);

Step 2 – BufferedReader br = new BufferedReader( is );

Please note: both of these steps can be combined together as below:


BufferedReader br = new BufferedReader( new InputStreamReader (System.in) );

BufferedReader
adds readLine()
and buffering
InputStreamReader
System.in
(InputStream)

adds read()

an abstract class
READING INPUT FROM
KEYBOARD
 Step 3 – Read the entire line from keyboard using BufferedReader class method
 String str = br.readLine();

 Step 4 – Read the Single character from keyboard using BufferedReader read method:
 Char ch = (char)br.read(); where (char) is the type casting. The ASCII value converted to character
value.
 Step 5 – Read the integer from keyboard
 Int age = Integer.ParseInt(br.readLine());
 Readline returns the string, Parseint converts it into the integer.
USING SCANNER CLASS
 Scanner class is introduced from Java 1.5 onwards

 Scanner class – used to scan strings and primitive data types


USING SCANNER CLASS
 Step 1:
 Import the scanner class from java.util.package
 Import java.util.Scanner;

 Step 2:
 Create and scanner object and attach it to System.in
 Scanner sc = new Scanner(System.in);

 Step 3:
 Each input from the user on the keyboard is collected as tokens. If it is integer you can receive in sc.nextInt(), if it is string
you can received in sc.next() etc
 String str = sc.next();
 Int age = sc.nextInt();
 Float avg = sc.nextFloat();
 Double amount = sc.nextDouble();
 Long bignumber = sc.Long();
 Byte smallnumber = sc.nextByte();
WRITING DATA TO CONSOLE
 System.out.print(‘A’);
 System.out.print(“HELLO”);
 System.out.print(250);
 System.out.print(“The value of a is”+a);
 System.out.println(“The value of a is” +a+ ”and b is” +b);
 System.out.printf(“The value of a and b is %d,%d”, a,b);
TYPE CASTING

Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
•Widening Casting (automatically IMPLICIT) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

•Narrowing Casting (manually EXPLICIT) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
WIDENING OR IMPLCIT
CASTING
 Widening casting is done automatically when passing a smaller size type to a larger size type:

float f=3.14; char ch=‘A’; int i=10;


duble d=f; int i=ch; short s=i;
NARROWING OR EXPLICIT
 Narrowing casting must be done manually by placing the type in parentheses in front of the value:
 Int i=65;

Short s=(short)I;
Char ch=(char)I;
 Double d = 123.456;

Int I = (int)d;
Float f = (float)d;
Long l = (long)f;chr c = char(i);
Short sh = (short)ch;
Byte b = (byte)sh;

You might also like