0% found this document useful (0 votes)
2 views5 pages

Java Methods Tutorial Programs

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)
2 views5 pages

Java Methods Tutorial Programs

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/ 5

Java Methods Tutorial Programs

Introduction
Methods in Java help us write modular, reusable, and organized code. Instead of repeating code,
we put it inside a method and call it whenever needed.

Problem Statement
Without methods, code gets repetitive. With methods, we can reuse logic easily.
// Without method (repeated code)
public class WithoutMethod {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Sum = " + (a + b));

int x = 5, y = 15;
System.out.println("Sum = " + (x + y));
}
}

// With method (reusable)


public class WithMethod {
static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Sum = " + sum(10, 20));
System.out.println("Sum = " + sum(5, 15));
}
}

Method Syntax
General form of a method: returnType methodName(parameters) { body }
public class MethodSyntax {
static void displayMessage() {
System.out.println("This is a simple method.");
}
public static void main(String[] args) {
displayMessage();
}
}

Program: Sum of Two Numbers


A simple method that returns the sum of two integers.
public class SumExample {
static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Sum = " + sum(10, 20));
}
}

Program: Greetings
Method with no return type (void) that just prints a greeting.
public class Greeting {
static void greet() {
System.out.println("Hello! Welcome to Java.");
}
public static void main(String[] args) {
greet();
}
}

Returning Values
Methods can return values using the return statement.
public class ReturnValue {
static int getNumber() {
return 42;
}
public static void main(String[] args) {
int num = getNumber();
System.out.println("Returned: " + num);
}
}

Returning a String
Methods can also return strings.
public class ReturnString {
static String greetUser(String name) {
return "Hello " + name + "!";
}
public static void main(String[] args) {
System.out.println(greetUser("Abhishek"));
}
}

Parameters (Integer Function)


Passing integers into a method.
public class SquareExample {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
System.out.println("Square = " + square(5));
}
}

Parameters (String Function)


Passing strings into a method.
public class PrintName {
static void printName(String name) {
System.out.println("Your name is: " + name);
}
public static void main(String[] args) {
printName("Abhishek");
}
}

Program: Swap Two Numbers


Demonstrates pass-by-value in Java. Original variables remain unchanged.
public class SwapExample {
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("Inside method: a=" + a + ", b=" + b);
}
public static void main(String[] args) {
int x = 10, y = 20;
swap(x, y);
System.out.println("Outside method: x=" + x + ", y=" + y);
}
}

Program: Pass Value


Shows that primitive values are passed as copies.
public class PassValue {
static void changeValue(int x) {
x = 99;
System.out.println("Inside method: x=" + x);
}
public static void main(String[] args) {
int a = 10;
changeValue(a);
System.out.println("Outside method: a=" + a);
}
}

Program: Change Value in Array


Arrays are objects, so modifications affect the original array.
public class ChangeArray {
static void change(int[] arr) {
arr[0] = 99;
}
public static void main(String[] args) {
int[] nums = {10, 20, 30};
change(nums);
System.out.println("After change: " + nums[0]);
}
}

Method Scope
Variables inside a method are only accessible within that method.
public class MethodScope {
static void show() {
int x = 10;
System.out.println("x = " + x);
}
public static void main(String[] args) {
show();
// System.out.println(x); // Error: x not visible here
}
}

Block Scope
Variables declared inside a block { } exist only inside that block.
public class BlockScope {
public static void main(String[] args) {
if (true) {
int a = 5;
System.out.println("Inside block: a=" + a);
}
// System.out.println(a); // Error: a not visible here
}
}
Loop Scope
Variables inside a loop exist only within that loop.
public class LoopScope {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("i=" + i);
}
// System.out.println(i); // Error: i not visible here
}
}

Shadowing
Local variable with the same name as class variable shadows it.
public class ShadowingExample {
static int x = 50;
public static void main(String[] args) {
System.out.println("Class variable x=" + x);
int x = 20; // shadows class variable
System.out.println("Local variable x=" + x);
}
}

Variable Arguments (Varargs)


Method that can take multiple arguments.
public class VarargsExample {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
public static void main(String[] args) {
System.out.println("Sum = " + sum(10, 20, 30, 40));
}
}

Method Overloading
Same method name, different parameter types.
public class OverloadingExample {
static int sum(int a, int b) {
return a + b;
}
static double sum(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(sum(10, 20));
System.out.println(sum(10.5, 20.5));
}
}

Q1: Prime Number


Check if a number is prime.
public class PrimeCheck {
static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPrime(29) ? "Prime" : "Not Prime");
}
}

Q2: Armstrong Number


Check if a number is an Armstrong number.
public class ArmstrongCheck {
static boolean isArmstrong(int n) {
int sum = 0, temp = n;
while (n > 0) {
int digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}
return sum == temp;
}
public static void main(String[] args) {
System.out.println(isArmstrong(153) ? "Armstrong" : "Not Armstrong");
}
}

Q3: Print All 3-digit Armstrong Numbers


Prints all Armstrong numbers between 100 and 999.
public class ArmstrongNumbers {
static boolean isArmstrong(int n) {
int sum = 0, temp = n;
while (n > 0) {
int digit = n % 10;
sum += digit * digit * digit;
n /= 10;
}
return sum == temp;
}
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
}
}

Outro
Summary: Methods help write modular code. We saw parameters, return types, scope, varargs,
overloading, and practice problems like Prime and Armstrong numbers.

You might also like