尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
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

More Related Content

What's hot

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
archana singh
 
The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181
Mahmoud Samir Fayed
 
XTW_Import
XTW_ImportXTW_Import
XTW_Import
Luther Quinn
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
Doug Hawkins
 
Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*
Intel® Software
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
JavaDayUA
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
Mahmoud Samir Fayed
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
Baruch Sadogursky
 
delegates
delegatesdelegates
delegates
Owais Masood
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
Mahmoud Samir Fayed
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
Technopark
 
The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185
Mahmoud Samir Fayed
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
julien.ponge
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeep
Sylvain Hallé
 
The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210
Mahmoud Samir Fayed
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
tvaleev
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196
Mahmoud Samir Fayed
 

What's hot (20)

QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181
 
XTW_Import
XTW_ImportXTW_Import
XTW_Import
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
 
The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212The Ring programming language version 1.10 book - Part 35 of 212
The Ring programming language version 1.10 book - Part 35 of 212
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
delegates
delegatesdelegates
delegates
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185The Ring programming language version 1.5.4 book - Part 26 of 185
The Ring programming language version 1.5.4 book - Part 26 of 185
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeep
 
The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210The Ring programming language version 1.9 book - Part 33 of 210
The Ring programming language version 1.9 book - Part 33 of 210
 
Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?Joker 2015 - Валеев Тагир - Что же мы измеряем?
Joker 2015 - Валеев Тагир - Что же мы измеряем?
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196
 

Viewers also liked

8150.graphs
8150.graphs8150.graphs
8150.graphs
Jonghoon Park
 
Sentiment Analysis
Sentiment AnalysisSentiment Analysis
Sentiment Analysis
ishan0019
 
CIS110 Computer Programming Design Chapter (3)
CIS110 Computer Programming Design Chapter  (3)CIS110 Computer Programming Design Chapter  (3)
CIS110 Computer Programming Design Chapter (3)
Dr. Ahmed Al Zaidy
 
Fanuc pmc programming manual
Fanuc pmc programming manualFanuc pmc programming manual
Fanuc pmc programming manual
Antonio J
 
Computer programming language concept
Computer programming language conceptComputer programming language concept
Computer programming language concept
Afiq Sajuri
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
Akshay Nagpurkar
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
wafaa_A7
 
Chapter 6m
Chapter 6mChapter 6m
Chapter 6m
wafaa_A7
 
1 . introduction to communication system
1 . introduction to communication system1 . introduction to communication system
1 . introduction to communication system
abhijitjnec
 
Chapter 2 amplitude_modulation
Chapter 2 amplitude_modulationChapter 2 amplitude_modulation
Chapter 2 amplitude_modulation
Hattori Sidek
 
Digital communication viva questions
Digital communication viva questionsDigital communication viva questions
Digital communication viva questions
ishan0019
 
Unit 4
Unit 4Unit 4
Unit 5
Unit 5Unit 5
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
Vasavi College of Engg
 
PULSE CODE MODULATION (PCM)
PULSE CODE MODULATION (PCM)PULSE CODE MODULATION (PCM)
PULSE CODE MODULATION (PCM)
vishnudharan11
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
Vasavi College of Engg
 
Digital communication system
Digital communication systemDigital communication system
Digital communication system
babak danyal
 
Digital modulation
Digital modulationDigital modulation
Digital modulation
Ankur Kumar
 
Analog communication
Analog communicationAnalog communication
Analog communication
Preston King
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
Vasavi College of Engg
 

Viewers also liked (20)

8150.graphs
8150.graphs8150.graphs
8150.graphs
 
Sentiment Analysis
Sentiment AnalysisSentiment Analysis
Sentiment Analysis
 
CIS110 Computer Programming Design Chapter (3)
CIS110 Computer Programming Design Chapter  (3)CIS110 Computer Programming Design Chapter  (3)
CIS110 Computer Programming Design Chapter (3)
 
Fanuc pmc programming manual
Fanuc pmc programming manualFanuc pmc programming manual
Fanuc pmc programming manual
 
Computer programming language concept
Computer programming language conceptComputer programming language concept
Computer programming language concept
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 6m
Chapter 6mChapter 6m
Chapter 6m
 
1 . introduction to communication system
1 . introduction to communication system1 . introduction to communication system
1 . introduction to communication system
 
Chapter 2 amplitude_modulation
Chapter 2 amplitude_modulationChapter 2 amplitude_modulation
Chapter 2 amplitude_modulation
 
Digital communication viva questions
Digital communication viva questionsDigital communication viva questions
Digital communication viva questions
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 5
Unit 5Unit 5
Unit 5
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
PULSE CODE MODULATION (PCM)
PULSE CODE MODULATION (PCM)PULSE CODE MODULATION (PCM)
PULSE CODE MODULATION (PCM)
 
Unit 3 principles of programming language
Unit 3 principles of programming languageUnit 3 principles of programming language
Unit 3 principles of programming language
 
Digital communication system
Digital communication systemDigital communication system
Digital communication system
 
Digital modulation
Digital modulationDigital modulation
Digital modulation
 
Analog communication
Analog communicationAnalog communication
Analog communication
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming language
 

Similar to Java practice programs for beginners

Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
Fahad Shaikh
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
Soumya Behera
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
14 thread
14 thread14 thread
14 thread
Bayarkhuu
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
anupamfootwear
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
kostikjaylonshaewe47
 
Java programs
Java programsJava programs
Java programs
jojeph
 
Java practical
Java practicalJava practical
Java practical
shweta-sharma99
 
Thread
ThreadThread
Thread
phanleson
 
Awt
AwtAwt
JAVA.pdf
JAVA.pdfJAVA.pdf
JAVA.pdf
jyotir7777
 
Java practical
Java practicalJava practical
Java practical
william otto
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
Novi_Wahyuni
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Ayes Chinmay
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
fiafabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
KhairunnisaPekanbaru
 

Similar to Java practice programs for beginners (20)

Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
14 thread
14 thread14 thread
14 thread
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
Java programs
Java programsJava programs
Java programs
 
Java practical
Java practicalJava practical
Java practical
 
Thread
ThreadThread
Thread
 
Awt
AwtAwt
Awt
 
JAVA.pdf
JAVA.pdfJAVA.pdf
JAVA.pdf
 
Java practical
Java practicalJava practical
Java practical
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 

Recently uploaded

Discover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched ContentDiscover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched Content
ScyllaDB
 
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDBScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB
 
Building a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data PlatformBuilding a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data Platform
Enterprise Knowledge
 
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdfLee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
leebarnesutopia
 
From NCSA to the National Research Platform
From NCSA to the National Research PlatformFrom NCSA to the National Research Platform
From NCSA to the National Research Platform
Larry Smarr
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
FilipTomaszewski5
 
Multivendor cloud production with VSF TR-11 - there and back again
Multivendor cloud production with VSF TR-11 - there and back againMultivendor cloud production with VSF TR-11 - there and back again
Multivendor cloud production with VSF TR-11 - there and back again
Kieran Kunhya
 
ScyllaDB Real-Time Event Processing with CDC
ScyllaDB Real-Time Event Processing with CDCScyllaDB Real-Time Event Processing with CDC
ScyllaDB Real-Time Event Processing with CDC
ScyllaDB
 
intra-mart Accel series 2024 Spring updates_En
intra-mart Accel series 2024 Spring updates_Enintra-mart Accel series 2024 Spring updates_En
intra-mart Accel series 2024 Spring updates_En
NTTDATA INTRAMART
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
Introduction to ThousandEyes AMER Webinar
Introduction  to ThousandEyes AMER WebinarIntroduction  to ThousandEyes AMER Webinar
Introduction to ThousandEyes AMER Webinar
ThousandEyes
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
Automation Student Developers Session 3: Introduction to UI Automation
Automation Student Developers Session 3: Introduction to UI AutomationAutomation Student Developers Session 3: Introduction to UI Automation
Automation Student Developers Session 3: Introduction to UI Automation
UiPathCommunity
 
New ThousandEyes Product Features and Release Highlights: June 2024
New ThousandEyes Product Features and Release Highlights: June 2024New ThousandEyes Product Features and Release Highlights: June 2024
New ThousandEyes Product Features and Release Highlights: June 2024
ThousandEyes
 
Day 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data ManipulationDay 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data Manipulation
UiPathCommunity
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
zjhamm304
 
Fuxnet [EN] .pdf
Fuxnet [EN]                                   .pdfFuxnet [EN]                                   .pdf
Fuxnet [EN] .pdf
Overkill Security
 
Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...
Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...
Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...
dipikamodels1
 
ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
UiPathCommunity
 

Recently uploaded (20)

Discover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched ContentDiscover the Unseen: Tailored Recommendation of Unwatched Content
Discover the Unseen: Tailored Recommendation of Unwatched Content
 
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDBScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
 
Building a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data PlatformBuilding a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data Platform
 
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdfLee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
Lee Barnes - Path to Becoming an Effective Test Automation Engineer.pdf
 
From NCSA to the National Research Platform
From NCSA to the National Research PlatformFrom NCSA to the National Research Platform
From NCSA to the National Research Platform
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
 
Multivendor cloud production with VSF TR-11 - there and back again
Multivendor cloud production with VSF TR-11 - there and back againMultivendor cloud production with VSF TR-11 - there and back again
Multivendor cloud production with VSF TR-11 - there and back again
 
ScyllaDB Real-Time Event Processing with CDC
ScyllaDB Real-Time Event Processing with CDCScyllaDB Real-Time Event Processing with CDC
ScyllaDB Real-Time Event Processing with CDC
 
intra-mart Accel series 2024 Spring updates_En
intra-mart Accel series 2024 Spring updates_Enintra-mart Accel series 2024 Spring updates_En
intra-mart Accel series 2024 Spring updates_En
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
Introduction to ThousandEyes AMER Webinar
Introduction  to ThousandEyes AMER WebinarIntroduction  to ThousandEyes AMER Webinar
Introduction to ThousandEyes AMER Webinar
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
Automation Student Developers Session 3: Introduction to UI Automation
Automation Student Developers Session 3: Introduction to UI AutomationAutomation Student Developers Session 3: Introduction to UI Automation
Automation Student Developers Session 3: Introduction to UI Automation
 
New ThousandEyes Product Features and Release Highlights: June 2024
New ThousandEyes Product Features and Release Highlights: June 2024New ThousandEyes Product Features and Release Highlights: June 2024
New ThousandEyes Product Features and Release Highlights: June 2024
 
Day 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data ManipulationDay 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data Manipulation
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
 
Fuxnet [EN] .pdf
Fuxnet [EN]                                   .pdfFuxnet [EN]                                   .pdf
Fuxnet [EN] .pdf
 
Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...
Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...
Call Girls Kochi 💯Call Us 🔝 7426014248 🔝 Independent Kochi Escorts Service Av...
 
ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
 

Java practice programs for beginners

  • 1. JAVA PRACTICE PROGRAMS FOR BEGINNERS WITH SOLUTIONS by Ishan Sharma
  • 2. 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
  • 3. 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); } }.
  • 4.
  • 5. 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");  }  }
  • 6.  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();  }  }
  • 7.
  • 8. 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]);  }  }
  • 9.
  • 10. 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);  }  }  }
  • 11.
  • 12. 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[]) {
  • 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);  }  }  }
  • 14.
  • 15. 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;
  • 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);  }  }
  • 17.
  • 18. 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() {
  • 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 );  }}  });  }}
  • 22.
  • 23. 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 {
  • 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();  }  }
  • 27.
  翻译: