Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views33 pages

Java Programs Test

The document contains various Java programming examples demonstrating fundamental concepts such as data types, variable scopes, string operations, control structures, inheritance, exception handling, and polymorphism. Each program includes code snippets along with expected outputs, covering topics like method overloading, constructor overloading, and the life cycle of applets. The document serves as a comprehensive guide for beginners to understand and implement basic Java programming techniques.

Uploaded by

bookuser2006
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)
10 views33 pages

Java Programs Test

The document contains various Java programming examples demonstrating fundamental concepts such as data types, variable scopes, string operations, control structures, inheritance, exception handling, and polymorphism. Each program includes code snippets along with expected outputs, covering topics like method overloading, constructor overloading, and the life cycle of applets. The document serves as a comprehensive guide for beginners to understand and implement basic Java programming techniques.

Uploaded by

bookuser2006
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/ 33

6.

30
Java Programming

Program 7 Program to display "Hello World" and display the size of all the Data Types.
public class DataTypeSize {
public static void main(String[] args) {
1/ Displaying "Hello World"
System.out. println("Hello World");
1/ Displaying the size of all primitive data types in bits
System. out .println("Size of Primitive Data Types in Bits:") ;
System.out. println( "Byte: + Byte.SIZE + " bits");
System.out. println ("Short: " + Short. SIZE + " bits");
System.out. println(" Integer: + Integer.SIZE + " bits");
System.out. println("Long: + Long.SIZE + bits") ;
System.out. println("Float: + Float.SIZE + " bits");
System.out.println("Double: + Double.SIZE + bits");
System. out.println("Character: + Character.SIZE + " bits");
System.out.println ("Boolean: Size is JVM dependent (typically 8 bits) ");

Output
Hello World Float: 32 bits
Double: 64 bits
Size of Primitive Data Types in Bits:
Character: 16 bits
Byte: 8 bits
Short: 16 bits Boolean: Size is JVM dependent (typically 8 bits)
Integer: 32 bits
Long: 64 bits
the Usage of Static, Local and Instance Variables
Program 10 Program to Implement
public class varDemo {

// Instance Variable (belongs to an object)


int a = 10;

1/ Static Variable (belongs to the class)


static int b = 20;
public void display() {
LLocal Variable (declared inside a method)
int c = 30;

System. out . println("Instance Variable: + a);


System.out.println("Static Variable: + b);
System.out.println("Local Variable: + c);
}

public static void main(Stringl] args) {


// Creating an object to access instance variables
varDemo obj = new varDemo();
obj.display() ;

1/ Accessing static variable directly through class


System.out. println("Accessing Static Variable Without Object:" + varDemo.b);

Output:
Instance Variable: 10
Static Variable: 20
Local Variable: 30
Accessing Static Variable Without Object:2
Program 6 ProgramtoImplement String Operations:String Length, Concatenation andSubstring.
import java.util.Scanner:

public class StringOperations


public static void main(String[] args) {
Scanner sc = new Scanner(System. in);

/ Taking input for first string


System.out. print ("Enter the first string: ");
String str1 = SC.nextLine();

|/ Finding length of the string


System.out. println("Length of the first string: + str1.length());

// Taking input for second string


System.out.print ("Enter the second string: ");
String str2 = SC.nextLine() ;
1/ Concatenating strings
String str3 = str1.concat(str2); + str3);
System.out . println ("Concatenated String:
substring extraction
/7 Taking input for starting index for substring:
");
("Enter the
ystem. out. print
int startIndex = sc.nextInt(); substring: );
("Enter the ending index for
ystem.Out.print
lnt endIndex = SC.nextInt 03
6
1/ Extracting substring
if (startIndex >= e && endIndex <= str3.length() && startIndex < endIndex) { In
String substr = str3.substring(startIndex, endIndex); exa
System.out. println ("Extracted Substring: " + subStr); col
} else { ty
System.out. println ("Invalid index values for substring. ");

sc.close(); W
} pi
}
Output: d
Enter the first string: Skyward
E
Length of the first string: 7
Enter the second string: Books
b
Concatenated String: SkywardBooks
Enter the starting index for substring: 7
T
Enter the ending index for substring: 11
Extracted Substring : Book
Control Structures 4.7

Program 3 Program to Find the Maximum of Three Numbers Using Else If Statements.
import java.util.sScanner;

nublic class Largest {


nublic static void main(Stringl] args) {
|/ Create Scanner object to read input
Scanner sc = new Scanner(System.in);

I/ Read three numbers from the user


System. out . print ("Enter first number: ");
int a = SC.nextInt();

System.out .print ("Enter second number: ");


int b = sc.nextInt();

System.out. print("Enter third number: ");


int c = SC.nextInt (O;

number using if-else-if ladder


// Determine the largest
if (a >= b && a >= c)
largest number. ");
System.out. println(a +" is the
else if (b >= c) largest number."):
System.out.println(b + " is the
else number."):
out.println(c + " is the largest
System.

scanner
/ Close the
Sc.close();

using an if-else-if ladder


Program 1 Program to Check whether the Number is Odd or Even.
mport java . util. Scanner;
public class EvenOdd { Output

public static void main(String args[]) { Enter Number:


Scanner sc = neW 28

/* To read number */
Scanner(System.in); Number is Even
System. out.println("Enter Number: "):
int num = Sc.nextInt();
if(num % 2 == 0)
System.out. println( "Number is Even ");
else
.out.println("Number is Odd"):
}

Explanation
arguments pasSsed d
Constructor, Parameterized Constructor and
No-arg
Program to Implement
Program 6 Constructor Overloading.

public class ConsDemo {

variables */
/* Declare tWo instance
int i,j
Constructor with no arguments - No-arg Constructor */
/*
ConsDemo () {
i-10;
j=20;

Constructor */
/* Constructor with one argument - Parameterized
ConsDemo (int a) {
i=a;
j=20;

/* Constructor with two arguments - Parameterized Constructor*/


ConsDemo(int a, int b) {
i=a;
j=b;
void display (){
System.out.println (" i - "+i):
System. out . println(" j = "+j);

public static void main(String args[]) {


ConsDemo al = new ConsDemo(); 1/ calls no argument constructor
/ calls constructor with one argument
ConsDemo a2 = new ConsDemo(11);
/ calls constructor with two arguments
ConsDemo a3 = new ConsDemo(111, 222) ;
al.display();
a2.display ();
a3.display();
Program 5 Program to Implement Array of Objects
I/ Class representing a Student
Output
class Student {
Name: Srikanth, Age: 20
String name; Name: Priya, Age: 22
int age; Name: Rahul, Age: 19
1/ Constructor
Student(String name, int age) {
this.name = name;
this.age = age;

details
1/ Method to display student
void display () {
+ name + Age: + age) ;
System. out.println( "Name:
}

public class ArrayofObjects {


main(String[] args) {
public static void
store Student objects
1/Creating an array to
[3];
Student[] students = new Student Student objects
array elements with
1/Initializing theStudent("Srikanth", 20);
students [o] = new
Student("Priya", 22);
students [1] = new
Student("Rahul", 19);
students [2] = new
Displaying the student details
// {
students.length; i++)
(int i = 0; i <
for students [i] .display();

}
Program 1 Program to Implement Single Inheritance
class X {
int i;

void functionX () {
System. out .println(" In Super Class: i = " + i);
"+j);// Error
17 System.out. println(" In Super Class: j =
}
}
Output
public class Y extends X In Sub Class: j = 20
int j; In Sub Class: i = 30
In Super Class: i = 30
void functionY() { :

System.out.println(" In Sub Class: j= : + j);


System.out. println(" In Sub Class: i= + i);

public static void main(String args[]) {


Y y1 = new Y0;
y1.j = 20;
y1.i = 30;
y1. functionY();
y1. functionX();
Program 3 Program to Demonstrate Multiple Inheritance Using Interface.
interface XYZ {
public void functionX O; Output
} void functionX()
void functionM()
interface MSD { void functionP()
public void functionM();
}
interface POR extends XYZ, MSD {
public void functionP() ;

class ABC implements POR {


public void functionX() {
System.out. println (" void functionX()");

public void functionM() {


System.out. println (" void functionM()");

public void functionP() {


System. out.println(" void functionP()");

class InterfaceMulti {
publíc static void main (String args[]) {
ABC al = new ABC();
al.functionX();
al.functionM();
a1.functionP() ;
Program 1 Java Program to Implement the Life Cycle of an Applet
import java.applet . Applet;
import java. awt.Graphics;

*/
/* <APPLET CODE="AppletLifeCycle.Class" WIDTH=300 HEIGHT=200> </APPLET>

public class Applet LifeCycle extends Applet {


public void init() {
System.out.println ("Applet Initialized"):

public void start() {


System.out.println("Applet Started");
}
public void stop() {
System.out . println("Applet Stopped" ) ;
}
public void destroy() {
System. out .println("Applet Destroyed" );
}
public void paint (Graphics g) {
g.drawstring("Applet Life Cycle Demo" 20, 20);
Output:

X
Applet Viewer: Appletl..
Applet
Applet Life Cycle Demo

Applet started.
Program 1 Program to Demonstrate a Division by Zero Exception
import java.util., Scanner; (ArithmeticException)
public class DivisionbyZeroDemo {
public static void main (String[] args) {
Scanner scanner = new Scanner(System. in);
System.out.print("Enter the value of a: ");
int a = Scanner.nextInt();
System.out.print( "Enter the value of b: ");
int b = Scanner.nextInt (); / If b is 0, it will cause an issue
try {
int result a / b; // May throw ArithmeticException if b = 0
System.out.println("Result: + result) ;
} catch (ArithmeticException e) {
allowed. " );
System. out.println("Error: Division by zero is not

Scanner.close();

Output
20 Enter the value of a: 10
Enter the value of a:
1O Enter the value of b: 0
Enter the value of b:
Error: Division by zero is not allowed.
Result: 2
Program to add two integers and two float numbers. When no arguments are supplied,
Program 5
givea default values to calculate the sum. Use method overloading
class Addition {
1/ Method to add two integers
int add(int a, int b) {
return a + b;

/ Method to add two floating-point numbers


float add(float a, float b) {
return a + b;
1/Method with no arguments, using default values
int add() {
int a = 5; // Default values
int b =10;
return a + b;
}

public static void main(String[] args) {


Addition obj = new Addition();

// Adding two integers


System. out . println("Sum of 10 and 20 (integers): " + obj.add(10, 20));
// Adding two float numbers
System. out. println("Sum of 5.5 and 2.3 (floats): + obj.add (5.5f, 2.3f));
// Adding using default values
System. out. println("Sum using default values : + obj.add());

Output:
Sum of 10 and 20 (integers) : 30
Sum of 5.5 and 2.3 (floats) : 7.8
Sum using default values : 15
subclass object.
Method Overriding)
Program 7 Program to Demonstrate Runtime Polvmorpbism (Using
import java.util.Scanner;

1/ Parent class
class Animal {
void makeSound ( ) {
System.out. println("An imal makes a sound");
}

|/ Subclass 1 - Dog
class Dog extends Animal {
@Override
void makeSound() {
System.out.println( "Dog barks");

1/ Subclass 2 - Cat
class Cat extends Animal {
@Override
void makeSound() {
System.out. println( "Cat meows");
}

1/ Main class
public class RuntimePolymorphismExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System. in);
|| Asking user to choose an option
System.out. println("Choose an animal:");
System.out. println("1. Dog");
System.out . println("2. Cat");
"):
System. out. print("Enter your choice (1 or 2):

int choice = scanner.nextInt();


reference
Animal myAnimal; // Parent class

choice
1/Assigning object based on user
if (choice ==
1) {
myAnimal = new Dog();
} else if (choice == 2) {
myAnimal = new Cat();
} else {
to Animal. ");
System.out.println (" Invalid choice! Defaulting
myAnimal = new Animal();

// Calling the overridden method


myAnimal.makeSound();

Scanner.close();

Output :
Choose an animal:
Choose an animal:
1. Dog 1. Dog
2. Cat
2. Cat
2): 2
Enter your choice (1 or
Enter your choice (1 or 2): 1
Cat meows
Dog barks
key
Program 5 Progran to Catch NegativeArraySizeException.
import java.util. Scanner;
public class NegativeArraySizeDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System. in);

System.out.print("Enter the size of the array: ");


int size = scanner. nextInt (); // If size is negative, it will cause an issue
try {
int [] arr =new int[size]; // May throw NegativeArraySizeException if size <@
System. out . println("Array of size + size + created successfully.");
} catch (NegativeArraySizeException e) {
System. out . printin("Error: Array size cannot be negative.");
}
Scanner.close();
}

Output
Enter the size of the array: 10 Enter the size of the array: -5
Array of size 10 created successfully. Error: Array size cannot be negative.
Explanation:
Program 6 Program to Handle NullPointerException and Use Finally Block to Display a Message.
import java.util.Scanner;

public class NullPointerExceptionDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System. in);

System. out . print("Enter a string (or press Enter to leave it empty): ") ;
String str =
Scanner.nextLine(); // Accept input from user
if (str.isEmpty()) {
str =null; // Simulating a null reference
try {
|/ May throw NullPointerException
System.out.printIn (" Length of the string: " + str. length (0);
} catch (NullPointerException e) {
System.out. println("Error: Entered string is empty or NULL.");
} finally {
System. out. println("Execution completed. Thank you!");

scanner.close();

Output
Run 1
Enter a string (or press Enter to leave it empty): Srikanth
Length of the string: 8
Execution completed. Thank you!

Run 2
Enter a string (or press Enter to leave it empty):
Error: Entered string is empty or NULL.
Execution completed. Thank you!
modularity, and access control within a Java application.
Program 5 Creating and Importing a User-Defined Packages
Let ussee how to create, compile and execute the java classes with user defined packages.
Step 1: Create a Program in the pack1 Package
Let us create a program that belongs to the packl package.
package packl;

public class packageExample

public void packMethod() {


System. out. println(" I'm packMethod() in pack1.packageExample");

Step 2: Compile the Program and Create the pack1 Directory


Save this file as PackageExample.java in C:\, Compile the program using the -d option, which
automatically creates the packl directory.
The compilation command is:
javac -d packageExample. java
(The dot. after -d represents the current directory.)
Aftercompilation, the pack 1directory is automatically created,and the compiled PackageExanple.
class file is placedinside it.
Ond FaCkaqes

pA Administratorr CAWindowstsysterm32\ermd.exe

CEN>Javaed pac kayeExanp lejava


Vo lune in drive Chas no labe l
Vo lune Serial Nunber is 94PE 50B6
Directory of CEN
03 2010 D4:33 AUTOEXEC. BAT
042010 99 50 <DIR> BP Checkout
10-032018 B4:33 8 CONFIG.SYS
B3-201e 20:10 <DIR> de 11
36-201O 19:17 38 des.c
2010 1306 <DIR> Dev Cpp
2010 11:25 <DIR) Downloads
32010 11:09 <DIR> eclipse
3201O 20:12 KDIR) Intel
0420i0 92#14 <DIR> METAINF
03-2010 21139 KDIR> 0raclexe
0920i0 12:05 KDIR> packi
Le-09 2010 11:40 15 pcge Examp lejava
14 072909 08:50 KDIR) PerfLogs
19-062016 1610 <DIR> Progran Files
26 08-2010 18:24 Progran Files (c86)
20-06--2010 19:15 38 src c
12-062010 15:34 51 student in.dat
12-06-2010 15:34 131 student out dat
D7-042010 02:26 <DIR> tenp
07 04-2010 02:16 325 Test war
09-04-2010 90:19 4.608 testxls
18-04-2010 13:34 <DIR> turbo
99-03--2010 18:58 <DIR> Users
29-08-2010 09 :37 <DIR> Windows
9 File (s) 5,348 bytes
16 Dir(s) 58.467,622,912 bytes free

The compiler automatically creates the pack1 directory. The PackageExample.class file will also
be stored inside this directory, as shown below.
oIS Administrator: CAWindows\system32\cmd.exe

C:>cd pack1
C:Apack1>dir
Vo lune in drive C has no label.
Vo lune Seria1 Number is 04FE-50B6
Directory of C:ypack1
10-092010 12:05 <DIR)
19-09-2010 12:05 <DIR
9-092010 12:05 454 package Example,class
1 File (s) 1E bytes
2 Dir<s) 58.46?463,168 bytes ree

Step 3: Create Another File in the pack2 Package and Import packi Package
Create another file called packageDemo.java in pack2package as shown below.
package pack2;
import packl.*;
public class packageDemo {
public static void main(String args[]) {
packageExample obj = new packageExample();
obj.packMethod ();

In this file, We import allclasses from pack1 using import pack1.*;. We create an object of the
PackageExample class and call the packMethod() method.
Step 4: Compile the pack2 Package
Save this file as PackageDemo.java in C:\. Compile the program using the -d option.
javac -d PackageDemo.java
After compilation, the pack2 directory is automatically created, and the PackageDemo.class file
is stored inside it.

8Administrator: CAWindows\system32cmd.exe

G:packi>cd
C:xjav ac -d pac kage Demojava
C:dir
in drive C has no labe 1.
Vo aneSerial Nånber is 04PE-50B6
Directory uf C:S
18-93-201 94:33 0 AUTOEXEC.BAT
B7-04-2010 09:50 <DIR> BE-Che ckout
0-03-201 94:33 9 CONFIG.SYS
39-63-2010 20:1O <DIR> de l l
20-06-201Ø 19:12 38 des .c
18-94-2010 13:06 <DIB Dey-Cpp
H3-03-2016 11:25 <D Downloads
13-93-2019 11:99 <DIR> eclipse
09-93-2010 20:12 <DI R> Intel
37-04-2019 02:14 <DIR) META-INP
13-93-2010 21:39 IR>
DIR
Iexe
18-09-201 12: 5 pack1
10-09-2019 12 :14 <DIR> pack2
18-09-201 11:52 185 ao«ge Denojava
10-9-2910 11:4D 157 pac kageExanple-java
14-0?-2009 98:50 <DIB> Perf Logs
19--062010 16:1Ø <DIR> Progan Files
26-B8-201A 18:24 <DIR> Progran Piles <x86)
20-06-201 19:15 38 src -c
12-0G-2010 15:34 51 st udent_in .dat
12-06-2016 15:34 131 student out.dat
7-04-2016 02:26 <DIR tem
Eenp
37-04-2010 02:16 325Test. war
-2016 B9:19 4,608 test.xls
39-2019
18
39 83 201
29-48-201O
1334
18:58
G9 :3?
<DIR>
<DIR
<DIR
10 Fi le <s>
turb0
Users
Windows
5.533 bytes
1? Dir(s) 58,467.323,984 bytes free
C:>cd pack2
Cpack2>d ir
Lunein driive C has no label.
Vo lune Serial NuL her is 04FE-50B6
Directory of C:pack2
19-092010 12:14 <DIR
I092016 12:14 <DIR
18-49 2019 12:14 34? package Deno c l a s
1 File (s) hyte
2Di(s)58,46?,323,904 bytesree
Step 5: Run the Program
The compilation of both classes is now complete. To execute the PackageDemo class, go to the C:\
prompt and run the following command:
java pack2.packageDemo.java

This runs the PackageDemo class, which accesses the PackageExample class from the pack1
package and calls the packMethod() method.

Administrator: CAWindows\system32\cmd.exe
C:)java pack2 .package Deno
I'm pac kMe t ho d()in pack1 - pac kageExanple
Program 9 Program to Check whether a Number is a Palindrome or Not
import java.util.Scanner;

public class Palindrome Check {


public static void main(String[] args) {
Scanner sc = new Scanner(System. in);
System.out. print("Enter a number: ");
int num = sc.nextInt (0;
int originalNum = num, reverse = 0, remainder;

while (num > 0) f


remainder = num % 10;
reverse = reverse * 10 + remainder;
num /= 10;

if (originalNum == reverse)
System. out.println(originalNum + is a palindrome.");
else
System.out.println (originalNum + is not a palindrome. ");

sc.close();

Output:
Enter a number: 121 Enter a number: 123
121 is a palindrome. 123 is not a palindrome.
6.43
Arrays, Strings and Predefined Classes

Program Program to Find the Factorial of a List of Numbers provided as Command-line


10 Arguments

public class FactorialCommandLine {


I/ Method to calculate factorial
nublic static long factorial (int num) {
if (num < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative
numbers. ");

long result = 1;
for (int i =1; i <= num; i++) {
result *= i;

return result;

public static void main(String[] args) {


I/ Check if command-line arguments are provided
if (args.length == 0) {
System.out.println("Please provide numbers as command-line arguments.");
return;

1/ Loop through all provided arguments


for (String arg : args) {
try {
17 Convert string to integer
int number = Integer.parseInt(arg);
I| Calculate factorial
long fact = factorial(number);
1/ Print the result
System.out. println("Factorial of " + number + " is: " + fact);
}catch (NumberFormatException e) {
+ arg + " Please enter a valid
System.out .println (" Invalid input:
integer.");
}catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
Output

Command Prompt

C:\JAVA>javac FactorialCommandLine. java


C:\JAV

C:\>java cp C:\JAVA FactorialCommandLine 2 5 10


Factorial of 2 is: 2
Factorial of 5 is: 120
Factorial of 10 is: 3628800

C:\>

Explanation
The nrogra!
Progran 10 Program to Display allPrime Numbers between Two Limits
import java.util.Scanner;

public class PrimeNumbersBetweenLimits {


public static void main(String[ ] args)
Scanner sc = new Scanner(System. in) ;

/7 Read the lower and upper limit from user


System.out .print("Enter the lower limit: "):
int lower = sc. nextInt ();

System.out. print("Enter the upper limit: "):


int upper = sC.nextInt () ;

System.out.println("Prime numbers between " + lower + and + upper + " :");

/ Loop through the range and check for prime numbers


for (int num = lower; num <= upper; num++) {
if (isPrime (num) ) {
System. out. print (num + ");

sc.close();

// Function to check if a number is prime


public static boolean isPrime (int n) {
if (n < 2) return false;
for (int i = 2; i <= Math.sqrt (n); i++) {
if (n % i == )
return false;
}
return truej
Output:
Enter the lower limit: 1 Enter the lower limit: 20
Enter the upper limit: 10 Enter the upper limit: 50
Prime numbers between 1 and 1O are: Prime numbers between 20 and 50 are:
2 35 7 23 29 31 37 41 43 47
Interface.
Program 5 Java Program to Create a Thread using Runnable
class MyThread implements Runnable {
public void run() {
System. out.println(" run() started ");
for (int i = 1; i <= 10; i++) {
Output
System.out.println (" The value is : " + i); Main Thread started
} Main Thread Completed
System. out.println(" run() completed "); run() started
The value is: 1
The value is: 2
The value is: 3
The value is : 4
The value is : 5
public class ThreadRunnable {
The value is : 6
public static void main(String args[]) { The value is :7
System. out. println("Main Thread started"); The value is: 8
MyThread obj =new MyThread (); The value is : 9
The value is: 10
Thread t1 = new Thread(obj, "Thread 0ne"); run() completed
t1.start();
System. out.printIn( "Main Thread Completed" );
}
}
M Thread cass

You might also like