UNIT-1 Notes

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

UNIT-1

Program Structure in Java

Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens
in Java Programs, Java Statements, Command Line Arguments, User Input to Programs, Escape
Sequences, Comments, Programming Style.

Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of
Variables, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants,
Formatted Output with printf() Method, Static Variables and Methods, Attribute Final,
Introduction to Operators, Precedence and Associativity of Operators, Assignment Operator
( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -) Operators, Ternary
Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical Operators.

Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions,


Ternary Operator?:, Switch Statement, Iteration Statements, while Expression, do–while Loop,
for Loop, Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.

Conpect-1 Introduction to JAVA


a) History of JAVA
 JAVA is a high-level, general-purpose, object-oriented, and secure programming language
developed by James Gosling at Sun Microsystems, Inc. in 1991.
 It is formally known as OAK. In 1995, Sun Microsystems changed the name to JAVA.
 In 2009, Sun Microsystems takeover by ORACLE Corporation.
 Initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was suited for internet programming.
 Currently, Java is used in internet programming, mobile devices, games, e-business
solutions, etc.
 The history of java starts from Green Team.
 Java team members (also known as Green Team).
Why "Oak" name
 Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
 In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
 There are 3 types’ editions in JAVA: Each edition of Java has different capabilities.
 Java Standard Editions (J2SE): It is used to create programs for a desktop computer.
 Java Enterprise Edition (J2EE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
 Java Micro Edition (J2ME): It is used to develop applications for small devices such as
set-top boxes, phone, and appliances.
b) Applications of JAVA

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in
3. Enterprise Applications such as banking applications.
4. Mobile Application
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
c) Java features
 The features of Java are also known as java buzzwords.
 A list of most important features of Java language is given below.
1. Simple 2. Object-Oriented 3. Portable 4. Platform independent

5. Secured 6. Robust 7. Architecture neutral 8. Interpreted

9. High Performance 10. Multithreaded 11. Distributed 12. Dynamic


1. Simple:-
Java is a simple language because its syntax is simple, clean, and easy to understand. Complex
and ambiguous concepts of C++ are either eliminated or re-implemented in Java. For example,
pointer and operator overloading are not used in Java.
2. Object-oriented:-
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation
3. Platform Independent:-
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language. On
compilation Java program is compiled into byte code. This byte code is platform independent
and can be run on any machine, plus this byte code format also provides security. Any machine
with Java Runtime Environment can run Java Programs.

4. Secure:-
Java is a secure programming language because it has no explicit pointer and programs runs in
the virtual machine. Java contains a security manager that defines the access of Java classes.
5. Multi Threading:-
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time, like While typing, grammatical errors are checked
along.
6. Architectural Neutral:-
Compiler generates byte codes, which have nothing to do with particular computer architecture;
hence a Java program is easy to interpret on any machine.
7. Portable:-
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't
require any implementation. For example, the size of primitive data types.

8. High Performance:-
Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.
9. Distributed:-
Java is distributed because it facilitates users to create distributed applications in Java. This
feature of Java makes us able to access files by calling the methods from any machine on the
internet.
10. Dynamic:-
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++. Java supports
dynamic compilation and automatic memory management (garbage collection).
11. Robust:-
Java makes an effort to check error at run time and compile time. It uses a strong memory
management system called garbage collector. Exception handling and garbage collection
features make it strong.
Conpect-2 Writing Simple Java Programs

Documentation Section: Documentation Section consists of a set of comment lines giving


name of the program, author name and other details optionally which programmer like to use
later. These comment lines are optional Ignored by compiler during program execution.
Ex: /* Addition of 2 numbers in java */
Package statement: Package statement placed just after documentation section. In this section
we can declare user defined packages this is optional section and note that there is only one
package statement in java program
Ex: package rc;
Import Statements: A package may contain many predefined classes and interfaces. If we
want to use any of them in our program we need to import that class. It is also optional
Ex: import java.util.Scanner; or import java.util.*;
Interface Statements: A java program may contain interfaces are used to achieve 100%
abstraction in java. It is also optional
Ex: interface Interface1 {
}
Class without main () method: This contains instance variables and methods in it. We can
also write main() method here. (then there is no need of class with main() section)
class Sample {
int s,b; // instance variables
void fun() //methods
{
int x,y; // local variable
}
}
Class with main() method: This section is mandatory because it contain main() method. Every
java program’s execution starts from main function only. Its Essential
Ex: class Mainclass
{
public static void main(String args[])
{
……
}
}
Concept-3 User Input to Programs
 Java Scanner class allows the user to take input from the console. It belongs
to java.util package.
 Java Scanner class is a text scanner that breaks the input into tokens using a delimiter. The
delimiter is whitespace by default.
 It is used to read the input of primitive types like int, double, long, short, float, and byte.
 Importing the class is the first step.
import java.util.Scanner;
 The object of the class Scanner is declared as follows.
Scanner sc= new Scanner (System. in);
Methods of Java Scanner Class
Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.

Example Program: - Illustration of a user's input from keyboard into program


Output:-

Concept-4 Command Line Arguments


 The java command-line argument is an argument i.e. passed at the time of running the java
program.
 The arguments passed from the console can be received in the java program and it can be
used as an input.
 When a Java application is invoked, the runtime system passes the command line arguments
to the application's main method through an array of strings.
 It must be noted that the number of arguments in an array. To ensure this, we can make use
of the length property of the array.
Example Program:- Illustration Concept of the Command Line Arguments

Output:-
 The main() method of every Java program only accepts string arguments. Hence it is not
possible to pass numeric arguments through the command line.
 However, we can later convert string arguments into numeric values.
Example Program:- Illustration Concept of the Numeric Command Line Arguments

Output:-

Concept-5 Data Types in Java

 Data types specify the different sizes and values that can be stored in the variable.
 There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
Arrays, and String.
boolean Data Type
 The Boolean data type is used to store only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
 Boolean data type variable are used in the dealing with logical statements.
 Its default value is false.
Example: boolean one = false
Integers Number
 Integer are whole number that is, they represent number that do not have a fractional part.
 The integer can be declared in four types according to the size of memory allocated.
1. byte 2. short 3. int 4. long
Byte Data Type
 The byte data type is an example of primitive data type.
 It is an 8-bit signed integer. That is 1 byte
 Its value-range lies between -128 to 127.
 Its minimum value is -128 and maximum value is 127.
 Its default value is 0.
Example: byte a = 10, byte b = -20
short Data Type
 The short data type is a 16-bit signed integer. That is 2 byte.
 Its value-range lies between -32,768 to 32,767 (inclusive).
 Its minimum value is -32,768 and maximum value is 32,767.
 Its default value is 0.
 Example: short s = 10000, short r = -5000
int Data Type
 The int data type is a 32-bit signed integer. That is 4 byte.
 Its value-range lies between -2,147,483,648 or (-2^31) to 2,147,483,647 or (2^31 -1).
 Its minimum value is -2,147,483,648 and maximum value is 2,147,483,647.
 Its default value is 0.
Example: int a = 100000, int b = -200000
long Data Type
 The long data type is a 64 bit signed integer. That is 8 byte.
 The value-range lies between -9,223,372,036,854,775,808 or (-2^63) to
9,223,372,036,854,775,807 or (2^63 -1)
 Its minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807.
 Its default value is 0.
 Example: long a=123455334453, long b=3123453211343
Float point number
 The numbers that are not whole numbers, or those that have fractional part, Examples are
3.141, 476.6, and so on.
 Java supports two types of such numbers
Float Data Type

 The float data type is a 32-bit floating point. That is 4 byte


 Its value range is 1.4 e-45 to 3.4e+38
 This is used for single-precision floating point number that is 7 digits after the decimal point
 The float data type should never be used for precise values, such as currency.
 Its default value is 0.0F. Example: float f1 = 234.5f
Double Data Type
 The double data type is a 64-bit floating point. That is 8 byte.
 Its value range is 4.9e-324 to 1.8e+308
 This is used for double-precision floating point number that is 15 digits after the
decimal point.
 The double data type also should never be used for precise values, such as currency.
 Its default value is 0.0.
Example: double d1 = 12.3.
Char Data Type
 The char data type is a single 16-bit Unicode character. That is 2 byte.
 Its value-range lies between '\u0000’ (or 0) to '\uffff'.
 The char data type is used to store characters.
Example: char letterA = 'A'
Concept-6 Declaration of Variables
 A variable is a container which holds the value while the Java program is executed.
 A variable is assigned with a data type.
 Variable is a name of memory location.
 Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be changed.
 All variable must be declared before they can be used in java.
 A variable is defined by the combination of an variable name, a type, and an optional
initializer.

Types of Variables
 There are three types of variables in Java
1. local variable 2. instance variable 3. static variable
Local Variable
 A variable declared inside the body of the method is called local variable.
 You can use this variable only within that method and the other methods in the class.
 A local variable cannot be defined with "static" keyword.
Instance variable
 A variable declared inside the class but outside the body of the method, is called instance
variable.
 It is not declared as static.
 It is called instance variable because its value is instance specific and is not shared among
instances.
Static variable
 A variable which is declared as static is called static variable. It cannot be local.
 You can create a single copy of static variable and share among all the instances of the class.
 Memory allocation for static variable happens only once when the class is loaded in the
memory. Example:

Java variable naming rules


 All variable should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 Variable can never used special character like +,-,&,*.
 Space are not allowed in variable names.
 A keyword cannot be used as an variable name.
 Most importantly, variable are case sensitive. Such as ADD or add both are different.
 After the first character, variable can have any combination of characters.
Concept-6 Scope of Variable Identifier
 The scope and lifetime of a variable is the part of the program in which it is visible and holds
the last entered value.
 A variable can be declared and defined inside a class, method, or block. It defines the scope
of the variable i.e. the visibility or accessibility of a variable.
 In Java, there are distinctly two types of scopes. (a) class scope and (b) method scope
 A variable declared in a class has class scope and scope of a variable declared in a method
has method scope.
 The variables declared in a block have block scope.
 Variable declared inside a block or methods are not visible to outside.
 Thus, the variables defined in main() at the beginning have scope in entire main() method,
however, those defined in a block have block scope.
 A block starts with the left brace ({ ) and ends with the right brace ( }).
The scope of variables is governed by the following rules.
 The scope starts from the point the variable is defined in the block (declared and value
assigned to it).
 Although the variable may be defined anywhere in a block, it can be used only in the
statements appearing after its definition Therefore, there is no use in defining a variable at
the end of block.
 If there are nested blocks, a variable defined in the outer block is visible in the inner blocks
also and it cannot be redefined with the same name in the inner blocks.
Programs
Output:-

Concept-7 Introduction to Operators


 Operators are special symbols (characters) that carry out operations on operands such as
(variables and values). For example: +, -, *, /, < , >, ?: etc.
 If an operator takes only one operand for its operation it is called unary operator.
 If it takes two operands, it is called binary operator and if it takes three operands, it is called
ternary operator.
There are many types of operators in Java which are given below:
1. Assignment Operator
2. Compound Assignment Operator
3. Arithmetic Operator
4. Increment & decrement Operator
5. Relational Operator
6. Ternary Operator
7. Boolean Logical Operator
8. Bitwise Operator & Bit Shift Operators
9. Special operators
Assignment Operator ( = ) & Compound Assignment Operator:-
 The Assignment operator is the single equal sign “=”.
 To assign the value 10 to a variable called X Example:- X=10;
 We write the name of the variable to which a value is to be assigned, and on its right, we
write the value to be assigned
 The name or variable on the left is also called L-value and the values on the right of = is
called R-value. Therefore, R-value is assigned to L-value.
variable_name = Expression;
Syntax: Datatype variable = value;

int x = 10;
Compound Assignment operators

Syntax: variable op=expression

Arithmetic Operator
 Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division.
 They act as basic mathematical operations.
 The operands of the arithmetic operators must be of a numeric type.
 Cannot use them on boolean type.
 This arithmetic operator is the binary operator that is to perform the operation it required
the two operands.
% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0
The + operator can also be used to concatenate two or more strings.
Program

Program

Here String is class and


also act string data type.
Increment & decrement Operator (++) and (--):-
 In JAVA Increment & Decrement Operator ++ and -- operator as both prefix and postfix
in Java.
 The ++ operator increases value by 1 and -- operator decreases the value by 1
X=X+1 (Or) X++; Y=Y+1 (Or) ++Y;
X=X-1 (Or) X--; Y=Y-1 (Or) --Y;
 There is no blank space between the composite symbols ++ or –

Program
Ternary Operator (?:)

 The conditional operator or ternary operator ?: is shorthand for the if-then-else statement.
 The syntax of the conditional operator is:
variable = Expression ? expression1 : expression2
Here's how it works.
If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.
Program

Relational Operator
 The relational operators determine the relationship between the two operands.
 It checks if an operand is greater than, less than, equal to, not equal to and so on.
 Depending on the relationship, it is evaluated to either true or false.
 Relational operators are used in decision making and loops.
Program

Output:-

Boolean Logical Operators


 A Boolean variable can have one of the two values, that is true or false.
 Logical Operators operate only on boolean values.
 The logical operators combine two boolean values to form a resultant boolean values.
Truth Table

Program

Output:-
Bitwise Operator & Bit Shift Operators
 Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
 Bitwise operator works on bits and performs the bit-by-bit operation.

Bitwise AND
 Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
 The & operator compares corresponding bits of two operands.
 If both bits are 1, it gives 1. If either of the bits is not 1, it gives 0.
Program on Bitwise AND

Bitwise OR
 Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
 The | operator compares corresponding bits of two operands.
 If either of the bits is 1, it gives 1. If not, it gives 0.

Program on Bitwise OR
Bitwise NOT
 It is also called as Bitwise complement.
 It is a unary operator (works on only one operand).
 It is denoted by ~.
 The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.

Program on Bitwise NOT


Bitwise XOR
 Bitwise XOR is a binary operator (operates on two operands).
 It's denoted by ^.
 The ^ operator compares corresponding bits of two operands.
 If corresponding bits are different, it gives 1. If corresponding bits are same, it gives 0.

Program on Bitwise XOR


Bit Shift Operators
 A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left.

 Bit shift Operators are as follows


1. Left Shift (<<) 2. Right Shift (>>)
Left Shift Operators
 The left shift operators (<<) shifts all of the bits in a value to the left a specified number of
times. Syntax :- value << num
 Here, num specifies the number of positions to left -shift the value in value.
 (<<) moves all of the bits in the specified values to the left by the number of bits positions
specified by num.
 When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end.

Right Shift Operators


 The Right shift operators (>>) shifts all of the bits in a value to the right a specified number
of times. Syntax: - value >> num
Here, num specifies the number of positions to right - shift the value in value.
 (>>) moves all of the bits in the specified values to the right by the number of bits positions
specified by num.
 When shifting right with a right shift, the least-significant bit is lost and a 0 is inserted on
the other end.

Special operators
 The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
 The instanceof in java is also known as type comparison operator because it compares
the instance with type. It returns either true or false.
Program
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1); //true
}
}
Output:-

Concept-8 Precedence and Associativity of Operators


 Operator precedence determines the order in which the operators in an expression are
evaluated.
 Precedence and associativity are two features of Java operators.
 When there are two or more operators in an expression, the operator with the highest priority
will be executed first. Associativity specify the direction that is left to right or right to left.
Concept-9 Control Statements
 A control statement in java is a statement that determines whether the statements will be
executed or not.
 It controls the flow of a program.
 The Java control statements inside a program are usually executed sequentially.
 Sometimes a programmer wants to break the normal flow and jump to another statement or
execute a set of statements repeatedly control statements are used.
 Control statements in java which breaks the normal sequential flow of the program are called
control statements.

Selection Statements
 Statements that determine which statement to execute and when are known as Selection
statements.
 The flow of the execution of the program is controlled by the control flow statement.
 Statement allow you to control the flow of your program execution based upon conditions
known only during runtime.
 Selection statements are as follows
1. Simple If statement

2. If else statement

3. If else if ladder statement

4. Nested if statement

5. Switch statement
Simple if statement
 The Java if statement tests the condition. It executes the if block if condition is true.
Syntax

Program

Output:-
If else statement
 The Java if-else statement also tests the condition.
 It executes the if block if condition is true otherwise else block is executed.
Syntax

Program:-

Output:-
If else-if ladder statement
 The if-else-if ladder statement executes one condition from multiple conditions.
 It is the any form of switch statement.
Syntax
Program:-

Output:-

Nested if statement
 The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
Syntax

Program:-

Output:-
Switch statement
 It is like if-else-if ladder statement.
 The Java switch statement executes one statement from multiple conditions.
 The switch statement tests the equality of a variable against multiple values.
 There can be one or N number of case values for a switch expression.
 The case value must be of switch expression type only.
 The case value must be constant. It doesn't allow variables.
 The case values must be unique. In case of duplicate value, it renders compile-time error.
 Each case statement can have a break statement which is optional. When control reaches
to the break statement, it jumps the control after the switch expression.
 If a break statement is not found, it executes the next case.
 The case value can have a default label which is optional.
 The Java switch expression must be of byte, short, int, long, char and string.
Syntax
Program:-
Iterative Statements / Looping statement
 Loops are used to execute a set of instructions/functions repeatedly when some conditions
become true.
 Iterative statements are as follows
1. while Loop
2. do-while loop
3. for loop
4. for-each loop
While Loop
 while loop is used to iterate a part of the program several times.
 If the number of iteration is not fixed, it is recommended to use while loop.
Syntax

Program
Infinitive While Loop

do-while Loop
 do-while loop is used to iterate a part of the program several times.
 If the number of iteration is not fixed and you must have to execute the loop at least once,
it is recommended to use do-while loop.
 The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax

Program
For Loop
 The Java for loop is used to iterate a part of the program several times.
 If the number of iteration is fixed, it is recommended to use for loop.
 In Java for loop is the same as C/C++.
 We can initialize the variable, check condition and increment/decrement value.
 It consists of four parts:
1.Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable.
It is an optional condition.
2.Condition: It is the condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false.
It must return boolean value either true or false. It is an optional condition.
3. Statement: The statement of the loop is executed each time until the condition is false.
4. Increment/Decrement: It increments or decrements the variable value.
It is an optional condition.
Syntax
Program

For Each Loop


 The for-each loop is used to traverse array in java.
 It is easier to use than simple for loop because we don't need to increment value and use
subscript notation.
 It works on elements basis not index.
 It returns element one by one in the defined variable.
Syntax
Program

Jump Statement
 The Java jumping statements are the control statements which transfer the program execution
control to a specific statement.
 These statements transfer execution control to another part of the program.
 Java has three types of jumping statements
1.break 2. continue
Break Statement
 When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
 It breaks the current flow of the program at specified condition.
 We can use break statement in the following cases.
 Inside the switch case to come out of the switch block.
 Within the loops to break the loop execution based on some condition.
 Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax

Program
Continue Statement
 The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately.
 The Java continue statement is used to continue the loop.
 It continues the current flow of the program and skips the remaining code at the specified
condition.
 Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax

Program
Concept-10 Elements or Tokens in Java Programs
 Java tokens are elements of java program which are identified by the compiler
Elements of Java (OR)

Keywords
 Keywords also known as reserved words or pre-defined words that have special meaning to
compiler.
 Keywords cannot be used as name of variables, methods, classes, or packages.
 All keywords must be used in lower case only and white space not allowed.
Identifier
 Identifier is the name of variables, methods, classes etc.
 Java is a case sensitive language.
Rules for framing Names or Identifiers.
1. It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
underscore (_).
2. It should not contain white spaces and special symbols.
3. It should not be a keyword of Java.
4. It should not start with a digit but it can start with an underscore.
Conventions for Writing Names
1. Names of packages are completely in lower-case letters such as mypackage, java.lang.
2. Names of classes and interfaces start with an upper-case letter.
3. Names of methods start with a lower-case character.
4. Names of variables should start with a lower-case character.
Separators
 These include comma (,) , semicolon (;), period(.), Parenthesis (), Square brackets [], etc.
Literals:-
 Literal is a notation that represents a fixed value in the source code.
 Literals are the constant values that appear directly in the program.
 It can be assigned directly to a variable.
 A literal represents a value which may be of primitive type, String type, or null type.
 The value may be a number (either whole or decimal point number) or a sequence of
characters which is called String literal, Boolean type, etc.
Types of Literals
1. Integer literals:-
 Sequences of digits.
 The whole numbers are described by different number systems such as decimal numbers,
hexadecimal numbers, octal numbers, and binary numbers.
 Each number has a different set of digits. Types of Integer Literals
a. Decimal Integer Literals b. Hex Integeral Literals c. Octal Integer Literals d.Binary Literals
a. Decimal Integer Literals
 These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
 Examples of such literals are 6, 453, 34789, etc.
b. Hex Integeral Literals
 These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D,
E, and F.
 The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and f.
 The numbers are preceded by 0x or 0X.
 Examples are 0x56ab, o0X6AF2, etc.
c. Octal Integer Literals
 These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
 These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
d. Binary Literals
 These are sequences of binary digits.
 Binary numbers have only two digits 0 and 1 and a base 2.
 These numbers are preceded by 0b.
 Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
2. Floating point literal
 These are floating decimal point numbers or fractional decimal numbers with base 10.
 Examples are 3.14159, 567.78, etc.
3. Boolean literal
 These are Boolean values. There are only two values true or false.
4. Character literal
 These are the values in characters.
 Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
5. String literal
 These are strings of characters in double quotes. Examples are “Delhi”, “John”, “AA”, etc.
6. Null literal
 There is only one value of Null Literal, that is, null.
Escape Sequences
 Escape Sequences character is preceded by a backslash (\) has a special meaning to the
compiler.
Program

Comments
 Comments are Line of Text which is not a part of the compiled program.
 Comments are used for documentation to explain source code.
 They are added to the source code of the program.
 Java supports three types of comments as:
1. Single-line comment:
These comments are started with two front slash characters (//)
Example: // This is Single line comment
2. Multi-line comment :
These comments are enclosed with /* and */
Example: /* It is Multi line Comments */
3. Documentation comment:
These comments are enclosed with /** and */.
It is different from multi line comments in that it can extracted by javadoc utility to generate
an HTML document for the program.
Example: /** It is documentation Comments */
Concept-11 Type Casting
 Type casting is a method or process that converts a data type into another data type in both
ways manually and automatically.
 The automatic conversion is done by the compiler and manual conversion performed by the
programmer.

There are two types of type casting. They are,


i. Implicit Type casting ii. Explicit Type casting
Implicit Type casting or Widening Type Casting
 Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down.
 Implicit type casting is done automatically by a compiler when we assign a value to the
variable.
 It is safe because there is no chance to lose data.
byte -> short -> char -> int -> long -> float -> double
 Example:
int a=10; double b;
b=a;
 Here a is integer and b is double variables.
 Integer value is automatically converted into double by the compiler.
Explicit Type casting OR Narrowing Type Casting
 Converting a higher data type into a lower one is called narrowing type casting.
 It is also known as explicit conversion or casting up.
 It is done manually by the programmer. In this conversion, there is loss of data.
 The explicit type casting is carried out by the following code:
type variable = (new_type) variable;
double D = 6.865;
int A = (int) D;
double -> float -> long -> int -> char -> short -> byte
Program on Implicit Type casting

Program on Explicit Type casting


Concept-12 Static Variables and Methods
Static Variables
 The static variables are class variables. Only one copy of such variables is kept in the
memory and all the objects share that copy.
 The static variables are accessed through class reference, whereas the instance variables are
accessed through class object reference
 The variables in a class may be modified by modifier static.
 The non-static variables declared in a class are instance variables.
 A static variable can be accessed directly by the class name and doesn’t need any object.
Syntax <class-name>.<variable-name>

Static Methods
 Static method in Java is a method which belongs to the class and not to the object.
 A static method can access only static data.
 It cannot access non-static data (instance variables).
 Static variables and methods can be accessed using the class name followed by a dot and the
name of the variable or method.
Syntax <class-name>.<method-name>

 For example The method like sqrt() is a static method in a Math class.
Math.sqrt(5);
Program
Concept-13 Attribute Final
Final Variable
 The value of a variable declared final cannot be changed in the program.
 It makes the variable a constant.
 A few examples of declarations are as follows:
final double PI = 3.14159; // The value of PI cannot be changed in its scope
final int M = 900; // The value of M cannot be changed in its scope
final double X = 7.5643; // The value of x cannot be changed in its scope.
 As mentioned in the comments, the values of PI, M, and x cannot be changed in their
respective scopes.
 The attribute final may be used for methods as well as for classes.
Final Method
 When final keyword is used with Java method, it becomes the final method.
 These are basically connected with inheritance of classes.
 A final method cannot be overridden in a sub-class.
Final Class:
 A Java class with final modifier is called final class
 A final class cannot be sub-classed or inherited.
 Several classes in Java are final including String, Integer, and other wrapper classes.
There are certain important points to be noted when using final keyword in Java
i. New value cannot be reassigned to a variable defined as final in Java.
ii. Final keyword can be applied to a member variable, local variable, method, or class.
iii. Final member variable must be initialized at the time of declaration.
iv. Final method cannot be overridden in Java
v. Final class cannot be inheritable in Java
Concept-14 Formatted Output with printf() Method
 The formatting of output may be carried out by method printf()
The syntax of the method printf () method is as follows
System.out.printf("Formatting string" variables separated by comma);
System.out.printf(“Price of this item = %d”, 22 , “Rupees.”);
The arguments in the example
1. “Price of this item=” It is a string that is displayed as aforementioned.
2. “%d” It is a formatting string for displayed of integer, that is, 22.
3. “Rupees.” A String that is displayed as written here.
Output:- Price of this item = 22 Rupees.

Program:-
Output:-
Important Question
1. Explain various Key Words available in Java.
2. Discuss the rules in Automatic Type Promotion in Expressions.
3. Explain various Operators in Java.
4. Write a Java Program to test whether a given character is Vowel or Consonant.
5. Write a Java Program to swap two numbers using bitwise operator.
6. Write a Java Program to find sum of natural numbers.
7. Write a Java Program to convert decimal number into a hexdecimal number.
8. Write a Java Program to convert decimal number into a binary number.
9. Write a Java Program to find the factorial of a given number.
10. Write a Java Program to find the area of triangle.
11. What are the basic (Primitive) data types defined in java.
12. How do you declare a variable and understand by scope of an identifier for a variable.
13. How is the Scanner class used by a user to input data into a program.
14. How do you declare a constant in java.
15. What is type casting? Explain with an example of automatic type casting and explicit type
casting.
16. Explain the table of Precedence and Associativity of Operators.
17. What are the different type’s selection statements in java?
18. What are the different types of looping and jump statements in java?
19. Explain type of element or token in Java Programming.
20. Explain in detail about Command Line Arguments in Java.
21. Write a short on Static Methods ,Variable and attribute final in Java.

You might also like