Java practice programs for beginners

Preview:

Citation preview

JAVA PRACTICE PROGRAMS FOR

BEGINNERS WITH SOLUTIONS

by Ishan Sharma

public class javaprog1{

String str1,str2,str3;

static int count;

javaprog1(){

count++;

}

javaprog1(String s1){

str1 = s1;

count++;

}

javaprog1(String s2,String s3){

str2 = s2;

str3 = s3;

count++;

}

WAP program to show constructor

overloading using static member

public static void main(String args[]){

javaprog1 obj1 = new javaprog1();

javaprog1 obj2 = new javaprog1("string 1");

javaprog1 obj3 = new javaprog1("string 2","string 3");

System.out.println("number of times static variable used : "+count);

}

}.

WAP to implement multilevel

inheritance and method overriding

class parent{

public void function(){

System.out.println("In parent class");

}

}

class child1 extends parent{

public void function(){

System.out.println("In child1 class");

}

}

class child2 extends parent{

public void function(){

System.out.println("In child2 class");

}

}

public class javaprog2{

public static void main(String args[]){

parent obj = new parent();

obj.function();

child1 obj_c1 = new child1();

child2 obj_c2 = new child2();

obj = obj_c1;

obj.function();

obj = obj_c2;

obj.function();

}

}

WAP to implement interface class

and show use of package

// JavaProg3 is a different

//package

package JavaProg3;

public interface javaprog3{

public void print(String str_arg);

}

import JavaProg3.*;

public class javaprog4 implements javaprog3{

public void print( String str_arg){

System.out.println(str_arg);

}

public static void main(String args[]){

javaprog4 obj = new javaprog4();

obj.print(args[0]);

}

}

WAP to implement multilevel

exception handling and create your

own exception import JavaProg3.*;

public class javaprog4 implements javaprog3{

public void print( String str_arg[]){

try{

for(int i=0;i<10;i++)

System.out.println(str_arg[i]+"\n");

}catch(Exception e){

System.out.println("exception caught and re-thrown");

throw(e);

}

}

public static void main(String args[]){

javaprog4 obj = new javaprog4();

try{

obj.print(args);

} catch(Exception e){

System.out.println(e);

}

}

}

WAP to implement 3 threads such that 1st

sleeps for 200ms, 2nd for 400ms and 3rd for

600ms

class NewThread implements Runnable {

Thread t;int time;

NewThread(String str,int time1) {

time = time1;

t = new Thread(this, str);

System.out.println(t);

t.start();

}

public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println(t);

Thread.sleep(time);

}

} catch (InterruptedException e) {

System.out.println("Child interrupted.");

}

System.out.println("Exiting"+t);

}

}

class ThreadDemo {

public static void main(String args[]) {

try {

NewThread t1 = new NewThread("thread1",200);

NewThread t2 = new NewThread("thread2",400);

NewThread t3 = new NewThread("thread3",600);

}catch (Exception e) {

System.out.println(" thread interrupted."+e);

}

}

}

WAP to create applet of moving

banner

import java.awt.*;

import java.applet.*;

public class ParamBannerextends Applet implements Runnable {

String msg=" Hello Java...... ";

Thread t = null;

int state;

boolean stopFlag;

public void start() {

setBackground(Color.blue);

setForeground(Color.green);

Font currentFont = new Font("TimesRoman", Font.PLAIN, 40);

setFont(currentFont);

t = new Thread(this);

stopFlag = false;

t.start();

}

public void run() {

char ch;

for( ; ; ) {

try {

repaint();

Thread.sleep(150);

ch = msg.charAt(0);

msg = msg.substring(1, msg.length());

msg += ch;

if(stopFlag)

break;

} catch(InterruptedExceptione) {}

}

}

public void paint(Graphics g) {

g.drawString(msg, 50, 30);

}

}

WAP to make a simple calculator import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class calculator extends JApplet {

JTextField jtf1,jtf2;

JButton add = new JButton("add");

JButton sub = new JButton("sub");

JButton mul = new JButton("mul");

JButton div = new JButton("div");

public void init() {

try {

SwingUtilities.invokeAndWait(

new Runnable() {

public void run() {

makeGUI();

}

}

);

} catch (Exception exc) {

System.out.println("Can't create because of " + exc);

}

}

private void makeGUI() {

setLayout(new FlowLayout());

jtf1 = new JTextField(5);

add(jtf1);

jtf2 = new JTextField(5);

add(jtf2);

add(add);

add(sub);

add(mul);

add(div);

add.addActionListener(new ActionListener() {

public void actionPerformed(ActionEventae) {

int a = Integer.parseInt(jtf1.getText());

int b = Integer.parseInt(jtf2.getText());

int ans = a+b;

StringBuilder str = new StringBuilder();

str.append(ans);

String str1 = str.toString();

showStatus( str1 );

}

});

sub.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

int a = Integer.parseInt(jtf1.getText());

int b = Integer.parseInt(jtf2.getText());

int ans = a-b;

StringBuilder str = new StringBuilder();

str.append(ans);

String str1 = str.toString();

showStatus( str1 );

}

});

mul.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

int a = Integer.parseInt(jtf1.getText());

int b = Integer.parseInt(jtf2.getText());

int ans = a*b;

StringBuilder str = new StringBuilder();

str.append(ans);

String str1 = str.toString();

showStatus( str1 );

}

});

div.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

int a = Integer.parseInt(jtf1.getText());

int b = Integer.parseInt(jtf2.getText());

if(b == 0)

showStatus( "can't be divided by 0" );

else{

int ans = a/b;

StringBuilder str = new StringBuilder();

str.append(ans);

String str1 = str.toString();

showStatus( str1 );

}}

});

}}

Build a client server chat

application //server class

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.*;

public class server implements Runnable {

ServerSocket serversocket;

BufferedReader br1, br2;

PrintWriter pr1;

Socket socket;

Thread t1, t2,t3;

String in="",out="";

public server() {

try {

t1 = new Thread(this);

t2 = new Thread(this);

t3 = new Thread(this);

serversocket = new ServerSocket(9876);

System.out.println("> Server is waiting for client to connect ");

socket = serversocket.accept();

System.out.println("Client connected with Ip " + socket.getInetAddress().getHostAddress());

t1.start();

t2.start();

} catch (Exception e) {

}

}

public void run() {

try {

if (Thread.currentThread() == t1) {

do {

br1 = new BufferedReader(new InputStreamReader(System.in));

pr1 = new PrintWriter(socket.getOutputStream(), true);

in = br1.readLine();

pr1.println(in);

} while (!in.equals("END"));

} else {

do {

br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = br2.readLine();

System.out.println("> Client says : " + out);

} while (!out.equals("END"));

}

} catch (Exception e) {

}

}

public static void main(String[] args) {

new server();

}

}

//client class

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.*;

public class Client implements Runnable {

BufferedReader br1, br2;

PrintWriter pr1;

Socket socket;

Thread t1, t2,t3;

String in = "", out = "";

public Client() {

try {

t1 = new Thread(this);

t2 = new Thread(this);

socket = new Socket("localhost", 9876);

t1.start();

t2.start();

} catch (Exception e) {

}

}

public void run() {

try {

if (Thread.currentThread() == t2 ) {

do {

br1 = new BufferedReader(new InputStreamReader(System.in));

pr1 = new PrintWriter(socket.getOutputStream(), true);

in = br1.readLine();

pr1.println(in);

} while (!in.equals("END"));

} else {

do {

br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = br2.readLine();

System.out.println("> Server says : " + out);

} while (!out.equals("END"));

}

} catch (Exception e) {

}

}

public static void main(String[] args) {

new Client();

}

}

References:

Herbert Schildt

Stackoverflow.com

END OF PRESENTATION