Sample Java Program
class HelloWorld {
public static void main(String[] args)
{
System.out.println("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
System.out.println("Original Array:");
printArray(numbers);
// Accessing elements of the array
System.out.println("\nElement at index 2: " + numbers[2]);
// Output: 30
// Modifying an element of the array
numbers[3] = 45;
// Print the modified array
System.out.println("\nModified Array:");
printArray(numbers);
// Calculating the sum of elements in the array
int sum = calculateSum(numbers);
System.out.println("\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 < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// 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){
System.out.println(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;
System.out.println("Light on? " + isOn);
// method to turnoff the light
void turnOff() {
isOn = false;
System.out.println("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()
led.turnOn();
// turn off the light by
// calling method turnOff()
halogen.turnOff();
}
}
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
System.out.println(Adder.add(11, 11)); // Output: 22
// Calling the add method with three integers
System.out.println(Adder.add(11, 11, 11)); // Output: 33
}
}
Java program example of Constructors
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(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) {
System.out.println(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() {
System.out.println(language + " can be used as backend language.");
}
public static void main(String[] args) {
// create object of Language class
Language java = new Language();
java.connectServer();
// call the inherited method of Frontend class
java.responsive(java.language);
}
}
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
System.out.println("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
System.out.println("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
d.show();
d.view();
}
}
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)
{
System.out.println(e);
}
System.out.println("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
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("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();
object.start();
}
}
}
File handling in java by random access file
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
// Simple Example of AWT Frame by inheritance
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(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 javax.swing.*;
import java.awt.*;
import java.awt.event.*;
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();
c.setLayout(null);
title = new JLabel("Registration Form");
title.setFont(new Font("Arial", Font.PLAIN, 30));
title.setSize(300, 30);
title.setLocation(300, 30);
c.add(title);
name = new JLabel("Name");
name.setFont(new Font("Arial", Font.PLAIN, 20));
name.setSize(100, 20);
name.setLocation(100, 100);
c.add(name);
tname = new JTextField();
tname.setFont(new Font("Arial", Font.PLAIN, 15));
tname.setSize(190, 20);
tname.setLocation(200, 100);
c.add(tname);
mno = new JLabel("Mobile");
mno.setFont(new Font("Arial", Font.PLAIN, 20));
mno.setSize(100, 20);
mno.setLocation(100, 150);
c.add(mno);
tmno = new JTextField();
tmno.setFont(new Font("Arial", Font.PLAIN, 15));
tmno.setSize(150, 20);
tmno.setLocation(200, 150);
c.add(tmno);
gender = new JLabel("Gender");
gender.setFont(new Font("Arial", Font.PLAIN, 20));
gender.setSize(100, 20);
gender.setLocation(100, 200);
c.add(gender);
male = new JRadioButton("Male");
male.setFont(new Font("Arial", Font.PLAIN, 15));
male.setSelected(true);
male.setSize(75, 20);
male.setLocation(200, 200);
c.add(male);
female = new JRadioButton("Female");
female.setFont(new Font("Arial", Font.PLAIN, 15));
female.setSelected(false);
female.setSize(80, 20);
female.setLocation(275, 200);
c.add(female);
gengp = new ButtonGroup();
gengp.add(male);
gengp.add(female);
dob = new JLabel("DOB");
dob.setFont(new Font("Arial", Font.PLAIN, 20));
dob.setSize(100, 20);
dob.setLocation(100, 250);
c.add(dob);
date = new JComboBox(dates);
date.setFont(new Font("Arial", Font.PLAIN, 15));
date.setSize(50, 20);
date.setLocation(200, 250);
c.add(date);
month = new JComboBox(months);
month.setFont(new Font("Arial", Font.PLAIN, 15));
month.setSize(60, 20);
month.setLocation(250, 250);
c.add(month);
year = new JComboBox(years);
year.setFont(new Font("Arial", Font.PLAIN, 15));
year.setSize(60, 20);
year.setLocation(320, 250);
c.add(year);
add = new JLabel("Address");
add.setFont(new Font("Arial", Font.PLAIN, 20));
add.setSize(100, 20);
add.setLocation(100, 300);
c.add(add);
tadd = new JTextArea();
tadd.setFont(new Font("Arial", Font.PLAIN, 15));
tadd.setSize(200, 75);
tadd.setLocation(200, 300);
tadd.setLineWrap(true);
c.add(tadd);
term = new JCheckBox("Accept Terms And Conditions.");
term.setFont(new Font("Arial", Font.PLAIN, 15));
term.setSize(250, 20);
term.setLocation(150, 400);
c.add(term);
sub = new JButton("Submit");
sub.setFont(new Font("Arial", Font.PLAIN, 15));
sub.setSize(100, 20);
sub.setLocation(150, 450);
sub.addActionListener(this);
c.add(sub);
reset = new JButton("Reset");
reset.setFont(new Font("Arial", Font.PLAIN, 15));
reset.setSize(100, 20);
reset.setLocation(270, 450);
reset.addActionListener(this);
c.add(reset);
tout = new JTextArea();
tout.setFont(new Font("Arial", Font.PLAIN, 15));
tout.setSize(300, 400);
tout.setLocation(500, 100);
tout.setLineWrap(true);
tout.setEditable(false);
c.add(tout);
res = new JLabel("");
res.setFont(new Font("Arial", Font.PLAIN, 20));
res.setSize(500, 25);
res.setLocation(100, 500);
c.add(res);
resadd = new JTextArea();
resadd.setFont(new Font("Arial", Font.PLAIN, 15));
resadd.setSize(200, 75);
resadd.setLocation(580, 175);
resadd.setLineWrap(true);
c.add(resadd);
setVisible(true);
}
// method actionPerformed()
// to get the action performed
// by the user and act accordingly
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sub) {
if (term.isSelected()) {
String data1;
String data
= "Name : "
+ tname.getText() + "\n"
+ "Mobile : "
+ tmno.getText() + "\n";
if (male.isSelected())
data1 = "Gender : Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2
= "DOB : "
+ (String)date.getSelectedItem()
+ "/" + (String)month.getSelectedItem()
+ "/" + (String)year.getSelectedItem()
+ "\n";
String data3 = "Address : " + tadd.getText();
tout.setText(data + data1 + data2 + data3);
tout.setEditable(false);
res.setText("Registration Successfully..");
}
else {
tout.setText("");
resadd.setText("");
res.setText("Please accept the"
+ " terms & conditions..");
}
}
else if (e.getSource() == reset) {
String def = "";
tname.setText(def);
tadd.setText(def);
tmno.setText(def);
res.setText(def);
tout.setText(def);
term.setSelected(false);
date.setSelectedIndex(0);
month.setSelectedIndex(0);
year.setSelectedIndex(0);
resadd.setText(def);
}
}
}
class Registration {
public static void main(String[] args) throws Exception
{
MyFrame f = new MyFrame();
}
}
// Border layout
import java.awt.*;
import javax.swing.*;
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
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
//Menudemo by java swing
import javax.swing.*;
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");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Socket Programming using TCP
// Demonstrating Client-side Programming
import java.io.*;
import java.net.*;
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);
System.out.println("Connected");
// Takes input from terminal
in = new DataInputStream(System.in);
// Sends output to the socket
out = new DataOutputStream(s.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}
// String to read message from input
String m = "";
// Keep reading until "Over" is input
while (!m.equals("Over")) {
try {
m = in.readLine();
out.writeUTF(m);
}
catch (IOException i) {
System.out.println(i);
}
}
// Close the connection
try {
in.close();
out.close();
s.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String[] args) {
Client c = new Client("127.0.0.1", 5000);
}
}
// Demonstrating Server-side Programming
import java.net.*;
import java.io.*;
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);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
s = ss.accept();
System.out.println("Client accepted");
// Takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(s.getInputStream()));
String m = "";
// Reads message from client until "Over" is sent
while (!m.equals("Over"))
{
try
{
m = in.readUTF();
System.out.println(m);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// Close connection
s.close();
in.close();
}
catch(IOException i)
{
System.out.println(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: