[go: up one dir, main page]

0% found this document useful (0 votes)
0 views60 pages

Unit 1

The document provides an overview of Java programming, covering its history, features (buzzwords), object-oriented programming concepts, data types, variables, constants, scope, lifetime, and operators. Key features of Java include simplicity, security, portability, and being object-oriented, while the document also explains various types of variables and operators used in Java. Additionally, it highlights the principles of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism.

Uploaded by

abhishek ch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views60 pages

Unit 1

The document provides an overview of Java programming, covering its history, features (buzzwords), object-oriented programming concepts, data types, variables, constants, scope, lifetime, and operators. Key features of Java include simplicity, security, portability, and being object-oriented, while the document also explains various types of variables and operators used in Java. Additionally, it highlights the principles of object-oriented programming such as classes, objects, encapsulation, inheritance, and polymorphism.

Uploaded by

abhishek ch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

JAVA-UNIT-1

Java Programming- History of Java, comments, Java Buzz words,


Data types, Variables, Constants, Scope and Lifetime of variables,
Operators, Type conversion and casting, Enumerated types,
Control flow- Conditional statements, loops, break and continue
statements, arrays, simple java stand alone programs, class,
object, and its methods constructors, methods, static fields and
methods, access control, this reference, overloading constructors,
recursion, exploring string class, garbage collection.

1. Java Buzz words


The features of Java are also known as Java buzzwords.

JAVA was developed by James Gosling in 1991 at Sun micro systems.

The following are the features or buzzwords of JAVA. They are

1. Simple

2. Secured

3. Portable

4. Object-oriented

5. Robust

6. Multithreaded

7. Architecture-neutral (or) Platform Independent

8. Compiled, Interpreted & High Performance

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

Java is a pure object oriented language. Almost everything in java is an object.


All program code and data reside within objects and classes Java comes with an
extensive set of classes, arranged in packages that we can use in our programs
by inheritance. The object model in java is simple and easy to extend.

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.

7. Architecture-neutral (or) Platform Independent

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.

8. Compiled, Interpreted & High Performance

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.

2. Object-Oriented Programming (OOP) features/Concepts of


JAVA
The following are the basic concepts/principles of OOP in JAVA.

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.

3. Data Types in Java


Java programming language has a rich set of data types. The data type is a
category of data stored in variables. In java, data types are classified into two
types and they are as follows.

1. Primitive Data Types

2. Non-primitive Data Types


1. Primitive Data Types

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.

A variable is the name of a reserved area allocated in memory. In other words, it


is a name of the memory location. It is a combination of "vary + able" which
means its value can be changed.
Syntax

data_type variable_name = value;

Variable is a name of memory location. There are three types of variables in


java.

1. local variable
2. instance variable
3. static variable

Example Program: Types of Variables in Java


public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

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{

public static void main(String[] args)


{

int var = 10; // Declared a Local Variable

// This variable is local to this main method only

System.out.println("Local Variable: " + var);

Output: Local Variable: 10

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 String name; // Declared Instance Variable

public InstanceVariable()

{ // Default Constructor

this.name = "javaprogramming"; // initializing Instance Variable

//Main Method

public static void main(String[] args)


{

// Object Creation

InstanceVariable name = new InstanceVariable();

// Displaying O/P

System.out.println(" name is: " + name.name);

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.

The static variable is access by using class name.

Example Program

class StaticVariable {

public static String name = "mahesh babu"; //Declared static variable

public static void main (String[] args) {

System.out.println(" Name is : "+StaticVariable.name);

}
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.

There are several ways to declare constants in Java.

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

final int MAX_VALUE = 100;

2. Using the "static final" keywords: Another way to declare a constant in


Java is to use the "static final" keywords. This is useful when you want to
declare a constant that can be accessed by all instances of a class. For example:

javaCopy code

public class Constants { public static final int MAX_VALUE = 100; }

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:

public enum DaysOfWeek { MONDAY, TUESDAY, WEDNESDAY,


THURSDAY, FRIDAY, SATURDAY, SUNDAY }

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

public class ConstantsExample {

public static final double PI = 3.14159; // declaring a constant named PI with


value 3.14159

public static void main(String[] args) {

double radius = 5.0;

double area = PI * radius * radius;

System.out.println("The area of a circle with radius " + radius + " is " + area);

6. Scope and Lifetime of variables in JAVA


In Java, the scope of a variable refers to the part of the program where the
variable is accessible and can be used. The lifetime of a variable refers to the
period of time during the execution of a program when the variable exists and
retains its value.

The scope of a variable can be determined by where it is declared and


initialized. There are two main types of variables in Java: local variables and
instance variables (also called class variables or member variables).

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

public class Demo

//instance variable

String name = "Andrew";

//class and static variable

static double height= 5.9;

public static void main(String args[])

//local variable

int marks = 72;

7. Operators in JAVA

Operator in java is a symbol that is used to perform operations.


There are many types of operators in java which are given below:

1. Arithmetic operators: +, -, *, /, %

2. Relational operators: >, <, <=, >=, ==, !=

3. Logical operators: &&, ||, !

4. Assignment operators: =

5. Conditional/Ternary operator: ? :

6. Increment and Decrement operators: ++, --

7. Bitwise operators: &, |, ^, <<, >>, ~

8. Special operators: new and instanceof

1. Arithmetic operators:-

1. Arithmetic operators are used to perform basic arithmetic operations


between the operands.

2. There are 5 types of Arithmetic operators in JAVA language.

They are +, -,* ,/ ,%.

3. Division operator(/) gives the result in quotient.

4. Modulus operator(%) gives the result in remainder.

5. % operator cannot be worked with the real constants.

2. Relational operators:-

1. Relational operators are used to compare the relation between the


operands.
2. There are 6 types of relational operators in JAVA language.

They are <, >, <=, >=,! = , ==.

3. Relational operator gives the result either in true or false.

3. Logical operators:-

1. Logical operators are used to combine two or more relational conditions.

2. Logical operators gives the result either in true or false.

3. There are 3 types of Logical operators in JAVA language. They are

1. Logical AND (&&).

2. Logical OR (||).

3. Logical NOT (!).

4. Assignment operator:-

Values can be assigned to a variables using assignment operator in JAVA


language. The symbol of assignment operator is ‘=’.

Assignment operator supports 5 short hand assignment operators in JAVA


language they are += , - = , * = , /= , %=

5.Conditional operator/Ternary opertor:-

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.

6. Increment and Decrement operators:-

1. These operators are used to increment or decrement the value of the


variable by 1.

2. ‘ ++ ’ is the increment operator in JAVA language.

3. ‘-- ’ is the decrement operator in JAVA language.

4. There are 4 types of operators in JAVA language.

1. Pre-increment operator

2. Post-increment operator

3. Pre-decrement operator

4. Post-decrement operator

1. Pre-increment operator:

1. ++ operator is placed before the operand is called pre-increment operator.


Ex: ++x,++a

2. Pre-increment operator specifies first increment the value of the variable


by 1 and then assigns the incremented value to other variable.

2. Post-increment operator:
1. ++ operator is placed after the operand is called post-increment operator.
Ex: x++,a++

2. Post-increment operator specifies first assigns the value of the variable to


other variable and then increments the value of the variable by1.

3. Pre-decrement operator:

1. -- operator is placed before the operand is called pre-decrement operator.


Ex: --x,--a

2. Pre-decrement operator specifies first decrement the value of the variable


by 1 and then assigns the decremented value to other variable.

4. Post-decrement operator:

1. -- operator is placed after the operand is called post-decrement operator.


Ex: x--,a--

2. Post-decrement operator specifies first assigns the value of the variable to


other variable and then decrements the value of the variable by1.

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.

There are 6 types of operators in JAVA language.

1. Bitwise AND (&)


2. Bitwise OR (|)

3. Bitwise X-OR (^)

4. Bitwise left shift (<<)

5. Bitwise right shift (>>)

6. Bitwise 1's complement ( ~)

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

1. new operator in JAVA

the new operator is used to create a new instance of a class. It dynamically


allocates memory for an object of a specified class and returns a reference to
that object. The new operator is followed by the name of the class that you want
to create an instance of, and a set of parentheses that may contain arguments to
the constructor.

For example, to create a new instance of the MyClass class, you would use the
following code:

MyClass obj = new MyClass();

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.

2. instanceof operator in JAVA

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. If we apply the
instanceof operator with any variable that has null value, it returns false.

The syntax of the instanceof operator is as follows:

object instanceof type

Example Program

class Simple1{

public static void main(String args[]){

Simple1 s=new Simple1();

System.out.println(s instanceof Simple1);//true

}
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

int num = 10;

double result = (double) num;

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

public class EnumExample {

enum DaysOfWeek {

MONDAY,

TUESDAY,

WEDNESDAY,

THURSDAY,

FRIDAY,

SATURDAY,

SUNDAY

public static void main(String[] args) {

DaysOfWeek today = DaysOfWeek.THURSDAY;

System.out.println("Today is: " + today);

}
10. Conditional/ Decision making statements in JAVA

There are 5 types of Conditional/Decision making statements in JAVA


language.

They are

1. if statement

2. if-else statement

3. nested if-else statement

4. if-else-if ladder statement

5. switch statement

1. if statement:

It can be used to execute a single statement or a group of statements if and only


if the specified condition is true.

It is a one way branching statement in JAVA language.

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:

It can be used to execute either if or else block of statements based on the


condition.

It is a two way branching statement in JAVA language.

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.

if the condition is false then statement1 is skipped and statement2 will be


executed and then control is transferred to the next statement in the program.

3. Nested if-else statement:


If we want to check more than one condition then nested if else is used.

It is multi way branching statement in JAVA language.

Syntax:

if (condition1)

if (condition2)

statement1;

else

statement2;

else

statement3;

next statement;

Operation: First the condition1 is checked if it is false then statement3 will be


executed and then control is transferred to the next statement in the program.
If the condition1 is true then condition2 is checked, if it is true then statement1
will be executed and then control is transferred to the next statement in the
program.

If the condition2 is false then statement2 will be executed and then control is
transferred to the next statement in the program.

4. if-else-if ladder statement:

If we want to check the multiple conditions then if-else-if ladder statement is


used.

It is multi way branching statement in JAVA language.

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.

It is a multi way branching statement in JAVA language.

Syntax:

switch(expression)

case value1:block1;
break;

case value2:block2;

break;

--------

--------

case valuen:blockn;

break;

default :default block;

next statement;

Operation: First the expression value (integer constant/character constant) is


compared with all the case values in the switch. if it is matched with any case
value then the particular case block will be executed and then control is
transferred to the next statement in the program.

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.

11. Loops or Repetition or Iterative statements in JAVA

There are 3 types of Loops/Repetition statements in JAVA language.

They are

1. while
2. do while

3. for

1. while loop statement:

It is used when a group of statements are executed repeatedly until the specified
condition is true.

It is also called entry controlled loop.

The minimum number of execution takes place in while loop is 0.

Syntax:

while(condition)

body of while loop;

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.

2. do while loop statement:-

It is used when a group of statements are executed repeatedly until the specified
condition is true.

It is also called exit controlled loop.


The minimum number of execution takes place in do while loop is 1.

Syntax:-

do

body of do while loop;

while(condition);

next statement;

In do-while loop condition should be end with semicolon (;).

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.

3. for loop statement:-

It is used when a group of statements are executed repeatedly until the specified
condition is true.

It is also called entry controlled loop.

The minimum number of execution takes place in for loop is 0.

Syntax:-
for (initialization;condition;increment/decrement )

body of for loop;

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.

12. break and continue statements in JAVA


In Java, the break and continue statements are used to modify the behavior of
loops.

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

for (int i = 0; i< 10; i++) {

if (i == 5) {

break; // exit the loop when i is 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

for (int i = 0; i< 10; i++) {

if (i == 5) {

continue; // skip this iteration when i is 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.

13. Arrays in JAVA


In Java, an array is a data structure that stores a fixed-size sequential collection
of elements of the same data type. The elements in an array can be accessed
using an index, which is an integer value that represents the position of the
element in the array.

Types of Arrays

1-D Array (1-DA):


A 1-D array, also known as a one-dimensional array, is a collection of
elements of the same data type arranged in a linear manner. It is also called a
vector or a one-dimensional vector. In Java, a 1-D array is declared with a
single set of square brackets [] after the data type.

Syntax: data_type [] variable_name = new data_type[size];


Example: int[] a= new int[5];

2-D Array (2-DA):


A 2-D array, also known as a two-dimensional array, is a collection of
elements of the same data type arranged in a tabular or matrix-like form with
rows and columns. It can be thought of as an array of arrays. In Java, a 2-D
array is declared with two sets of square brackets [][] after the data type
Syntax: data_type[][] variable_name = new data_type[size][size];
Example: int[][] a= new int[5][4];

Example Program1: Addition of two matrices


import java.util.Scanner;

class AddMatrix

public static void main(String args[])

int i,j;

Scanner in = new Scanner(System.in);

int A[][] = new int[3][3];

int B[][] = new int[3][3];

int C[][] = new int[3][3];

System.out.println("Enter the elements of A");

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j < 3 ;j++ )

A[i][j] = in.nextInt();

System.out.println();

System.out.println("Enter the elements of B");

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j < 3 ;j++ )


B[i][j] = in.nextInt();

System.out.println();

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j < 3 ;j++ )

C[i][j] = A[i][j] + B[i][j] ;

System.out.println("Sum of matrices:-");

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j < 3 ;j++ )

System.out.print(C[i][j]+"\t");

System.out.println();

Example Program2: Multiplication of two matrices


import java.util.Scanner;

class MulMatrix

public static void main(String args[])

int i,j,k;

Scanner in = new Scanner(System.in);


{

int A[][] = new int[3][3];

int B[][] = new int[3][3];

int C[][] = new int[3][3];

System.out.println("Enter the elements of A");

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j < 3 ;j++ )

A[i][j] = in.nextInt();

System.out.println("Enter the elements of B");

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j < 3 ;j++ )

B[i][j] = in.nextInt();

System.out.println("\n\noutput matrix:-");

for ( i= 0 ; i < 3 ; i++ )

for ( j= 0 ; j <3;j++)

for ( k= 0 ; k <3;k++ )

C[i][j]=C[i][j]+A[i][k]*B[k][j] ;

}
}

for ( i= 0 ; i < 3; i++ )

for ( j=0 ; j < 3;j++ )

System.out.print(C[i][j]+ "\t");

System.out.println();

else

System.out.print("multipication does not exist ");

14. Class in JAVA


In Java, a class is a blueprint for creating objects that encapsulate data and
behavior. It is a fundamental concept in object-oriented programming, and it
allows you to create complex programs by defining your own custom data
types.

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.

Here is an example of a simple Java class:

public class Person {

// instance variables

private String name;


private int age;

// constructor

public Person(String name, int age) {

this.name = name;

this.age = age;

// methods

public void sayHello() {

System.out.println("Hello, my name is " + name + " and I am " + age + " years
old.");

public void setAge(int age) {

this.age = age;

public int getAge() {

return age;

public void setName(String name) {

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:

Person person = new Person("John", 30);

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());

This would output:

Hello, my name is John and I am 30 years old.

31

15. Object in JAVA


In Java, an object is an instance of a class that encapsulates data and behavior.
An object represents a real-world entity, and it has a state and behavior. The
state of an object is stored in instance variables, also known as fields, while its
behavior is defined by methods.
To create an object in Java, you first need to define a class. A class is a
blueprint for creating objects, and it specifies the properties and methods that an
object of that class will have.

Once you have defined a class, you can create objects of that class using the
new keyword, like this:

Person person = new Person("John", 30);

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:

String name = person.getName();

int age = person.getAge();

This calls the getName() and getAge() methods of the person object, which
return the values of the name and age fields, respectively.

You can also call methods on the object, like this:

person.sayHello();

This calls the sayHello() method of the person object, which prints a message to
the console.

16. Methods in JAVA


Java is an object-oriented programming language that supports a wide range of
methods. A method is a block of code that performs a specific task, and it can
be used to perform an action, return a value, or both. Here are some of the most
commonly used methods in Java:
1. void method: This is a method that does not return any value. It is often used
to perform a task or operation, such as printing a message to the console or
updating a variable.

Example

public void printMessage() {

System.out.println("Hello, world!");

2. return method: This is a method that returns a value. It is often used to


calculate a value or to retrieve data from a variable or object.

Example

public int calculateSum(int a, int b) {

int sum = a + b;

return sum;

3. static method: This is a method that belongs to a class, rather than an


instance of the class. It can be called without creating an object of the class.

Example

public static void printMessage() {

System.out.println("Hello, world!");

4. constructor method: This is a method that is used to create objects of a


class. It is often used to set initial values for the object's fields.

Example
public class Person {

private String name;

public Person(String name) {

this.name = name;

5. instance method: This is a method that belongs to an instance of a class,


rather than the class itself. It can be called using an object of the class.

Example

public class Person {

private String name;

public void setName(String name) {

this.name = name;

public String getName() {

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:

The name of a constructor is the same as the name of the class.

Constructors don't have a return type, not even void.

Constructors are called automatically when an object is created.

If no constructor is defined in a class, Java provides a default constructor with


no arguments.

A class can have multiple constructors with different arguments (overloading).

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.

Constructors can throw exceptions to indicate that an error occurred during


initialization.

Types of java constructors

There are two types of constructors:

1. Default constructor

2. Parameterized constructor

1.Default constructor

A constructor that have no parameter is known as default constructor.

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will
be invoked at the time of object creation.

class Bike1{

Bike1(){

System.out.println("Bike is created");

public static void main(String args[]){

Bike1 b=new Bike1();

Output: Bike is created

2. Parameterized constructor

A constructor which has parameters is known as parameterized constructor.

Example of 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;

Student(int i,String n){

id = i;

name = n;
}

void display(){

System.out.println(id + " " +name);

public static void main(String args[]){

Student s1 = new Student(111,"Karan");

Student s2 = new Student(222,"Aryan");

s1.display();

s2.display();

18. Static fields and methods


Static fields and methods in Java are related concepts that are used to define
class-level data and behavior.

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:

public class MyClass {


public static int myStaticField;

public static void myStaticMethod() {

System.out.println("Hello from myStaticMethod");

In this example, myStaticField is a static field of the MyClass class, while


myStaticMethod() is a static method. These can be accessed using the class
name, like this:

MyClass.myStaticField = 42;

MyClass.myStaticMethod();

19. Access control/Access modifiers in JAVA


Access control in Java refers to the mechanisms that restrict or allow access to
the various members (fields, methods, classes, and interfaces) of a class. Java
provides four access modifiers to control the level of access that is allowed for a
particular member:

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.

Here's an example that demonstrates the use of these access modifiers:

package com.example;

public class MyClass {

public int publicField;

protected int protectedField;

int defaultField;

private int privateField;

public void publicMethod() {

// Can be accessed from any code in any package

protected void protectedMethod() {

// Can be accessed from any code in the same package or any subclass of
MyClass

void defaultMethod() {

// Can be accessed from any code in the same package

}
private void privateMethod() {

// Can only be accessed from within MyClass

20. this reference in JAVA


In Java, the "this" reference is a keyword that refers to the current object. It can
be used inside an instance method or a constructor to refer to the object on
which the method or constructor is being called.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

For example, consider the following class:

public class MyClass {

private int value;

public MyClass(int value) {

this.value = value;

}
public void setValue(int value) {

this.value = value;

public int getValue() {

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.

21. Overloading constructors in JAVA


In Java, constructor overloading refers to the practice of defining multiple
constructors for a class with different parameter lists. This allows objects to be
instantiated with different initial states, depending on the parameters passed to
the constructor.

Constructor overloading is similar to method overloading, which involves


defining multiple methods with the same name but different parameter lists.

Here's an example that demonstrates constructor overloading:

public class MyClass {

private int value;

public MyClass() {

this(0);
}

public MyClass(int value) {

this.value = value;

public MyClass(int value1, int value2) {

this(value1 + value2);

// ...

In this example, MyClass has three constructors: a no-argument constructor that


calls the single-argument constructor with a value of 0, a single-argument
constructor that sets the value field to the specified value, and a two-argument
constructor that calls the single-argument constructor with the sum of the two
values.

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.

Example Program1: Factorial Number


import java.util.*;
class Factorial
{
int recursion(int n)
{
if(n==0||n==1)
return 1;
else
return n*recursion(n-1);
}

public static void main(String[] args)


{
Factorial fc=new Factorial();
Scanner sc=new Scanner(System.in);
System.out.println("Enter n value");
int n=sc.nextInt();
System.out.println("factorial of " + n + " is"+fc.recursion(n));
}
}

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.

Example Program2: Fibonacci Series


public class MainClass1 {

public static long fibonacci(long


number) {

if ((number == 0) || (number == 1))

return number;

else

// recursion step

return fibonacci(number - 1) +

fibonacci(number - 2);

public static void main(String[] args) {

System.out.printf("Fibonacci of 10:\n");

for (int counter = 0; counter < 10;

counter++)

System.out.printf("%d\t",

fibonacci(counter));

Output: Fibonacci of 10:

0 1 1 2 3 5 8 13 21 34

23. Exploring String class in JAVA


In Java, the String class is used to represent a sequence of characters. Strings are
one of the most commonly used data types in Java, and the String class provides
a wide range of methods for working with and manipulating strings. Here are
some of the most commonly used methods of the String class:
1.length(): This method returns the length of the string, i.e., the number of
characters in the string.
2.charAt(int index): This method returns the character at the specified index in
the string. The index is zero-based, with the first character at index 0.
3.substring(int beginIndex, int endIndex): This method returns a new string
that is a substring of the original string, starting from the beginIndex
(inclusive) and ending at the endIndex (exclusive).
4.concat(String str): This method concatenates the specified string str to the
end of the original string and returns a new string.
5.toLowerCase(), toUpperCase(): These methods return new strings that are
the lowercase and uppercase versions of the original string, respectively.
6.startsWith(String prefix), endsWith(String suffix): These methods check if
the original string starts with the specified prefix or ends with the specified
suffix, respectively, and return a boolean value.
7.replace(char oldChar, char newChar), replace(CharSequence target,
CharSequence replacement): These methods replace occurrences of a character
or a sequence of characters in the original string with a new character or a new
sequence of characters, respectively, and return a new string.

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

24. garbage collection in JAVA


In Java, the garbage collector is a part of the Java Virtual Machine (JVM) that
automatically manages the memory allocation and deallocation for Java objects.
When an object is created in Java, memory is allocated to store the object, and
when the object is no longer needed, the memory must be deallocated so that it
can be reused by other objects.

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.

public static void gc(){}

Example of garbage collection in JAVA

public class TestGarbage1{


public void finalize(){
System.out.println("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}

Output:

object is garbage collected

object is garbage collected

25. Write a Java program to check whether a given number is


palindrome or not?
import java.util.Scanner;

class Palindrome
{

public static void main(String args[])

int n,r,sum=0,temp;

Scanner in=new Scanner(System.in);

System.out.println("enter any number");

n=in.nextInt();

temp=n;

while(n>0){

r=n%10;

sum=(sum*10)+r;

n=n/10;

if(temp==sum)

System.out.println("palindrome number ");

else

System.out.println("not a palindrome");

26. Write a Java program to print the prime numbers from 1 to


N?
import java.util.Scanner;

public class Prime {

public static void main(String[] args) {


int n, fact;

Scanner in = new Scanner(System.in);

System.out.println("Enter any number");

n = in.nextInt();

System.out.println("Prime numbers from 1 to n are");

for (int i = 1; i <= n; i++) {

fact = 0;

for (int j = 1; j <= i; j++) {

if (i%j == 0) {

fact++;

if (fact == 2) {

System.out.println(i);

in.close();

27. Write a java program to display the Fibonacci series without


using Recursion?
class Fibonacci {

public static void main(String[] args)

{
int n = 10, firstTerm = 0, secondTerm = 1;

System.out.println("Fibonacci Series till " + n + " terms:");

for (int i = 1; i <= n; ++i) {

System.out.print(firstTerm + ", ");

int nextTerm = firstTerm + secondTerm;

firstTerm = secondTerm;

secondTerm = nextTerm;

28. Write a Java program to check whether a given number is


Armstrong or not?
public class Armstrong {

public static void main(String[] args) {

int number = 371, originalNumber, remainder, result = 0;

originalNumber = number;

while (originalNumber != 0)

remainder = originalNumber % 10;

result += Math.pow(remainder, 3);

originalNumber /= 10;

if(result == number)

System.out.println(number + " is an Armstrong number.");


else

System.out.println(number + " is not an Armstrong number.");

29. Write a java program to reverse the given number?


public class Reverse

public static void main(String[] args)

int number = 987654, reverse = 0;

while(number != 0)

int remainder = number % 10;

reverse = reverse * 10 + remainder;

number = number/10;

System.out.println("The reverse of the given number is: " + reverse);

30. Write a Java program to sort a given set of strings in the


alphabetical order?
import java.io.*;
class AscendingNames {

public static void main(String[] args)

// storing input in variable

int n = 4;

// create string array called names

String names[]= { "Rani", "Akshaya", "Guru", "Roshan" };

String temp;

for (int i = 0; i < n; i++)

for (int j = i + 1; j < n; j++)

// to compare one string with other strings

if (names[i].compareTo(names[j]) > 0)

// swapping

temp = names[i];

names[i] = names[j];

names[j] = temp;

// print output array

System.out.println("The names in alphabetical order are: ");


for (int i = 0; i < n; i++)

System.out.println(names[i]);

You might also like