Sample Java Program
class HelloWorld {
public static void main(String[] args)
{
[Link]("Hello, World");
}
}
Single dimensional array in java
public class ArrayExample {
// Main Function
public static void main(String[] args)
{
// Declare and initialize an array of integers
int[] numbers = { 10, 20, 30, 40, 50 };
// Print the elements of the array
[Link]("Original Array:");
printArray(numbers);
// Accessing elements of the array
[Link]("\nElement at index 2: " + numbers[2]);
// Output: 30
// Modifying an element of the array
numbers[3] = 45;
// Print the modified array
[Link]("\nModified Array:");
printArray(numbers);
// Calculating the sum of elements in the array
int sum = calculateSum(numbers);
[Link]("\nSum of elements in the array: " + sum);
// Output: 145
}
// Method to print the elements of an array
public static void printArray(int[] arr)
{
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
[Link]();
}
// Method to calculate the sum of elements in an array
public static int calculateSum(int[] arr)
{
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
}
Java program of For Each Loop
//An example of Java for-each loop
class ForEachExample1{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
[Link](i);
}
}
}
Java class and objects
class Lamp {
// stores the value for light
// true if light is on
// false if light is off
boolean isOn;
// method to turn on the light
void turnOn() {
isOn = true;
[Link]("Light on? " + isOn);
// method to turnoff the light
void turnOff() {
isOn = false;
[Link]("Light on? " + isOn);
}
}
public class Main {
public static void main(String[] args) {
// create objects led and halogen
Lamp led = new Lamp();
Lamp halogen = new Lamp();
// turn on the light by
// calling method turnOn()
[Link]();
// turn off the light by
// calling method turnOff()
[Link]();
}
}
Java program example of overloading methods
class Adder {
// Method to add two integers
static int add(int a, int b) {
return a + b;
}
// Method to add three integers
static int add(int a, int b, int c) {
return a + b + c;
}
}
public class TestOverloading1 {
public static void main(String[] args) {
// Calling the add method with two integers
[Link]([Link](11, 11)); // Output: 22
// Calling the add method with three integers
[Link]([Link](11, 11, 11)); // Output: 33
}
}
Java program example of Constructors
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Java program example of multiple inheritance
interface Backend {
// abstract class
public void connectServer();
}
class Frontend {
public void responsive(String str) {
[Link](str + " can also be used as frontend.");
}
}
// Language extends Frontend class
// Language implements Backend interface
class Language extends Frontend implements Backend {
String language = "Java";
// implement method of interface
public void connectServer() {
[Link](language + " can be used as backend language.");
}
public static void main(String[] args) {
// create object of Language class
Language java = new Language();
[Link]();
// call the inherited method of Frontend class
[Link]([Link]);
}
}
Creating a Package in java program
// Name of package to be created
package data;
// Class to which the above package belongs
public class Demo {
// Member functions of the class- 'Demo'
// Method 1 - To show()
public void show()
{
// Print message
[Link]("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
[Link]("Hello");
}
}
// accessing the package
// Name of the package
import data.*;
// Class to which the package belongs
class ncj {
// main driver method
public static void main(String arg[])
{
// Creating an object of Demo class
Demo d = new Demo();
// Calling the functions show() and view()
// using the object of Demo class
[Link]();
[Link]();
}
}
Java program of exception handling using try..catch
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
Multithreading by implementing runnable interface
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
[Link](
"Thread " + [Link]().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
[Link]("Exception is caught");
}
}
}
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
[Link]();
}
}
}
File handling in java by random access file
import [Link];
import [Link];
public class RandomAccessFileExample {
static final String FILEPATH ="[Link]";
public static void main(String[] args) {
try {
[Link](new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
[Link]();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
[Link](position);
byte[] bytes = new byte[size];
[Link](bytes);
[Link]();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
[Link](position);
[Link]([Link]());
[Link]();
}
}
// Simple Example of AWT Frame by inheritance
import [Link].*;
class First extends Frame{
First(){
Button b=new Button("click me");
[Link](30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
//Student Registration form created by using AWT Controls
// Java program to implement
// a Simple Registration Form
// using Java Swing
import [Link].*;
import [Link].*;
import [Link].*;
class MyFrame
extends JFrame
implements ActionListener {
// Components of the Form
private Container c;
private JLabel title;
private JLabel name;
private JTextField tname;
private JLabel mno;
private JTextField tmno;
private JLabel gender;
private JRadioButton male;
private JRadioButton female;
private ButtonGroup gengp;
private JLabel dob;
private JComboBox date;
private JComboBox month;
private JComboBox year;
private JLabel add;
private JTextArea tadd;
private JCheckBox term;
private JButton sub;
private JButton reset;
private JTextArea tout;
private JLabel res;
private JTextArea resadd;
private String dates[]
= { "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"11", "12", "13", "14", "15",
"16", "17", "18", "19", "20",
"21", "22", "23", "24", "25",
"26", "27", "28", "29", "30",
"31" };
private String months[]
= { "Jan", "feb", "Mar", "Apr",
"May", "Jun", "July", "Aug",
"Sup", "Oct", "Nov", "Dec" };
private String years[]
= { "1995", "1996", "1997", "1998",
"1999", "2000", "2001", "2002",
"2003", "2004", "2005", "2006",
"2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2018",
"2019" };
// constructor, to initialize the components
// with default values.
public MyFrame()
{
setTitle("Registration Form");
setBounds(300, 90, 900, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
c = getContentPane();
[Link](null);
title = new JLabel("Registration Form");
[Link](new Font("Arial", [Link], 30));
[Link](300, 30);
[Link](300, 30);
[Link](title);
name = new JLabel("Name");
[Link](new Font("Arial", [Link], 20));
[Link](100, 20);
[Link](100, 100);
[Link](name);
tname = new JTextField();
[Link](new Font("Arial", [Link], 15));
[Link](190, 20);
[Link](200, 100);
[Link](tname);
mno = new JLabel("Mobile");
[Link](new Font("Arial", [Link], 20));
[Link](100, 20);
[Link](100, 150);
[Link](mno);
tmno = new JTextField();
[Link](new Font("Arial", [Link], 15));
[Link](150, 20);
[Link](200, 150);
[Link](tmno);
gender = new JLabel("Gender");
[Link](new Font("Arial", [Link], 20));
[Link](100, 20);
[Link](100, 200);
[Link](gender);
male = new JRadioButton("Male");
[Link](new Font("Arial", [Link], 15));
[Link](true);
[Link](75, 20);
[Link](200, 200);
[Link](male);
female = new JRadioButton("Female");
[Link](new Font("Arial", [Link], 15));
[Link](false);
[Link](80, 20);
[Link](275, 200);
[Link](female);
gengp = new ButtonGroup();
[Link](male);
[Link](female);
dob = new JLabel("DOB");
[Link](new Font("Arial", [Link], 20));
[Link](100, 20);
[Link](100, 250);
[Link](dob);
date = new JComboBox(dates);
[Link](new Font("Arial", [Link], 15));
[Link](50, 20);
[Link](200, 250);
[Link](date);
month = new JComboBox(months);
[Link](new Font("Arial", [Link], 15));
[Link](60, 20);
[Link](250, 250);
[Link](month);
year = new JComboBox(years);
[Link](new Font("Arial", [Link], 15));
[Link](60, 20);
[Link](320, 250);
[Link](year);
add = new JLabel("Address");
[Link](new Font("Arial", [Link], 20));
[Link](100, 20);
[Link](100, 300);
[Link](add);
tadd = new JTextArea();
[Link](new Font("Arial", [Link], 15));
[Link](200, 75);
[Link](200, 300);
[Link](true);
[Link](tadd);
term = new JCheckBox("Accept Terms And Conditions.");
[Link](new Font("Arial", [Link], 15));
[Link](250, 20);
[Link](150, 400);
[Link](term);
sub = new JButton("Submit");
[Link](new Font("Arial", [Link], 15));
[Link](100, 20);
[Link](150, 450);
[Link](this);
[Link](sub);
reset = new JButton("Reset");
[Link](new Font("Arial", [Link], 15));
[Link](100, 20);
[Link](270, 450);
[Link](this);
[Link](reset);
tout = new JTextArea();
[Link](new Font("Arial", [Link], 15));
[Link](300, 400);
[Link](500, 100);
[Link](true);
[Link](false);
[Link](tout);
res = new JLabel("");
[Link](new Font("Arial", [Link], 20));
[Link](500, 25);
[Link](100, 500);
[Link](res);
resadd = new JTextArea();
[Link](new Font("Arial", [Link], 15));
[Link](200, 75);
[Link](580, 175);
[Link](true);
[Link](resadd);
setVisible(true);
}
// method actionPerformed()
// to get the action performed
// by the user and act accordingly
public void actionPerformed(ActionEvent e)
{
if ([Link]() == sub) {
if ([Link]()) {
String data1;
String data
= "Name : "
+ [Link]() + "\n"
+ "Mobile : "
+ [Link]() + "\n";
if ([Link]())
data1 = "Gender : Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2
= "DOB : "
+ (String)[Link]()
+ "/" + (String)[Link]()
+ "/" + (String)[Link]()
+ "\n";
String data3 = "Address : " + [Link]();
[Link](data + data1 + data2 + data3);
[Link](false);
[Link]("Registration Successfully..");
}
else {
[Link]("");
[Link]("");
[Link]("Please accept the"
+ " terms & conditions..");
}
}
else if ([Link]() == reset) {
String def = "";
[Link](def);
[Link](def);
[Link](def);
[Link](def);
[Link](def);
[Link](false);
[Link](0);
[Link](0);
[Link](0);
[Link](def);
}
}
}
class Registration {
public static void main(String[] args) throws Exception
{
MyFrame f = new MyFrame();
}
}
// Border layout
import [Link].*;
import [Link].*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]); // b2 will be placed in the South Direction
[Link](b3, [Link]); // b2 will be placed in the East Direction
[Link](b4, [Link]); // b2 will be placed in the West Direction
[Link](b5, [Link]); // b2 will be placed in the Center
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
//Menudemo by java swing
import [Link].*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
[Link](i1); [Link](i2); [Link](i3);
[Link](i4); [Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}}
Socket Programming using TCP
// Demonstrating Client-side Programming
import [Link].*;
import [Link].*;
public class Client {
// Initialize socket and input/output streams
private Socket s = null;
private DataInputStream in = null;
private DataOutputStream out = null;
// Constructor to put IP address and port
public Client(String addr, int port)
{
// Establish a connection
try {
s = new Socket(addr, port);
[Link]("Connected");
// Takes input from terminal
in = new DataInputStream([Link]);
// Sends output to the socket
out = new DataOutputStream([Link]());
}
catch (UnknownHostException u) {
[Link](u);
return;
}
catch (IOException i) {
[Link](i);
return;
}
// String to read message from input
String m = "";
// Keep reading until "Over" is input
while () {
try {
m = [Link]();
[Link](m);
}
catch (IOException i) {
[Link](i);
}
}
// Close the connection
try {
[Link]();
[Link]();
[Link]();
}
catch (IOException i) {
[Link](i);
}
}
public static void main(String[] args) {
Client c = new Client("[Link]", 5000);
}
}
// Demonstrating Server-side Programming
import [Link].*;
import [Link].*;
public class Server {
// Initialize socket and input stream
private Socket s = null;
private ServerSocket ss = null;
private DataInputStream in = null;
// Constructor with port
public Server(int port) {
// Starts server and waits for a connection
try
{
ss = new ServerSocket(port);
[Link]("Server started");
[Link]("Waiting for a client ...");
s = [Link]();
[Link]("Client accepted");
// Takes input from the client socket
in = new DataInputStream(
new BufferedInputStream([Link]()));
String m = "";
// Reads message from client until "Over" is sent
while ()
{
try
{
m = [Link]();
[Link](m);
}
catch(IOException i)
{
[Link](i);
}
}
[Link]("Closing connection");
// Close connection
[Link]();
[Link]();
}
catch(IOException i)
{
[Link](i);
}
}
public static void main(String args[])
{
Server s = new Server(5000);
}
}
// example of printing message 10 times by jsp
<html>
<head>
<title>JSP Print Message Example</title>
</head>
<body>
<h2>Printing Message 5 Times Using Scriptlet</h2>
<%
for (int i = 1; i <= 5; i++) {
%>
<p>Hello, this is message <%= i %></p>
<%
}
%>
</body>
</html>
Output: