UNIT-1 Notes
UNIT-1 Notes
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. 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
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:
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
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:
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:-
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
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.
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.