0% found this document useful (0 votes)
4 views23 pages

Java

The document provides a comprehensive overview of various Java programming concepts, including constant variables, variable scope, branching statements, looping statements, classes, method parameters, method overloading, constructors, and practical examples. Each section includes sample code and explanations to illustrate the concepts effectively. Additionally, it covers specific programming tasks such as calculating sums, checking for values in arrays, and averaging marks.

Uploaded by

omkumbhar011
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)
4 views23 pages

Java

The document provides a comprehensive overview of various Java programming concepts, including constant variables, variable scope, branching statements, looping statements, classes, method parameters, method overloading, constructors, and practical examples. Each section includes sample code and explanations to illustrate the concepts effectively. Additionally, it covers specific programming tasks such as calculating sums, checking for values in arrays, and averaging marks.

Uploaded by

omkumbhar011
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

LAB: Java Programming

BCS-407

1. Program to demonstrate Constant Variable.


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.
o The purpose to use the static modifier is to manage the memory.
o It also allows the variable to be available without loading any instance of the
class in which it is defined.
o The final modifier represents that the value of the variable cannot be changed.
It also makes the primitive data type immutable or unchangeable.

The syntax to declare a constant is as follows:

final datatype identifier_name=value;

For example, price is a variable that we want to make constant.

final double PRICE=432.78;

final is the non-access modifier. The double is the data type and PRICE is the
identifier name in which the value 432.78 is assigned.
To declare a variable as constant, we use both static and final modifiers. It
shares a common memory location for all objects of its containing class.
The use of constants in programming makes the program easy and understandable
which can be easily understood by others. It also affects the performance because a
constant variable is cached by both JVM and the application.
→ Simple program of constant variable:
class variableconst
{
public static void main(String args[])

COCSIT, Latur
LAB: Java Programming
BCS-407

{
final double PRICE=245.94;
int unit=12;
double total_bill;
total_bill=PRICE*unit;
[Link]("The total amount you have to pay is:" +total_bill);
}
}

→ Output for above program is:

→ Program of how we cannot assign value to final variable:


class variableconst
{
public static void main(String args[])
{
final double PRICE=245.94;
PRICE=221.94;
int unit=12;
double total_bill;
total_bill=PRICE*unit;
[Link]("The total amount you have to pay is:" +total_bill);
}
}

COCSIT, Latur
LAB: Java Programming
BCS-407

→ Output for above program is:

2. Program to demonstrate Scope Variable.


Variables are an essential part of data storage and manipulation in the realm of
programming. In addition to making values available within a programme, they
offer a means of holding them temporarily. Not all variables, though, are made
equally. Each variable has a scope that specifies how long it will be seen and used
in a programme. Java code must be efficient and error-free, which requires an
understanding of variable scope. The scope of variables in Java will be explored in
this section, along with their effects on how programmes are executed.
→ Program:
public class Main {
public static void main(String[] args) {
// The following variable is a class variable, and is accessible throughout the class
int classVariable = 100;
if (true) {
// The following variable is a local variable, and is only accessible within this block
int localVariable = 200;
[Link]("Class variable: " + classVariable);
[Link]("Local variable: " + localVariable);
}

// The local variable is not accessible here


// [Link]("Local variable: " + localVariable);

COCSIT, Latur
LAB: Java Programming
BCS-407

[Link]("Class variable: " + classVariable);


}
}

→ Output:

The local variable is only accessible within the block in which it is declared (i.e.,
between the curly braces {}). The class variable, on the other hand, is accessible
throughout the class.

3. Program to demonstrate Branching Statement.


Branching statements are the statements used to jump the flow of execution from
one part of a program to another. The branching statements are mostly used
inside the control statements. Java has mainly three branching statements,
i.e., continue, break, and return. The branching statements allow us to exit from
a control statement when a certain condition meet.
In Java, continue and break statements are two essential branching statements
used with the control statements. The break statement breaks or terminates the
loop and transfers the control outside the loop. The continue statement skips the
current execution and pass the control to the start of the loop.
→ Program to demonstrate break:
The break statement in Java is commonly used to exit from a loop prematurely.
Here's a simple example demonstrating its usage:
public class BreakExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int searchFor = 6;

COCSIT, Latur
LAB: Java Programming
BCS-407

boolean found = false;


for (int number: numbers) {
if (number == searchFor) {
found = true;
break; // exit the loop if the number is found
}
}
if (found) {
[Link]("Number " + searchFor + " found!");
} else
{
[Link]("Number " + searchFor + " not found!");
}
}
}

→ Output:

In this example, the program searches for a specific number (searchFor) within an
array of numbers. If the number is found, the loop is terminated early using the
break statement, and the program prints a message indicating that the number was
found. If the number is not found, it prints a message indicating that it was not
found.
→ Program to demonstrate continue:
public class ContinueExample {

COCSIT, Latur
LAB: Java Programming
BCS-407

public static void main(String[] args) {


// Print even numbers from 1 to 10, skipping odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // skip the rest of the loop body for odd numbers
}
[Link](i);
}
}
}

→ Output:

The continue statement is used in Java to skip the current iteration of a loop and
proceed to the next iteration.
In this example, the loop iterates from 1 to 10. When the value of i is odd
(determined by i % 2 != 0), the continue statement is executed, causing the loop
to skip the rest of the iteration and move on to the next value of i. Therefore, only
even numbers are printed.

4. Program to demonstrate Looping Statement.


Looping is a feature that facilitates the execution of a set of instructions repeatedly
until a certain condition holds false. Java provides three types of loops namely
the for loop, the while loop, and the do-while loop. Loops are also known
as Iterating statements or Looping constructs in Java.
→ Program:
public class LoopingExample {

COCSIT, Latur
LAB: Java Programming
BCS-407

public static void main(String[] args) {


// Example of for loop
[Link]("Example of for loop:");
for (int i = 1; i <= 5; i++) {
[Link]("Iteration " + i);
}

// Example of while loop


[Link]("\nExample of while loop:");
int j = 1;
while (j <= 5) {
[Link]("Iteration " + j);
j++;
}

// Example of do-while loop


[Link]("\nExample of do-while loop:");
int k = 1;
do {
[Link]("Iteration " + k);
k++;
} while (k <= 5);
}
}

COCSIT, Latur
LAB: Java Programming
BCS-407

→ Output:

The for loop iterates a specific number of times, defined by an initialization, a


condition, and an increment/decrement expression.
The while loop continues iterating as long as a condition is true.
The do-while loop is similar to the while loop, but it always executes the loop
body at least once before checking the condition.

5. Program to demonstrate Simple Class.


public class Car {
// Fields or instance variables
private String make;
private String model;
private int year;
// Constructor
public Car(String make, String model, int year) {
[Link] = make;

COCSIT, Latur
LAB: Java Programming
BCS-407

[Link] = model;
[Link] = year;
}
// Methods to access and modify fields
public String getMake() {
return make;
}
public void setMake(String make) {
[Link] = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
[Link] = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
[Link] = year;
}

// Method to display car information


public void displayInfo() {
[Link]("Car Make: " + make);
[Link]("Car Model: " + model);

COCSIT, Latur
LAB: Java Programming
BCS-407

[Link]("Car Year: " + year);


}
public static void main(String[] args) {
// Creating an instance of the Car class
Car myCar = new Car("Toyota", "Corolla", 2020);
// Displaying car information
[Link]();
}
}

→ Output:

The Car class represents a simple model of a car, with fields for make, model, and
year.
It has a constructor to initialize the object with the provided values.
Getter and setter methods are provided to access and modify the fields of the
object.
The displayInfo() method prints out the details of the car.
In the main method, an instance of the Car class is created and its information is
displayed.

6. Program to demonstrate Method Parameter.


In Java, methods can have parameters that allow you to pass data to the method
when it is called. Here's an example demonstrating how to define a method with
parameters:

COCSIT, Latur
LAB: Java Programming
BCS-407

→ Program:
public class MethodParameterExample {
// Method that takes two integers as parameters and returns their sum
public static int add(int a, int b) {
return a + b;
}
// Method that takes an array of strings as a parameter and prints them
public static void printNames(String[] names) {
for (String name : names) {
[Link](name);
}
}

public static void main(String[] args) {


// Calling the add method with two integers as arguments
int sum = add(5, 3);
[Link]("Sum: " + sum);

// Calling the printNames method with an array of strings as an argument


String[] myNames = {"Alice", "Bob", "Charlie"};
printNames(myNames);
}
}

COCSIT, Latur
LAB: Java Programming
BCS-407

→ Output:

The add method takes two integer parameters (a and b) and returns their sum.
The printNames method takes an array of strings (names) as a parameter and
prints each name in the array.
In the main method, we call these methods with appropriate arguments. add(5, 3)
passes two integer values to the add method, and printNames(myNames) passes
an array of strings to the printNames method.

7. Program to demonstrate Method Overloading.


Method overloading in Java allows you to define multiple methods with the same
name but with different parameter lists. Here's an example demonstrating method
overloading:
→ Program:
public class MethodOverloadingExample {
// Method to add two integers
public static int add(int a, int b) {
return a + b;
}

// Method to add three integers


public static int add(int a, int b, int c) {
return a + b + c;
}

COCSIT, Latur
LAB: Java Programming
BCS-407

// Method to concatenate two strings


public static String concatenate(String str1, String str2) {
return str1 + str2;
}

public static void main(String[] args) {


// Calling the add method with two integers
int sum1 = add(5, 3);
[Link]("Sum1: " + sum1);

// Calling the add method with three integers


int sum2 = add(5, 3, 2);
[Link]("Sum2: " + sum2);

// Calling the concatenate method with two strings


String result = concatenate("Hello, ", "world!");
[Link]("Concatenated string: " + result);
}
}

→ Output:

In this above example:


There are two add methods, one taking two int parameters and another taking
three int parameters.

COCSIT, Latur
LAB: Java Programming
BCS-407

There's a concatenate method that takes two String parameters.


All three methods have the same name (add or concatenate), but they differ in the
number or type of parameters.
In the main method, we call each overloaded method with appropriate arguments,
and Java resolves which method to call based on the arguments provided.

8. Program to demonstrate Constructor.


→ Program:
public class Rectangle {

// Instance variables

private double length;

private double width;

private double area;

// Constructor with parameters

public Rectangle(double length, double width) {

[Link] = length;

[Link] = width;

// Method to calculate area

public void calculateArea() {

area = length * width;

// Getter method for area

public double getArea() {

return area;

// Main method to demonstrate the use of constructor

public static void main(String[] args) {

// Creating a new Rectangle object using the constructor

Rectangle myRectangle = new Rectangle(5.0, 3.0);

COCSIT, Latur
LAB: Java Programming
BCS-407

// Calculating the area

[Link]();

// Accessing the area using the getter method and printing it

[Link]("Area of the rectangle: " + [Link]());

→ Output:

We have a Rectangle class with three instance variables: length, width, and area.
The class has a constructor Rectangle(double length, double width) which takes
two parameters and initializes the instance variables length and width.
There's a method calculateArea() which calculates the area of the rectangle using
the formula length * width.
There's a getter method getArea() to access the value of the area.
In the main method, we create a new Rectangle object myRectangle by calling the
constructor with the provided parameters.
We then calculate the area of the rectangle using the calculateArea() method and
print it using the getter method.

COCSIT, Latur
[Link] an array of five float and calculate their sum.
public class APQ1 {

public static void main(String[] args) {

float [] a={44.4f,42.1f,12.3f,34.2f,22.2f};

float sum=0;

for(float b:a) //for each loop.

sum=sum+b;

[Link]("sum of above float is=”+sum);

OUTPUT :- sum of above float is=155.2

2 program to find out wheather a given [Link] is


present in an array or not.
public class APQ2 {

public static void main(String[] args) {

int [] a={23,22,25,22,56,12};

int num=23;

boolean array=false;

for(int b:a)

if(num==b)

array=true;
break;

if(array)

[Link]("the value is present in an array");

else{

[Link]("the value is not present in an array");

Output :- the value is present in an array.

3 Program to calculate [Link] from an array contain


marks using for each loop
public class APQ3 {

public static void main(String[] args) {

int [] mark={22,44,55,66,78,98,44};

float sum=0;

for(int b:mark)

sum=sum+b;

}
[Link]("the average marks are="+sum/[Link]);

OUTPUT :- the average marks are=58.142857

[Link] program to add two matrices of size 2*3


public class APQ4 {

public static void main(String[] args) {

int [] [] a={{1,2,3},

{4,5,6}};

int [] [] b={{1,2,3},

{4,5,6}};

int [] [] result={{0,0,0},

{0,0,0}};

for(int i=0;i<[Link];i++)

for(int j=0;j<a[i].length;j++)

result[i][j]=a[i][j]+b[i][j];

for(int i=0;i<a[i].length;i++)

{
for(int j=0;j<a[i].length;j++){

[Link](result[i][j] + " ");

result[i][j]=a[i][j]+b[i][j];

[Link](" ");

OUTPUT :- 246

8 10 12

[Link] a program to reverse an Array.


public class APQ5 {

public static void main(String[] args) {

int [] a={1,2,3,4,45,56,56,44,33};

int l=[Link];

int n=[Link](l, 2);

int temp;

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

temp=a[i];

a[i]=a[l-1-i];

a[l-1-i]=temp;

for(int element:a)

{
[Link](element+" ");

OUTPUT:- 33 44 56 56 45 4 3 2 1

[Link] a program to find maximum element from an


array
public class APQ6 {

public static void main(String[] args) {

int [] a={22,33,4,78,900,95};

int max=0;

for (int element: a)

if(element>max)

max=element;

[Link]("the maximum value in an array is= "+max);

OUTPUT :- the maximum value in an array is= 900.

[Link] a program to find out array is sorted or not


public class APQ7 {
public static void main(String[] args) {

int [] a={2,4,5,6,7,8,100};

boolean issorted=true;

for(int i=0;i<[Link]-1;i++)

if(a[i]>a[i+1])

issorted=false;

break;

if(issorted)

[Link]("sorted array");

else{

[Link]("unsorted array");

OUTPUT :- sorted array

[Link] a program to find maximum element from an


array
public class APQ8 {

public static void main(String[] args) {

int[] array = {5, 3, 9, 1, 7};

int min = findMinimum(array);

[Link]("Minimum element in the array: " + min);

public static int findMinimum(int[] array) {

if (array == null || [Link] == 0) {

throw new IllegalArgumentException("Array must not be empty or null");

int min = array[0];

for (int i = 1; i < [Link]; i++) {

if (array[i] < min) {

min = array[i];

return min;

OUTPUT :- Minimum element in the array: 1

You might also like