1 UNIT-1 Notes
1 UNIT-1 Notes
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.
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. 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.
7. 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.
8. 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:-
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:-
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java: Primitive and Non Primitive
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 is not allowed in variable names.
A keyword cannot be used as a 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 three types of scopes. (a) class scope (b) method scope (c) block 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:-
int x = 10;
Compound Assignment operators
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
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:-
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.
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:-
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
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:-
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
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
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 Constants:-
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.
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
Program:-
Output:-
Important Question
1. List and explain the Tokens in the Java language.
2. List and explain the features of Java language.
(Or)
3. What are java buzz words? Give brief description.
4. List and explain the Data types in Java program with examples.
5. Explain how with the help of Command line arguments we can customize the behavior of
the main() method
6. What is a variable? Explain their importance in java language. What rules to be followed
to define them?
7. List and explain the control statements with examples.
(Or)
Compare the working of the while loop and do-while loop with suitable examples.
(Or)
Demonstrate Nested if and else using an example.
(Or)
Explain the syntax of various Loop control statements in Java.
(Or)
List the various control statement. Explain any one control statement with the help of
flowchart and example program.
(Or)
Explain various types of iterative statements with suitable example.
8. Demonstrate the operator precedence using a Java program.
9. Explain various types of Operators with example.
(Or)
Demonstrate Bitwise operators using a Java program.
(Or)
Demonstrate the Increment and Decrement operators with a Java program.
(Or)
List and explain the Unary, Binary and Ternary operators with examples.
(Or)
Demonstrate logical operators with an example Java program.
(Or)
With the help of example program explain the various arithmetic operators supported by
java language.
10. Demonstrate implicit and explicit type casting with an example program.
11. Explain the usage of Static variables and methods with an example Java program.
(Or)
Develop a Java program to demonstrate the behavior of static methods &variables?
12. What do you understand by type casting & automatic promotion? Explain with suitable
examples.
(Or)
Discuss the rules in Automatic Type Promotion in Expressions.
Important Program
1. Develop a Java program to perform string reverse operations.
2. Develop a program to compute factorial of a number.
3. Write a java program to read three numbers through the keyboard and find their sum and
average.
4. Develop a program to compute factorial of a given number.
5. Write a Java Program to test whether a given character is Vowel or Consonant.
6. Write a Java Program to swap two numbers using bitwise operator.
7. Write a Java Program to find sum of natural numbers.
8. Write a Java Program to convert decimal number into a hexdecimal number.
9. Write a Java Program to convert decimal number into a binary number.
10. Write a Java Program to find the area of triangle.