0% found this document useful (0 votes)
8 views12 pages

Java Observation Book

The document contains multiple Java programs demonstrating various programming concepts such as calculating averages, area of a circle, recursion for factorials, printing patterns, and using arrays. It also covers object-oriented principles like constructors, getters, setters, inheritance, and polymorphism. Additionally, it provides instructions for using the Eclipse IDE for project creation, code formatting, and debugging.

Uploaded by

magt02468
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)
8 views12 pages

Java Observation Book

The document contains multiple Java programs demonstrating various programming concepts such as calculating averages, area of a circle, recursion for factorials, printing patterns, and using arrays. It also covers object-oriented principles like constructors, getters, setters, inheritance, and polymorphism. Additionally, it provides instructions for using the Eclipse IDE for project creation, code formatting, and debugging.

Uploaded by

magt02468
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/ 12

1.

Calculate the Average of Numbers

import java.util.Scanner;
public class AverageCalculator
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
double sum = 0;
System.out.println("Enter " + n + "
numbers:"); for (int i = 0; i < n; i++) {
double num =
scanner.nextDouble(); sum +=
num;
}
double average = sum / n;
System.out.println("Average: " + average);
scanner.close();
}
}

Output:
Enter the number of elements:
5 Enter 5 numbers:
2
3
4
5
6
Average: 4.0

2. Calculate the Area of a Circle

import java.util.Scanner;
public class AreaOfCircle
{
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the radius of
Circle: "); double radius =
scanner.nextDouble();
double area = Math.PI * radius * radius;
System.out.println("Area of the circle with radius " + radius + " is " + area);
}
}

Output:
Enter the radius of Circle: 7
Area of the circle with radius 7.0 is 153.93804002589985

3. Program for find the Factorial of a given Number Using Recursion

import java.util.Scanner;
public class FactorialUsingRecursion {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a positive
integer: "); int n = scanner.nextInt();
long factorial = calculateFactorial(n);
System.out.println("Factorial of " + n + " is " + factorial);
scanner.close();
}
public static long calculateFactorial(int
n) { if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}

Output:
Enter a positive integer: 9
Factorial of 9 is 362880

4. Print a Pattern (e.g., Triangle)

import java.util.Scanner;
public class PrintPattern {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a positive integer to adjust the size of the
triangle: "); int n = scanner.nextInt();
for (int i =1; i <= n; i++)
{ for (int j = 1; j <= i;
j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

Output:
Enter a positive integer to adjust the size of the triangle: 6
*
**
***
****
*****
******

5. Program for using Single Dimensional Arrays

import java.util.Scanner;
public class ArrayInputOutput {
public static void main(String[]
args) {
Scanner scanner = new Scanner(System.in);
// Input: Size of the array
System.out.print("Enter the size of the array:
"); int size = scanner.nextInt();
// Create the array with the specified
size int[] array = new int[size];
// Input: Elements of the array
System.out.println("Enter " + size + " elements for the
array:"); for (int i = 0; i < size; i++) {
System.out.print("Element " + (i + 1) + ":
"); array[i] = scanner.nextInt();
}
// Display the elements of the array
System.out.println("The elements of the array
are:"); for (int i = 0; i < size; i++) {
System.out.println("Element " + (i + 1) + ": " + array[i]);
}
scanner.close();
}
}
Output:
Enter the size of the array: 6
Enter 6 elements for the array:
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Element 6: 7
The elements of the array are:
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Element 6: 7

6. Program for using Two Dimensional Arrays

import java.util.Scanner;
public class TwoDimensionalArray {
// Method to create and initialize a 2D array
public static int[][] create2DArray(int rows, int
cols) { return new int[rows][cols];
}
// Method to fill the 2D array with user input
public static void fill2DArray(int[][] array, Scanner scanner) {
System.out.println("Enter the values for the 2D array:");
for (int i = 0; i < array.length; i++)
{ for (int j = 0; j < array[i].length;
j++) {
System.out.print("Enter value for position (" + i + "," + j + "):
"); array[i][j] = scanner.nextInt();
}
}
}
// Method to display the 2D array
public static void display2DArray(int[][] array) {
System.out.println("The 2D array is:");
for (int i = 0; i < array.length; i++)
{ for (int j = 0; j < array[i].length;
j++) { System.out.print(array[i][j]
+ " ");
}
System.out.println(); // Move to the next line after each row
}
}
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
// Input number of rows and columns
System.out.print("Enter number of rows:
"); int rows = scanner.nextInt();
System.out.print("Enter number of columns:
"); int cols = scanner.nextInt();
// Create the 2D array
int[][] array = create2DArray(rows, cols);
// Fill the 2D array with user input
fill2DArray(array, scanner);
// Display the 2D array
display2DArray(array);
// Close the scanner
scanner.close();
}
}

Output:
Enter number of rows: 3
Enter number of
columns: 2
Enter the values for the 2D
array: Enter value for position
(0,0): 2
Enter value for position (0,1): 3
Enter value for position (1,0): 4
Enter value for position (1,1): 5
Enter value for position (2,0): 6
Enter value for position (2,1):
7 The 2D array is:
23
45
67

Constructor: Used to initialize the objects with initial values. It's called when an instance of a
class is created.
Getters and Setters: Methods used to retrieve and update the value of a private field of a
class, providing controlled access.
7. Program for how to use a constructor to initialize an object and how to use getters
and setters to access and modify private fields.

public class Person {


// Private fields
private String
name; private int
age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge()
{ return age;
}
// Setter for age
public void setAge(int age) {
// You can add validation logic here
if(age > 0) {
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
// Main method to test the Person class
public static void main(String[] args) {
// Create a Person object using the
constructor Person person = new
Person("Rama", 25);
// Access fields using getters
System.out.println("Name: " +
person.getName()); System.out.println("Age: "
+ person.getAge());
// Modify fields using setters
person.setName("Sitha");
person.setAge(30);
// Access modified fields using getters
System.out.println("Updated Name: " +
person.getName()); System.out.println("Updated Age: " +
person.getAge());
// Try setting an invalid
age person.setAge(-5);
}
}

Output:
Name: Rama
Age: 25
Updated Name:
Sitha Updated Age:
30 Age must be
positive.

8. Reverse a String

import java.util.Scanner;
public class ReverseString
{
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = "";
for (int i = input.length() - 1; i>= 0; i--)
{ reversed += input.charAt(i);
}
System.out.println("Reversed string: " +
reversed); scanner.close();
}
}

Output:
Enter a string: Hello World!
Reversed string: !dlroW olleH

9. A program to check some constraints (final, static, access modifiers) using inheritance in
java.

class Sample
{
public int a=20; //instance variable of public type
private static int b=50; //static variable of private
type
public static final int CONST=60; //constant variable of public
type public static void method1() //static method
{
System.out.println("this is from class Sample as a static method ");
}
public void method2() //instance method
{
System.out.println("this is from class Sample as a instance method ");
}
private void method3() //instance method as private type
{
System.out.println("this is from class Sample as instance method ");
}
}
class SampleTest extends Sample //inheriting Sample class to SampleTest
{
public int d=100; //instance variable
private static int b=40; //static variable
/*public void method1() //static method can't be override
{
System.out.println("this is from class B as instance method");
}*/
public void method2() //instance method overriding
{
System.out.println("this is overridden method from class SampleTest");
}
public static void main(String args[])
{
SampleTest st=new SampleTest (); //object of SampleTest
System.out.println("the value of a is :"+st.a);
//System.out.println("the value of b from class Sample is :"+Sample.b); //not accessing a
private variable
System.out.println("the value of c is :"+Sample.CONST); //static variable accessing by class name
//Sample.CONST=90; // final variable can't be modified
System.out.println("the value of b from class SampleTest is
:"+SampleTest.b); System.out.println("the value of d is :"+st.d);
Sample.method1(); //accessing static method in class Sample
st.method2(); //accessing overriden method
//st.method3(); //can't accessing private method of class Sample
}
}

Output:
the value of a is
:20 the value of c
is :60
the value of b from class SampleTest is
:40 the value of d is :100
this is from class Sample as a static method
this is overridden method from class SampleTest

10. Use Eclipse or Net bean platform and acquaint yourself with the various menus.
Create a test project, add a test class, and run it. See how you can use auto
suggestions, auto fill. Try code formatter and code refactoring like renaming
variables, methods, and classes. Try debug step by step with a small program of
about 10 to 15 lines which contains at least one if else condition and a for loop.

Using Eclipse:
1. Download and Install Eclipse:
 Go to the Eclipse downloads page and download the Eclipse IDE for Java Developers.
 Install Eclipse by following the on-screen instructions.
2. Create a Test Project:
 Open Eclipse.
 Go to File > New > Java Project.
 Enter a project name (e.g., TestProject) and click Finish.
3. Add a Test Class:
 Right-click on the src folder in your project.
 Select New > Class.
 Enter a package name (e.g., com.example) and a class name (e.g., TestClass).
 Check the box to include the public static void main(String[] args) method.
 Click Finish.
4. Write and Run a Test Program:
 Open the TestClass.java file and add below code:
package com.example;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a number: ");
int num =
scanner.nextInt(); if (num
> 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is 5 or less");
}
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
scanner.close();
}
}
 Save the file and run it by right-clicking on the file and selecting Run As > Java
Application.
5. Use Autosuggestions and Autofill:
 Start typing code, and you will see Eclipse providing suggestions and autofill
options. For example, type Sys and press Ctrl+Space to see suggestions for System.
6. Code Formatting:
 Right-click on your Java file and select Source > Format to automatically format your
code according to the default style settings.
7. Code Refactoring:
 Right-click on a variable, method, or class name and select Refactor > Rename to
rename it across the entire project.
8. Debug Step-by-Step:
 Set a breakpoint by double-clicking on the left margin next to a line of code.
 Right-click on the file and select Debug As > Java Application.
 Use the debug perspective to step through the code, inspect variables, and control the
execution flow.
9. Run:
 To run the project Select run menu, click on the run (ctrl+F11).

Output:
Enter a number: 7
Number is greater than
5 Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
11.`Dog.java` (Inheritance and Polymorphism)
package
com.example.animal;
public class Dog
extends Animal {
public Dog(String
name, int age) {
super(name, age);
}
@Override
public void makeSound() {
System.out.println("Woof Woof");
}
}

`Cat.java` (Inheritance and Polymorphism)


package
com.example.animal;
public class Cat
extends Animal {
public Cat(String
name, int age) {
super(name, age);
}
@Override
public void makeSound() {
System.out.println("Meow Meow");
}
}

`Main.java`
package com.example.main;
import
com.example.animal.An
imal; import
com.example.animal.Do
g; import
com.example.animal.Cat
; public class Main {
public static void
main(String[] args) { Animal
myDog = new Dog("Buddy",
3); Animal myCat = new
Cat("Whiskers", 2);
System.out.println("Dog's Name: " +
myDog.getName()); System.out.println("Dog's Age: "
+ myDog.getAge()); myDog.makeSound();
System.out.println("Cat's Name: " +
myCat.getName()); System.out.println("Cat's Age: "
+ myCat.getAge()); myCat.makeSound();
}
}

Output:
Dog's Name:
Buddy Dog's
Age: 3
Woof Woof
Cat's Name:
Whiskers
Cat's Age: 2
Meow Meow

You might also like