Unit 1
Unit 1
1. Simple
2. Secured
3. Portable
4. Object-oriented
5. Robust
6. Multithreaded
9. Distributed
10. Dynamic
1. Simple
Java is a small and simple language. Java does not use pointers, pre-processor
header files, goto statement and many other. It also eliminates operator
overloading and multiple inheritance. Java inherits the C/C++ syntax and many
of the object oriented features of C++.
2. Secured
When it comes to security, Java is always the first choice. With java secure
features it enable us to develop virus free, temper free system. Java program
always runs in Java runtime environment with almost null interaction with
system OS, hence it is more secure.
3. Portable
Java programs can be easily moved from one computer system to another,
anywhere and anytime. This is the reason why Java has become a popular
language for programming on Internet.
4. Object-oriented
5. Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism, and many more.
6. Multithreaded
Multithreaded means handling multiple tasks simultaneously. This means that
we need not wait for the application to finish one task before beginning another.
To accomplish this, java supports multithreaded programming which allows
writing programs that do many things simultaneously.
Java has invented to achieve "write once; run anywhere, anytime, forever". The
java provides JVM (Java Virtual Machine) to achieve architectural-neutral or
platform-independent. The JVM allows the java program created using one
operating system can be executed on any other operating system.
Java code is translated into byte code after compilation and the byte code is
interpreted by JVM (Java Virtual Machine). This two steps process allows for
extensive code checking and also increase security. JVM can execute byte codes
(highly optimized) very fast with the help of Just in time (JIT) compilation
technique.
9. Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods
across a network.
10. Dynamic
Java has the capability of linking dynamic new classes, methods and objects.
1. Class
2. Object
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
1. Class:
A class is a collection of objects of the similar type.
Class is a user defined data type in JAVA. Once a class has been defined we can
create any number of objects belonging to that class.
2. Object:
It is a collection of no. of entities and they may represent a person or a place or
a bank account or a table of data or any item that the program has to handle.
Object is collection of number of entities that has state and behavior and it may
be any real world entity.
3. Data Encapsulation:
The process of combining data and functions into a single unit is called data
encapsulation. With using encapsulation the data is not accessible outside the
world only those functions which are present in the class can access the data.
4. Data Abstraction:
It refers to the act of representing essential features without including the
background details or any explanations.
5. Inheritance:
It is the process of objects of one class acquiring the properties of objects of
another class. The main advantage of inheritance is to provide the data
reusability i.e., we can add additional features to the existing class without
modifying it.
6. Polymorphism:
It refers to the ability to take more than one form. In polymorphism an operation
can exhibit different behaviors in different instances. For example consider the
operation of addition of two numbers then operation will generate a sum. If the
operands are strings then the operation would produce a third string by
concatenation.
The primitive data types are built-in data types and they specify the type of
value stored in a variable and the memory size. The primitive data types do not
have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char,
and boolean.
2. Non-primitive Data Types
In java, non-primitive data types are the reference data types or user-created
data types. All non-primitive data types are implemented using object concepts.
Every variable of the non-primitive data type is an object. The non-primitive
data types may use additional methods to perform certain operations. The
default value of non-primitive data type variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue,
Stack, Class, Interface, etc.
4. Variables in JAVA
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
1. local variable
2. instance variable
3. static variable
1) Local Variable
The variables declared inside a method or blocks are known as local variables.
A local variable is visible within the method in which it is declared. The local
variable is created when execution control enters into the method or block and
destroyed after the method or block execution completed.
Example Program
class LocalVariable{
2) Instance Variable
The variables declared inside a class and outside any method, constructor or
block are known as instance variables or member variables. These variables are
visible to all the methods of the class. The changes made to these variables by
method affects all the methods in the class. These variables are created separate
copy for every object of that class.
Example Program
class InstanceVariable {
public InstanceVariable()
{ // Default Constructor
//Main Method
// Object Creation
// Displaying O/P
3) Static variable
A static variable is a variable that declared using static keyword. The instance
variables can be static variables but local variables cannot. Static variables are
initialized only once, at the start of the program execution. The static variable
only has one copy per class irrespective of how many objects we create.
Example Program
class StaticVariable {
}
5. Constants in JAVA
Constant is a value that cannot be changed after assigning it. Java does not
directly support the constants.
In Java, to declare any variable as constant, we use static and final modifiers. It
is also known as non-access modifiers. According to the Java naming
convention the identifier name must be in capital letters.
1. Using the "final" keyword: One way to declare a constant in Java is to use
the "final" keyword. When a variable is declared as final, its value cannot be
changed after it is initialized. For example
javaCopy code
3. Using an enum: You can also define a constant using an enum. An enum is a
special type of class that represents a group of constants. For example:
In the above example, each of the days of the week is a constant, and they can
be accessed using the name of the enum and the dot operator.
For example:
DaysOfWeek.MONDAY
All of the above methods of declaring constants in Java ensure that the value of
the constant cannot be changed once it has been initialized.
Example Program
System.out.println("The area of a circle with radius " + radius + " is " + area);
Local variables are declared and initialized within a method or a block of code.
The scope of a local variable is limited to the method or block where it is
declared and initialized, and it is not accessible outside of that scope. Once the
control flow leaves the scope of the local variable, the variable is destroyed and
its value is lost.
Instance variables, on the other hand, are declared and initialized outside of any
method, in the class definition. The scope of an instance variable is the entire
class, and it is accessible from any method within the class.
Example Program
//instance variable
//local variable
7. Operators in JAVA
1. Arithmetic operators: +, -, *, /, %
4. Assignment operators: =
5. Conditional/Ternary operator: ? :
1. Arithmetic operators:-
2. Relational operators:-
3. Logical operators:-
2. Logical OR (||).
4. Assignment operator:-
In JAVA language ‘?’ and ‘:’ are called conditional operator or ternary
operators.
Syntax: Condition ? TRUE Part : FALSE Part;
Here first the condition is checked, if it is true then TRUE Part is executed
otherwise FALSE Part is executed.
1. Pre-increment operator
2. Post-increment operator
3. Pre-decrement operator
4. Post-decrement operator
1. Pre-increment operator:
2. Post-increment operator:
1. ++ operator is placed after the operand is called post-increment operator.
Ex: x++,a++
3. Pre-decrement operator:
4. Post-decrement operator:
7. Bitwise operators:-
The data stored in a computer memory as a sequence of 0’s and 1’s.There are
some operators works with 0’s and 1’s are called bitwise operators. Bitwise
operators cannot be worked with real constants.
1. Bitwise AND (&): The result of the bitwise AND is 1 when both the bits are
1 otherwise 0.
2. Bitwise OR (|): The result of the bitwise OR is 0 when both the bits are 0
otherwise 1.
3. Bitwise X-OR (^): The result of the bitwise X-OR is 1 when one bit is 0 and
other bit is 1 otherwise 0.
4. Bitwise left shift (<<): This operator can be used to shift the bit positions to
the left by ‘n’ positions.
5. Bitwise right shift (>>): This operator can be used to shift the bit positions to
the right by ‘n’ positions.
6. Bitwise 1's complement (~): This operator can be used to reverse the bit i.e.,
it changes from 0 to 1 and 1 to 0.
8. Special operators
For example, to create a new instance of the MyClass class, you would use the
following code:
This creates a new object of the MyClass class and assigns a reference to it to
the variable obj. The parentheses are empty because MyClass has a default
constructor that takes no arguments.
The java instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface).
Example Program
class Simple1{
}
8. Java Type casting and Type conversion
In Java, type conversion and casting are used to change the data type of a
variable or expression. Type conversion refers to changing the data type of a
variable or expression from one data type to another, while casting refers to
explicitly changing the data type of a variable or expression.
Type conversion
In type conversion, a data type is automatically converted into another data
type by a compiler at the compiler time. In type conversion, the destination
data type cannot be smaller than the source data type, that’s why it is also
called widening conversion. One more important thing is that it can only be
applied to compatible data types.
Example
int x=30;
float y;
y=x; // y==30.000000.
Type Casting
In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing
casting, the destination data type may be smaller than the source data type
when converting the data type to another data type, that’s why it is also called
narrowing conversion.
Syntax
destination_datatype = (target_datatype)variable;
Example
In this code, the (double) before num casts the int value to a double.
9. enum(Enumerated data type)
An enumerated data type, or enum, in Java is a special type of class that
represents a group of constants. Enums are useful when you want to define a set
of values that are known at compile time and are not likely to change. An enum
is defined using the enum keyword, and its values are defined as a list of named
constants inside curly braces {}.
Example Program:enum
enum DaysOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
10. Conditional/ Decision making statements in JAVA
They are
1. if statement
2. if-else statement
5. switch statement
1. if statement:
Syntax:
if (condition)
Statements;
next statement;
Operation: First the condition is checked if it is true then the statements will be
executed and then control is transferred to the next statement in the program.
if the condition is false, control skips the statements and then control is
transferred to the next statement in the program.
2. if-else statement:
Syntax:
if (condition)
statement1;
else
statement2;
next statement;
Operation: First the condition is checked if the condition is true then statement1
will be executed and it skips statement2 and then control is transferred to the
next statement in the program.
Syntax:
if (condition1)
if (condition2)
statement1;
else
statement2;
else
statement3;
next statement;
If the condition2 is false then statement2 will be executed and then control is
transferred to the next statement in the program.
Syntax:
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
}
else if(condition n)
statement n;
else
default statement;
next statement;
Operation: This type of structure is known as the else-if ladder. This chain
generally looks like a ladder hence it is also called as an else-if ladder. The test-
expressions are evaluated from top to bottom. Whenever a true test-expression
if found, statement associated with it is executed. When all the n test-
expressions becomes false, then the default else statement is executed.
5. switch statement:
If we want to select one statement from more number of statements then switch
statement is used.
Syntax:
switch(expression)
case value1:block1;
break;
case value2:block2;
break;
--------
--------
case valuen:blockn;
break;
next statement;
If the expression value is not matched with any case value then default block
will be executed and then control is transferred to the next statement in the
program.
They are
1. while
2. do while
3. for
It is used when a group of statements are executed repeatedly until the specified
condition is true.
Syntax:
while(condition)
next statement;
Operation: First the condition is checked if the condition is true then control
enters into the body of while loop to execute the statements repeatedly until the
specified condition is true.
if the condition is false, the body of while loop is skipped and control comes out
of the loop and continues with the next statement in the program.
It is used when a group of statements are executed repeatedly until the specified
condition is true.
Syntax:-
do
while(condition);
next statement;
Operation: In do-while loop the condition is checked at the end i.e., the control
first enters into the body of do while loop to execute the statements. After the
execution of statements it checks for the condition. if the condition is true then
the control again enters into the body of do while loop to execute the statements
repeatedly until the specified condition is true.
if the condition is false then control continues with the next statement in the
program.
It is used when a group of statements are executed repeatedly until the specified
condition is true.
Syntax:-
for (initialization;condition;increment/decrement )
next statement;
Operation: First initial value will be assigned. Next condition is checked if the
condition is true then control enters into the body of for loop to execute the
statements. After the execution of statements the initial value will be
incremented/decremented. After initial value will be incremented/decremented
the control again checks for the condition. If the condition is true then the
control is again enters into the body of for loop to execute the statements
repeatedly until the specified condition is true.
if the condition is false, the body of for loop is skipped and control comes out of
the loop and continues with the next statement in the program.
1. break statement:-
break is an unconditional statement used to terminate the loops or switch
statement.
When it is used in loops (while,do while,for) control comes out of the loop and
continues with the next statement in the program.
When it is used in switch statement to terminate the particular case block and
then control is transferred to the next statement in the program.
Syntax:-
statement;
break;
Example Program
if (i == 5) {
System.out.println(i);
In this example, the loop will execute until i is equal to 5, and then it will
terminate.
2. continue statement:-
continue is an unconditional statement used to control to be transferred to the
beginning of the loop for the next iteration without executing the remaining
statements in the program.
Syntax:-
statement;
continue;
Example Program
if (i == 5) {
System.out.println(i);
In this example, the loop will skip the iteration where i is equal to 5 and move
on to the next iteration.
Types of Arrays
class AddMatrix
int i,j;
A[i][j] = in.nextInt();
System.out.println();
System.out.println();
System.out.println("Sum of matrices:-");
System.out.print(C[i][j]+"\t");
System.out.println();
class MulMatrix
int i,j,k;
A[i][j] = in.nextInt();
B[i][j] = in.nextInt();
System.out.println("\n\noutput matrix:-");
for ( j= 0 ; j <3;j++)
for ( k= 0 ; k <3;k++ )
C[i][j]=C[i][j]+A[i][k]*B[k][j] ;
}
}
System.out.print(C[i][j]+ "\t");
System.out.println();
else
A class defines the properties and methods that an object of that class can have.
The properties (also called instance variables) are the data fields that store the
state of the object, while the methods define the behavior of the object.
// instance variables
// constructor
this.name = name;
this.age = age;
// methods
System.out.println("Hello, my name is " + name + " and I am " + age + " years
old.");
this.age = age;
return age;
this.name = name;
}
public String getName() {
return name;
This class defines a person with a name and an age, and provides methods to set
and get the values of those properties, as well as a method to say hello.
To create an object of this class, you would use the following syntax:
This creates a new person object with the name "John" and the age 30. You can
then call the methods of the object, like this:
person.sayHello();
person.setAge(31);
System.out.println(person.getAge());
31
Once you have defined a class, you can create objects of that class using the
new keyword, like this:
This creates a new object of the Person class, with the name "John" and the age
30. The object is stored in the person variable.
You can then access the state and behavior of the object using dot notation. For
example, you can access the name and age properties of the person object like
this:
This calls the getName() and getAge() methods of the person object, which
return the values of the name and age fields, respectively.
person.sayHello();
This calls the sayHello() method of the person object, which prints a message to
the console.
Example
System.out.println("Hello, world!");
Example
int sum = a + b;
return sum;
Example
System.out.println("Hello, world!");
Example
public class Person {
this.name = name;
Example
this.name = name;
return name;
}
17. Constructors in Java:
In Java, a constructor is a special method that is called when an object of a class
is created. It is used to initialize the object's state and allocate memory for it.
Constructors in Java:
Constructors can call other constructors in the same class using the this()
keyword.
A constructor can also call a constructor of the parent class using the super()
keyword.
1. Default constructor
2. Parameterized constructor
1.Default constructor
class Bike1{
Bike1(){
System.out.println("Bike is created");
2. Parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student{
int id;
String name;
id = i;
name = n;
}
void display(){
s1.display();
s2.display();
A static field is a variable that belongs to the class, rather than an instance of the
class, and is shared among all instances of the class. In contrast, a non-static (or
instance) field belongs to an instance of the class and has a unique value for
each instance.
A static method is a method that belongs to the class, rather than an instance of
the class. Like static fields, static methods can be invoked without creating an
instance of the class.
Static fields and methods are declared using the static keyword in Java. Here's
an example:
MyClass.myStaticField = 42;
MyClass.myStaticMethod();
1.public: The public access modifier allows unrestricted access to the member
from any code in any package.
2.protected: The protected access modifier allows access to the member from
any code in the same package or any subclass of the class.
3.private: The private access modifier allows access to the member only from
within the same class.
4.default (no modifier): The default access modifier allows access to the
member from any code in the same package.
package com.example;
int defaultField;
// Can be accessed from any code in the same package or any subclass of
MyClass
void defaultMethod() {
}
private void privateMethod() {
this.value = value;
}
public void setValue(int value) {
this.value = value;
return this.value;
In this class, this.value refers to the value field of the current object. In the
constructor, this.value = value sets the value of the object's value field to the
value passed as a parameter. In the setValue() and getValue() methods,
this.value is used to refer to the current object's value field.
public MyClass() {
this(0);
}
this.value = value;
this(value1 + value2);
// ...
22. Recursion
Recursion is a programming technique in which a function calls itself to solve
a problem. It is a way of solving complex problems by breaking them down
into smaller, simpler sub problems, and solving them recursively until a base
condition is met. Recursion involves a function calling itself directly or
indirectly.
In the above example, When the method is called with a value of 5, for
example, it first calculates 5 * factorial(4), which in turn calculates 4 *
factorial(3), and so on, until it reaches the base case of factorial(0), which
returns 1. The final result is then returned all the way back up the call stack.
return number;
else
// recursion step
return fibonacci(number - 1) +
fibonacci(number - 2);
System.out.printf("Fibonacci of 10:\n");
counter++)
System.out.printf("%d\t",
fibonacci(counter));
0 1 1 2 3 5 8 13 21 34
Example Program
import java.lang.*;
class StringExample
{
public static void main(String args[])
{
String s="Welcome to Java programming";
System.out.println("Length of the string="+s.length());
System.out.println("Character at 13 index="+s.charAt(13));
System.out.println("Sub string from 5 to 15="+s.substring(5,15));
System.out.println("Lower case="+s.toLowerCase());
System.out.println("Upper case="+s.toUpperCase());
}
}
Output:
Length of the string=27
Character at 13 index=v
Sub string from 5 to 15=me to Java
Lower case=welcome to java programming
Upper case=WELCOME TO JAVA PROGRAMMING
The garbage collector in Java tracks which objects are still in use and which
ones are no longer needed, and automatically deallocates the memory for the
unused objects. This process is called garbage collection.
To do so, we were using free() function in C language and delete() in C++. But,
in java it is performed automatically. So, java provides better memory
management.
1. finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method
is defined in Object class as:
protected void finalize(){}
2. gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
Output:
class Palindrome
{
int n,r,sum=0,temp;
n=in.nextInt();
temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
if(temp==sum)
else
System.out.println("not a palindrome");
n = in.nextInt();
fact = 0;
if (i%j == 0) {
fact++;
if (fact == 2) {
System.out.println(i);
in.close();
{
int n = 10, firstTerm = 0, secondTerm = 1;
firstTerm = secondTerm;
secondTerm = nextTerm;
originalNumber = number;
while (originalNumber != 0)
originalNumber /= 10;
if(result == number)
while(number != 0)
number = number/10;
int n = 4;
String temp;
if (names[i].compareTo(names[j]) > 0)
// swapping
temp = names[i];
names[i] = names[j];
names[j] = temp;
System.out.println(names[i]);