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]);
 }
 }
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 ParamBanner
extends 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(InterruptedException
e) {}
 }
 }
 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() {
 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(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 );
 }
 });
 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;
 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

Java practice programs for beginners

  • 1.
    JAVA PRACTICE PROGRAMSFOR BEGINNERS WITH SOLUTIONS by Ishan Sharma
  • 2.
    public class javaprog1{ Stringstr1,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
  • 3.
    public static voidmain(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); } }.
  • 5.
    WAP to implementmultilevel 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");  }  }
  • 6.
     class child2extends 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();  }  }
  • 8.
    WAP to implementinterface 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]);  }  }
  • 10.
    exception handling andcreate 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);  }  }  }
  • 12.
    WAP to implement3 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[]) {
  • 13.
     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);  }  }  }
  • 15.
    WAP to createapplet of moving banner  import java.awt.*;  import java.applet.*;  public class ParamBanner extends 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;
  • 16.
     for( ;; ) {  try {  repaint();  Thread.sleep(150);  ch = msg.charAt(0);  msg = msg.substring(1, msg.length());  msg += ch;  if(stopFlag)  break;  } catch(InterruptedException e) {}  }  }  public void paint(Graphics g) {  g.drawString(msg, 50, 30);  }  }
  • 18.
    WAP to makea 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() {  SwingUtilities.invokeAndWait(  new Runnable() {  public void run() {  makeGUI();  }  }  );  } catch (Exception exc) {  System.out.println("Can't create because of " + exc);  }  }  private void makeGUI() {
  • 19.
     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(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 );  }  });  sub.addActionListener(new ActionListener() {  public void actionPerformed(ActionEvent ae) {
  • 20.
     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) {
  • 21.
     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 );  }}  });  }}
  • 23.
    Build a clientserver 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 {
  • 24.
     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();  }  }
  • 25.
     //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;  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 {
  • 26.
     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();  }  }
  • 28.
  • 29.