1
How to write a Java Program:
1. Create a Java File:
- Open your favorite text editor or IDE (like Notepad++, Eclipse, IntelliJ IDEA, or VS Code).
- Create a new file and save it as `HelloWorld.java`.
2. Write the Java Code:
- Type the following code into the file:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
3. Compile the Program:
- Open your command prompt (CMD) or terminal.
- Navigate to the directory where you saved `HelloWorld.java` using the `cd` command.
cd path\to\your\directory
- Compile the program using the `javac` (Java Compiler) command:
javac HelloWorld.java
- This command will generate a `HelloWorld.class` file in the same directory.
4. Run the Program:
- Run the compiled Java program using the `java` command:
java HelloWorld
- You should see the following output:
Hello, World!
Comments in Java: Comments are used to annotate the code and are ignored by the compiler.
// This is a single-line comment
/*
* This is a multi-line comment
* It spans multiple lines
*/
Variable Scope:
1. Local Variables:
- Declared inside a method or block.
- Accessible only within the method or block.
- Must be initialized before use.
Example:
import java.io.*;
class Variables
{
int localVar; // Instance variable
public void myMethod() {
int localVar = 5; // Local variable
System.out.println(localVar);
}
}
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
2
public class LocalVar
{
public static void main(String[] args)
{
Variables v1=new Variables();
v1.myMethod();
}
}
2. Instance Variables:
- Declared inside a class but outside any method.
- Each object of the class has its own copy.
- Initialized to default values if not explicitly initialized.
Example:
import java.io.*;
class Variables
{
int instanceVar; // Instance variable
public void myMethod()
{
System.out.println(instanceVar); // Default value is 0
}
}
public class InstanceVar
{
public static void main(String[] args)
{
Variables v1=new Variables();
v1.myMethod();
}
}
3. Static Variables (Class Variables):
- Declared with the `static` keyword inside a class but outside any method.
- A single copy is shared among all instances of the class.
- Initialized to default values if not explicitly initialized.
Example:
import java.io.*;
class Variables
{
static int staticVar; // Static/Class variable
public void myMethod()
{
System.out.println(staticVar); // Default value is 0
}
}
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
3
public class StaticVar
{
public static void main(String[] args)
{
Variables v1=new Variables();
v1.myMethod();
}
}
Arrays in Java:
Program demonstrates the creation, initialization, and iteration through an Array of integers:
public class ArrayExample {
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5};
System.out.println("Elements of myArray:");
for (int i = 0; i <myArray.length; i++)
{
System.out.println(myArray[i]);
}
System.out.println("MyArray First Element: "+myArray[0]);
System.out.println("MyArray Third Element: "+myArray[2]);
}
}
Java Operators and Expressions:-
Sum of two variables:
public class Sum {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
public class AllOperators {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x + y);
System.out.println(x - y);
System.out.println(x * y);
System.out.println(x / y);
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
4
System.out.println(x % y);
System.out.println(x > y); // returns true, because 5 is higher than 3
System.out.println(x != y); // returns true because 5 is not equal to 3
System.out.println(x > 3 && x < 10); // returns true because 5 is greater than 3 AND 5 is
less than 10
x *= 3;
System.out.println(x);
x++;
System.out.println(x);
y--;
System.out.println(y);
}
}
Control statements in Java:
Control statements in Java are constructs that determine the flow of program execution. They
allow you to control how different parts of your program are executed based on conditions,
loops, and branching. They help you make decisions, loop over data, and execute code
selectively.
Some common types of control statements in Java, along with examples:
1. if Statement:
The `if` statement is used for conditional execution. It executes a block of code only if a
specified
condition is true.
Example:
public class MyClass
{
public static void main(String args[])
{
int x = 10;
if (x > 5)
{
System.out.println("x is greater than 5");
}
}
}
2. if-else Statement:
The `if-else` statement allows you to execute one block of code if a condition is true and another
block
if the condition is false.
Example:
public class MyClass2
{
public static void main(String args[])
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
5
{
int x = 3;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}
}
}
3. if-else if-else Statement:
You can use the `if-else if-else` statement to check multiple conditions in sequence.
Example:
public class MyClass3
{
public static void main(String args[])
{
int x = 7;
if (x < 5) {
System.out.println("x is less than 5");
} else if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is equal to 5");
}
}
}
4. switch Statement:
The `switch` statement is used to perform different actions based on different conditions. It's
especially
useful when you have a single value to compare against multiple possible values.
Example:
public class SwitchCase
{
public static void main(String args[])
{
int dayOfWeek = 3;
switch (dayOfWeek=2) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ....
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
6
default:
System.out.println("Unknown day");
}
}
}
5. for Loop:
The `for` loop is used to iterate over a range of values. It has an initialization step, a condition to
check, and an update step.
Example:
public class ForLoop
{
public static void main(String args[])
{
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}
6. while Loop:
The `while` loop continues to execute a block of code as long as a specified condition is true.
Example:
public class WhileLoop
{
public static void main(String args[])
{
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
}
}
7. do-while Loop:
The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code is
executed at
least once.
Example:
public class DoWhileLoop
{
public static void main(String args[])
{
int count=0;
do {
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
7
System.out.println("Count: " + count);
count++;
} while (count < 5);
}
}
8. break,continue and return Statements:
The `break` statement is used to exit a loop prematurely, and the `continue` statement is used to
skip
the current iteration and move to the next one within a loop.
Example:
public class BCR
{
public static void main(String args[])
{
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
}
}
Program which illustrate the control statements in java:
public class ControlStatementsExample {
public static void main(String[] args) {
int num1 = 20;
int num2 = 10;
// If-Else Statement
if (num1 > num2) {
System.out.println("num1 is greater than num2");
} else {
System.out.println("num2 is greater than or equal to num1");
}
// For Loop
System.out.print("Numbers from 1 to 5: ");
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println(); // Move to the next line
// While Loop
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
8
int count = 3;
System.out.print("Countdown: ");
while (count > 0) {
System.out.print(count + " ");
count--;
}
System.out.println();
// Do-While Loop
int n = 1;
System.out.print("Numbers from 1 to 5 using do-while: ");
do {
System.out.print(n + " ");
n++;
} while (n <= 5);
System.out.println();
// Switch Statement
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
default:
dayName = "Unknown";
}
System.out.println("Day " + day + " is " + dayName);
}
}
Display Even numbers between 1 -100:-
public class EvenNumbers {
public static void main(String[] args) {
System.out.println("Even Numbers from 1 to 100:");
// Loop through numbers from 1 to 100
for (int i = 1; i <= 100; i++) {
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
9
// Check if the number is even using the modulo operator
if (i % 2 == 0) {
// If it's even, print it
System.out.print(i + " ");
}
}
}
}
Display Odd numbers between 1 -100:-
public class OddNumbers {
public static void main(String[] args) {
System.out.println("Odd Numbers from 1 to 100:");
// Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
// Check if the number is odd (remainder when divided by 2 is not 0)
if (i % 2 != 0) {
System.out.print(i + " ");
}
}
}
}
Program of Factorial number:-
class Factorial{
static int fact(int number){
int f=1;
for(int i=1;i<=number;i++){
f=f*i;
}
return f;
}
public static void main(String args[]){
int result=fact(5);
System.out.println("Factorial of 5="+result);
}
}
Program of Fibonacci series:-
class Fibonacci{
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
10
public static void main(String[] args)
{
int n=10,i,f0=1,f1=1,f2=0;
for(i=1;i<=n;i++)
{
f2=f0+f1;
f0=f1;
f1=f2;
f2=f0;
System.out.println(f2);
}
}
}
Display Prime numbers between 1 -100:-
public class PrimeNumbers {
public static void main(String[] args) {
System.out.println("Prime numbers between 1 and 100 are:");
for (int i = 2; i <= 100; i++) { // Start from 2 as 0 and 1 are not prime
if (isPrime(i)) {
System.out.print(i + " ");
// Function to check if a number is prime
public static boolean isPrime(int number) {
if (number <= 1) { // 0 and 1 are not prime numbers
return false;
// Check for divisibility from 2 up to the square root of the number
for (int i = 2; i <= Math.sqrt(number); i++) {
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur
11
if (number % i == 0) {
return false; // If divisible, it's not prime
return true; // If no divisors found, it's prime
Java Basic Programs By A.Harish, Asst. Prof, CSE KITS-Singapur