Java exercises and solutions programming


Java exercises

Java exercises here are indented to provide you the opportunity to practice the Java programming language concepts. You will start from basic Java exercises to more complex exercises. The solution is provided for each exercise. You should try to solve each problem by yourself first before checking the solution. To navigate from one page of exercises to another, you will use the right navigation bar. If you have any questions regarding to each problem, you are encouraged to post them at our forum.

Exercise 1: Write a Java program to display Hello World on the screen.

Solution:


public class HelloWorld
{
public static void main(String[] args)
{
  
   System.out.println("Hello World.");

}

}

Exercise 2:Write a Java program to display the asterisk pattern as shown below:

*****

*****

*****

*****

*****

Solution:


public class JavaExercises
{
public static void main(String[] args)
{
printAsterisk();
}

static void printAsterisk(){


  System.out.println("*****");
  System.out.println("*****");
  System.out.println("*****");
  System.out.println("*****");
  System.out.println("*****");

}

}

Exercise 3: Write a Java program to declare two integer variables, one float variable, and one string variable and assign 10, 12.5, and "Java programming" to them respectively. Then display their values on the screen.

Solution:


public class JavaExercises
{
public static void main(String[] args)
{
accessVariables();
}

static void accessVariables(){

int x;
float y;
String s;
x = 10;
y = 12.5f;
s = "Java programming";
System.out.println(x);
System.out.println(y);
System.out.println(s);

        }

}

Exercise 4: Write a Java program by using BufferedReader class  to prompt a user to input his/her name and then the output will be shown as an example below:

Hello Dara!

Solution:

import java.io.*;
public class JavaExercises
{
public static void main(String[] args)
{
printName();
}

static void printName(){
String pname=null;

try{
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter your name:");
   pname=br.readLine();
}catch(IOException e){}


System.out.println("Hello "+pname);

}

}




Comments

Thabang comment

 Thabang

Develop a program that read an odd numbered size from the keyboard and print “M” according to the size read. Your implementation MUST make use of nested loops. Your program must check that the user enters an odd number. The size read from the keyboard represent n*n matrix so that if 11 was read from the keyboard then M is printed in 11*11 matrix using upper case X and space characters..


2016-11-03
aftab comment

 aftab

Write a class player that contains attributes for the players name,average and team.write three functions to change and display these attributes.also write a constructor that asks for input to initialize all the attributes.
plz tell me anser of this program


2016-09-25
Jay JAy comment

 Jay JAy

A large company pays its salespeople on a commision basis. The salespeople receive $200 per week, plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. You have been supplied with a list of items sold by each salesperson. The values of these items are as follows:
Item Value
1 239.99
2 2129.75
3 399.95
4 4350.89


2016-08-17
Jay JAy comment

 Jay JAy

A large company pays its salespeople on a commision basis. The salespeople receive $200 per week, plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. You have been supplied with a list of items sold by each salesperson. The values of these items are as follows:
Item Value
1 239.99
2 2129.75
3 399.95
4 4350.89


2016-08-17
hihihi comment

 hihihi

Write a program that prompts the user to enter five test scores N whereas N is, 100=<N=<0. If the entered test score is invalid then prints “Invalid test score” and the entered test score is disregarded. Compute the average and the highest test score among five successful test scores entered then display the average and the highest test score.


2016-08-05
hihihi comment

 hihihi

Write a program that prompts the user to enter five test scores N whereas N is, 100=<N=<0. If the entered test score is invalid then prints “Invalid test score” and the entered test score is disregarded. Compute the average and the highest test score among five successful test scores entered then display the average and the highest test score.


2016-08-05
seo comment

 seo

Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword....wait there's even more Now what if i told you there was a simple Wordpress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at. <a href="http://www.SEORankingLinks.us">Seo Plugin</a>
[url=http://www.SEORankingLinks.us/]seo[/url]


2016-06-26
seo comment

 seo

Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword....wait there's even more Now what if i told you there was a simple Wordpress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at. <a href="http://www.SEORankingLinks.com">Seo Plugin</a>
seo http://www.SEORankingLinks.com/


2016-06-11
Munezero comment

 Munezero

gives a formula to compute the
wind-chill temperature. The formula is valid for temperature in the range between -58°F
and 41°F and wind speed greater than or equal to 2. Write a program that
prompts the user to enter a temperature and a wind speed. The program displays
the wind-chill temperature if the input is valid, otherwise displays a message indicating
whether the temperature and/or wind speed is invalid.


2016-03-16
saad here is the program for s comment

 saad here is the program for s

package drills1;
import java.util.Scanner;
public class Drills1 {
public static void main(String[] args) {
Scanner x = new Scanner (System.in);
int [] anArray = new int[10];
for(int i=0;i<10;i++){
anArray[i]=(i+1);
}
System.out.println("The array is printed as:");
for(int i=0;i<10;i++){
System.out.print(anArray[i]+" ");
}
}
}


2016-03-05
h comment

 h

JAVA) write a program IN JAVA that uses a method called quadrant that accepts as parameters a pair of double values representing an (x, y) point and returns the quadrant number for that point. Recall that quadrants are numbered as integers from 1 to 4 with the upper-right quadrant numbered 1 and the subsequent quadrants numbered in a counterclockwise fashion: xid-111609318_1 Notice that the quadrant is determined by whether the x and y coordinates are positive or negative numbers. Return 0 if the point lies on origin (point 0,0). return a -1 if the point is on the x axis, return -2 if the point is on the y axis. For example, the call of quadrant(-2.3, 3.5) should return 2 and the call of quadrant(4.5, -4.5) should return 4. The values for x and y should be entered by the user, and the where the point is located should be output by another method Name the class project3............................ based offf

import java.util.*;
public class h.w
{public static void main(String[] args)
{Scanner in=new Scanner(System.in);
double a,b,c;
a=input(in,"enter a");
b=input(in,"enter b");
c=input(in,"enter c");
solution(a,b,c);
}
public static void solution(double a,double b,double c)
{double x1,x2,disc,den;
disc=Math.pow(b,2)-4*a*c;
if(disc<0)
{System.out.println("no real solutions");
}
if(disc>=0)
{System.out.println("has real solutions:");
if(disc==0)
{x1=(-b+Math.sqrt(disc))/(2*a);
System.out.println("1 root: "+x1);
}
else
{x1=(-b+Math.sqrt(disc))/(2*a);
x2=(-b-Math.sqrt(disc))/(2*a);
output(x1,x2);
}
}
}
public static void output(double x1,double x2)
{System.out.println("Solutions:\nx1="+x1+"\nx2="+x2);

}
public static double input(Scanner in,String variable)
{
System.out.print(variable+": ");
return in.nextDouble();

}
}


2015-12-05
Robert comment

 Robert

can u pls answer this problem..
I have some problem of understanding this problem. ty
An audio signal is sometimes stored as a list of int values. The values represent the intensity of the signal at successive time intervals. Of course, in a program the signal is represented with an array.
Often a small amount of noise is included in the signal. Noise is usually small, momentary changes in the signal level. An example is the "static" that is heard in addition to the signal in AM radio.
Smoothing a signal removes some of the noise and improves the perceptual quality of the signal. This exercise is to smooth the values in an integer array.
Say that the original values are in the array "signal". Compute the smoothed array by doing this: Each value smooth [N] is the average of three values: signal [N-1], signal[N], andsignal [N+1].
For the first element of smooth, average the first two elements of signal. For the last element of smooth, average the last two elements of signal.
Use integer arithmetic for this so that the values in smooth are integers.
C:\>java Smooth
signal: 1 5 4 5 7 6 8 6 5 4 5 4
smooth: 3 3 4 5 6 7 6 6 5 4 4 4
C:\>


2015-10-21
Xenyo comment

 Xenyo

Help me write, compile, and test a program that prints your full name, hall of residence and telephone number on three separate lines on the screen.


2015-10-09
prakash comment

 prakash

thanks...


2015-08-28
CARmene comment

 CARmene

please help me on this:
4. Write a Java program to store integers from 1 to 10 into an array and output the stored integers on the computer screen



2015-08-03
carl comment

 carl

As a beginner can you tell me how to answer this kind of problem.

Write a class that accepts a user's hourly rate of pay and the number of hours worked. Display the user's gross pay, the withholding tax (15% of gross pay), and the net pay (gross pay-withholding).


2015-07-08
Dhanlaxmi comment

 Dhanlaxmi

thank u !!! it was really useful


2015-05-03
Padmavathi comment

 Padmavathi

the output is : b a a a
a b a a
a a b a
a a a b
i just want the program for the above output.
Thanks in advance .


2015-04-12
Dimple comment

 Dimple

How do you do the following assignment in Java:
Compare two investments over period of n years, one being fixed deposit giving repo-rate +2% return and other being risky investment with rate of return of repo-rate +10% with risk factor of 30% (30% chance that GAINS will not materialize ) Prompt user for repo-rate and "n"


2015-04-02
walla  comment

 walla

Purpose:
The purpose of this assignment is to help you learn the Java environment and practice I/O instructions, assignment, and simple arithmetic operators.
General Guidelines When Writing Programs:
- Include the following comments at the top of your source codes
// -----------------------------------------------------
// Assignment (include number)
// Question: (include question/part number, if applicable)
// Written by: (include your name and student ID)
// -----------------------------------------------------
- In a comment, give a general explanation of what your program does. As the programming questions get more complex, the explanations will get lengthier.
- Include comments in your program describing the main steps in your program.
- Display a welcome message which includes your name(s).
- Display clear prompts for users when you are expecting the user to enter data from the keyboard.
- All output should be displayed with clear messages and in an easy to read format.
- End your program with a closing message so that the user knows that the program has terminated.
Part 1: MyFirstProgram
In this part you are required to write a program (called MyFirstProgram.Java) that displays the following, the program should display the following (the name on the output must be replaced by your name; the date and time should also be updated to reflect the date and time you worked on the assignment; however this date and time are just fixed value as you code them in the assignment.)
Welcome to My First Java Program!
This Program was written by: David Miller.
The assignment was done individually on March 15, 2015 at 23:37:32 PM.
End of Program!
Part 2: Online Music/Apps Store
An online music and apps store offers all apps for 3$ each and all songs for 7$ each. The store requires members to prepay any amount of money they wish, and then download as many apps or as many songs accordingly. You are required to write a program that would ask the user for the amount that he/she will pay, then display two messages indicating:
- the maximum number of apps that can be downloaded, and how much funds will remain in the account after that, if any.
- the maximum number of songs that can be downloaded, the number of apps that can be downloaded after that if funds allow, and how much funds will remain in the account after that, if any.
Notice the parenthesis in app(s) and song(s) in the output.
For this assignment, assume that the user will always enter a valid integer value that is >= 0, and within the limit of the integer range.
Here is an example of how your program should behave (the value (shown in bolded italic for clarification purpose only) is entered by the user):
How much money do you wish to prepay?
89
With this amount, you will be able to purchase 29 app(s). You will then have 2$ left as a credit on your account.
Alternatively, for this amount, you will be able to purchase 12 song(s) and 1 app(s). You will then have 2$ left as a credit on your account.
Thanks for Shopping at Best Music Store!
Here is another example when the program executes:
How much money do you wish to prepay?
70
With this amount, you will be able to purchase 23 app(s). You will then have 1$ left as a credit on your account.
Alternatively, for this amount, you will be able to purchase 10 song(s) and 0 app(s). You will then have 0$ left as a credit on your account.
Thanks for Shopping at Best Music Store!
Submitting Assignment 1
- IMPORTANT: You are allowed to work on a team of 2 students at most (including yourself!). Any teams of 3 or more students will result in 0 marks for all team members. If your work on a team, ONLY one copy of the assignment is to be submitted for both members.
- Zip together the source codes. (Please use WINZIP).
- Naming convention for zip file: Create one zip file, containing all source files for your assignment using the following naming convention:
The compressed file should be called a#_studentID, where # is the number of the assignment studentID is your student ID(s) number. For example, for the first assignment, student 1234567 would submit a compressed file named a1_1234567.zip.
- Submit your compressed file at: https://elearning.yu.edu.jo.
- Submit only ONE version of an assignment. If more than one version is submitted the first one will be graded and all others will be disregarded.
Submission status
Submission status No attempt
Grading status Not graded
Due date Sunday, 15 March 2015, 11:55 PM
Time remaining 6 days 2 hours

need a solution


2015-03-13
irtiza comment

 irtiza

how i make program of the International Cricket Council (ICC) wants to design an information system (IS)
to information about all the teams, both national and international, all the
players, and all the cricket matches that are being played around the world.
In the cricketing world, there are teams, each team has a name, country of origin
and whether the team is domestic or international. Each team can have many
players. Each player have a name, date‐of‐birth, country of origin, and the teams
in which the player plays. There are also umpires, umpires also have a name, dateof‐
birth, country of origin, and the matches in which they officiate. Matches are
played between different teams on different grounds and they have a result.
There are different grounds across the globe. Each ground has a name, capacity,
and the country in which it is located.
Each match is officiated by four umpires, two on‐field umpires, one third umpire,
and a fourth official. Matches can be of different types, a one‐day match, a T20
match, a test‐match, a tour‐match, and a four‐day match. Each type of match
have different attributes like, number of days, number of overs per side, number
of innings, etc.
You have to do the following:
1. Identify the classes
2. Identify their attributes and behaviors
3. Identify the relationships between different classes
4. State the type of the relation as well


2015-03-08
siphokazi mqambayiyana comment

 siphokazi mqambayiyana

dear reader i need someone to tell me how to read from a text file.


2015-02-24
Dara comment

 Dara

Joshua, your code is correct. For a small program like the one in exercise 2, placing the code to print the stars in main is fine. However, for many lines of code (e.g 1000), dividing it into different modules ( or methods) helps your program well-structured.


2015-02-22
Joshua comment

 Joshua

In exercise 2, why do you need to use
---their solution---
public class JavaExercise
{
public static void main(String[] args)
{
printAsterisk();
}
static void printAsterisk()
{
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
}
}

when what I made:

public class Asterisk
{
public static void main(String[] args)
{
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
}
}

did the exact same thing? what is the difference? I mean should I not have made it it's own class?


2015-02-18
Riya (Student) comment

 Riya (Student)

dear reader,
i need the solution for the java program written below.. whoever could help me, i would be grateful for that person since its my project.. its an emergency.. i hope u may help me.. the above programs are to easy and cannot help me in the project so please...

1. Write a program to check whether a number is perfect square or not.
2. Write a program to take two numbers as input then display both HCF and LCM of those two numbers.

(If any of those programs are available in this site and i did not see it then i am extremely sorry..)


2015-02-12
dalal  comment

 dalal

thanks, but this is too easy for exercises :(


2014-10-27
Ammad ul haq comment

 Ammad ul haq

Design and implement a set of classes that define various types of reading material: books, novels, magazines, technical journals, text- books, and so on. Include data values that describe various attributes of the material, such as the number of pages and the names of the primary characters. Include methods that are named appropriately for each class and that print an appropriate message. Create a main driver class to instantiate and exercise several of the classes


2014-10-11
ben comment

 ben

in the 4 exercise, you just could do:


String name;
Scanner sc = new Scanner(System.in);
name = sc.nextLine;
System.out.println("Hello "+ name );



and not use the buferedReader at all.




2014-10-07
nosisa comment

 nosisa

how do you do the following exercise:
A bank in your town updates its customers’ accounts at the end of eachmonth.
The bank offers two types of accounts: savings and checking. Every customer
must maintain a minimum balance. If a customer’s balance falls below the
minimum balance, there is a service charge of $10.00 for savings accounts and
$25.00 for checking accounts. If the balance at the end of the month is at least
the minimum balance, the account receives interest as follows:
a. Savings accounts receive 4% interest.
b. Checking accounts with balances of up to $5000 more than the minimum
balance receive 3% interest; otherwise, the interest is 5%.
Write a program that reads a customer’s account number (int type),
account type (char type; s or S for savings, c or C for checking), minimum
balance that the account should maintain, and current balance. The
program should then output the account number, account type, current balance, and an appropriate message. Test your program by running it five
times, using the following data:
46728 S 1000 2700
87324 C 1500 7689
79873 S 1000 800
89832 C 2000 3000
98322 C 1000 750


2013-09-17
Oman comment

 Oman

Thank u for useful Java exercises


2012-11-01
CAPTCHA image



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.