Java Programs Test
Java Programs Test
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 {
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:
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;
scanner
/ Close the
Sc.close();
/* 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.
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;
details
1/ Method to display student
void display () {
+ name + Age: + age) ;
System. out.println( "Name:
}
}
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() { :
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>
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;
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):
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();
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);
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;
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;
pA Administratorr CAWindowstsysterm32\ermd.exe
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;
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
long result = 1;
for (int i =1; i <= num; i++) {
result *= i;
return result;
Command Prompt
C:\>
Explanation
The nrogra!
Progran 10 Program to Display allPrime Numbers between Two Limits
import java.util.Scanner;
sc.close();