Java Notes Unit I
Java Notes Unit I
Simple: A very simple, easy to learn and understand language for programmers
who are already familiar with OOP concepts. Java’s programming style and
structure follows the lineage of C, C++ and other similar languages makes the use
of java efficiently.
Object-oriented: Java is object oriented. Java inherits features of C++. OOP
features of java are influenced by C++. OOP concept forms the heart of java
language that helps java program in survive the inevitable changes accompanying
software development.
Robust: The multi platformed environment of the Web places extraordinary
demands on a program, because the program must execute reliably in a variety of
systems. Thus, the ability to create robust programs was given a high priority in the
design of Java.
Secure, Portable: Java programs are safe and secure to download from internet. At
the core of the problem is the fact that malicious code can cause its damage due to
unauthorized access gained to system resources. Java achieved this protection by
confining a program to the Java execution environment and not allowing it access
to other parts of the computer. The same code must work on all computers.
Therefore, some means of generating portable executable code was needed.
Multithreaded: Java supports multithreaded programming, which allows a
programmer to write programs that performs multiple tasks simultaneously. The
Java run-time system comes with an elegant and sophisticated solution for multi-
process synchronization that helps to construct smoothly running interactive
systems.
Interpreted & High performance: Java enables the creation of cross-platform
programs by compiling into an intermediate representation called Java bytecode.
This code can be executed on any system that implements the Java Virtual
Machine. The Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a
just-in-time compiler.
Dynamic: Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time. This
makes it possible to dynamically link code in a safe and expedient manner.
Java Programming Environment: -
Syntax:
class classname {
field declaration or data members;
method declaration or member functions;
}
void total() {
total = mark1+mark2+mark3;
System.out.println("Total:"+total);
}
void average() {
average = total/3;
System.out.println("Average:"+average);
}
public static void main(String[] args) {
//creating an object using new keyword
Student obj = new Student();
//invoking method using the object
System.out.println("Name of the student:"+name);
obj.total();
obj.average();
}
}
We can also create multiple objects and store information in it through reference variable.
Example:
class Student{
String name;
int id;
}
class Student1{
public static void main(String[] args) {
//creating an object using new keyword
Student s1 = new Student();
Student s2 = new Student();
}
}
Java Tokens:-
Tokens are the smallest elements of a program that is meaningful to the compiler. They
are also known as the fundamental building blocks of the program. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
6. Comments
7. Separators
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.
Ex:-abstract assert boolean
break byte case
catch char class
const continue default
Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user-defined names consisting of long sequence of letters and digits
with either a letter or the underscore (_) as a first character.
Ex:- MyVariable n
MYVARIABLE m
I sal
Constants/Literals:- Constants are also like normal variables. But the only difference
is, their values cannot be modified by the program once they are defined. Constants
refer to fixed values. They are also called as literals. Constants may belong to any of the
data type.
Syntax:
final data_type variable_name;
Special Symbols:
Ex:- [] () {}, ; * =
Separators are used to separate different parts of the codes. It tells the compiler about
completion of a statement in the program. The most commonly and frequently used
separator in java is semicolon (;).
Data types are the kind of data that variables hold in a programming language. A data type is an
attribute of data that tells the compiler or interpreter how the programmer plan to use the data.
There are two types of data types in Java:
• Primitive data types ( intrinsic or built-in types )
• Non-primitive data types (derived types )
Data
Size Description
Type
byte 1 byte Stores whole numbers from -128 to 127
2
short Stores whole numbers from -32,768 to 32,767
bytes
4
int Stores whole numbers from -2,147,483,648 to 2,147,483,647
bytes
8 Stores whole numbers from -9,223,372,036,854,775,808 to
long
bytes 9,223,372,036,854,775,807
4
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
bytes
8
double Stores fractional numbers. Sufficient for storing 15 decimal digits
bytes
boolean 1 bit Stores true or false values
boolean 1 bit Stores true or false values
2
char Stores a single character/letter or ASCII values
bytes
Primitive types are predefined (already defined) in Java. A primitive type starts with a lowercase
letter. The primitive data types include char, byte, short, int, long, boolean, float, and double.
char :
The char data type is used to store a single character. The character must be surrounded by single
quotes.
char grade = 'A'; //A is a charater
System.out.println(grade);
byte:
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory.
byte num = 120;
System.out.println(num);
short:
The short data type can store whole numbers from -32768 to 32767.
short num = 6000;
System.out.println(num);
int:
The int data type is the preferred data type when we create variables with a numeric value. The
int data type can store whole numbers from -2147483648 to 2147483647.
int num = 100000;
System.out.println(num);
long:
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that
you should end the value with an "L".
long num = 16000000000L;
System.out.println(num);
boolean:
A boolean data type is declared with the boolean keyword and can only take the values true or
false.
boolean male = true;
boolean female = false;
System.out.println(male); // Outputs true
System.out.println(female); // Outputs false
float:
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you
should end the value with an "f".
float num = 4.75f;
System.out.println(num);
double:
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you
should end the value with a "d".
double num = 18.85d;
System.out.println(num);
Interfaces:
The interface keyword to create an interface. An interface is slightly different from the class. It
contains only ****constants and method declarations.
interface car // car is the interface name{ void start(); void stop(); }
Strings:
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes.
String greeting = "Hello World"; System.out.println(greeting);
Arrays:
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. To declare an array, define the variable type with square brackets.
String[] cars = {"Audi", "BMW", "Ford"}; int[] num = {10, 20, 30, 40};
Narrowing casting must be done manually by placing the type in parentheses in front of the
value.
syntax:
type variable1 = (type) variable2;
Example:
public class Main {
public static void main(String[] args) {
double valueDouble = 8.79;
int valueInt = (int) valueDouble; // Manual casting: double to int
System.out.println(valueDouble); // Outputs 8.79
System.out.println(valueInt); // Outputs 8
}}
here (int) is the used in parentheses in front of the value to convert double data type to int data
type.
Operator is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Unary Operator :- The Java unary operators require only one operand. Unary operators are used to perform
various operations
Arithmetic Operators:- Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.
Logical Operators:- You can also test for true or false values with logical
operators. Logical operators are used to determine the logic between variables or
values.
Operator Name Description Example
&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result !(x < 5 && x < 10)
is true
Java Strings:- Strings are used for storing text. A String variable contains a collection of
characters surrounded by double quotes.
String Length:- A String in Java is actually an object, which contain methods that can perform
certain operations on strings. For example, the length of a string can be found with the length()
method.
There are many string methods available, for example toUpperCase() and
toLowerCase():
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
Syntax:
while(Boolean_expression) {
// Statements
}
Example:
while( x < 15 ) {
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}
}
}
/*EXPLANATION:
The loop executes until the value of x is less than 15, the value of x is incremented
by 1. When the condition is false the loop exit */
/*OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
2. do while loop : A do-while loop is similar to a while loop with one exception that
it executes the statements inside the body of the do-while before checking the
condition. If the Boolean expression is true, the statements in the loop execute again.
This process repeats until the Boolean expression is false.
Syntax:
do {
// Statements
}while(Boolean_expression);
Expressions:
do {
System.out.print("value x : " + x );
x++;
System.out.print("\\n");
}while( x < 15 );
}
}
/*EXPLANATION:
The control passes to the body of the loop and then checks the condition.
If the condition is less than 15 loop executes, and then the value of x is incremented
by 1. When the condition false the loop terminates. */
/*OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
3. for loop:- A for loop ( finite loop ) is a repetition control structure that allows you
to efficiently write a loop that needs to be executed a specific number of times. A for
loop is useful when you know how many times a task is to be repeated.
Syntax:
Example:
/* OUTPUT
value x : 10
value x : 11
value x : 12
value x : 13
value x : 14 */
Jump Statements:-
Jump statements are used to unconditionally transfer program control from
one point to elsewhere in the program. Jump statements are primarily used to
interrupt loops or switch-case instantly. Java supports three jump statements: break,
continue, and return.
i) break statement:
The break construct is used to break out of the middle of loops: for, do, or while
loop. When a break statement is encountered, execution of the current loops
immediately stops and resumes at the first statement following the current loop.
Example:
Example:
Example:
/*OUTPUT:
5 */
1.If Statements
The if statement is used to test the condition. It checks boolean conditions true or
false. There are various types of if statements in Java.
• Simple if statement
• if-else statement
• if-else-if ladder
• nested if statement
i) Simple if Statement :
The Java if statement tests the condition. It executes the *if block* if the
condition is true. Where boolean_expression is a condition.
Syntax:
if(Boolean_expression/condition) {
// Statements will execute if the Boolean expression is true
}
Example:
/*OUTPUT:
Welcome to ShapeAI */
Syntax:
if(Boolean_expression/condition) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
Statement-X;
Example:
/*OUTPUT
This is else statement */
Syntax:
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is true.
}
Statement-X;
Example:
/*EXPLANATION:
executes the second else if block hence the num value 30 is equal to 30 */
/* OUTPUT
Value of X is 30 */
Syntax:
switch(expression) {
case value :
// Statements
break;
case value :
// Statements
break;
Example:
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Good");
break;
case 'C' :
System.out.println("Well done");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
/*EXPLANATION:
The given expression grade is assigned with 'C'. hence it matches with the case 'C'.
So case 'C' statement "Well done" is executed*/
/*OUTPUT:
Well done
Your grade is C */
Ternary operator (? :) :-
The meaning of ternary is composed of three parts. The ternary operator
(?:) consists of three operands. It is used to evaluate Boolean expressions. The
operator decides which value will be assigned to the variable. It is the only
conditional operator that accepts three operands. It can be used instead of the if-else
statement.
Syntax:
variable = (condition) ? expression1 : expression2
Example:-
public class TernaryOperatorExample
{
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}
Labeled Loop:-
A label is a valid variable name that denotes the name of the loop to where the control
of execution should jump. To label a loop, place the label before the loop with a
colon at the end. Therefore, a loop with the label is called a labeled loop.
1. Java Labeled “for” Loop:- Labeling a for loop is useful when we want to break
or continue a specific for loop according to requirement. If we put a break statement
inside an inner for loop, the compiler will jump out from the inner loop and continue
with the outer loop again.
if we need to jump out from the outer loop using the break statement given inside
the inner loop then we should define the label along with the colon(:) sign before the
loop.
Syntax:
labelname:
for(initialization; condition; incr/decr)
{
//functionality of the loop
}
Example:-
public class LabeledForLoop
{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}
// create an array
int[] numbers = {3, 9, 5, -5};