SlideShare a Scribd company logo
1 of 29
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 181Mahmoud Samir Fayed
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug 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 KrennJavaDayUA
 
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 196Mahmoud 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 212Mahmoud 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 180Mahmoud 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
 
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 180Mahmoud Samir Fayed
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
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 185Mahmoud 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
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepSylvain 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 210Mahmoud 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 196Mahmoud 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

Sentiment Analysis
Sentiment AnalysisSentiment Analysis
Sentiment Analysisishan0019
 
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 manualAntonio J
 
Computer programming language concept
Computer programming language conceptComputer programming language concept
Computer programming language conceptAfiq 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 3Akshay Nagpurkar
 
Chapter 6m
Chapter 6mChapter 6m
Chapter 6mwafaa_A7
 
1 . introduction to communication system
1 . introduction to communication system1 . introduction to communication system
1 . introduction to communication systemabhijitjnec
 
Chapter 2 amplitude_modulation
Chapter 2 amplitude_modulationChapter 2 amplitude_modulation
Chapter 2 amplitude_modulationHattori Sidek
 
Digital communication viva questions
Digital communication viva questionsDigital communication viva questions
Digital communication viva questionsishan0019
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesVasavi 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 languageVasavi College of Engg
 
Digital communication system
Digital communication systemDigital communication system
Digital communication systembabak danyal
 
Digital modulation
Digital modulationDigital modulation
Digital modulationAnkur Kumar
 
Analog communication
Analog communicationAnalog communication
Analog communicationPreston King
 
Unit1 principle of programming language
Unit1 principle of programming languageUnit1 principle of programming language
Unit1 principle of programming languageVasavi 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 FileFahad Shaikh
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
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.pdfanupamfootwear
 
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.pdfkostikjaylonshaewe47
 
Java programs
Java programsJava programs
Java programsjojeph
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek 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 ProgramsUpender Upr
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harianKhairunnisaPekanbaru
 

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
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

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.