Java Coding Practice

java problem solving questions online

What kind of Java practice exercises are there?

How to solve these java coding challenges, why codegym is the best platform for your java code practice.

  • Tons of versatile Java coding tasks for learners with any background: from Java Syntax and Core Java topics to Multithreading and Java Collections
  • The support from the CodeGym team and the global community of learners (“Help” section, programming forum, and chat)
  • The modern tool for coding practice: with an automatic check of your solutions, hints on resolving the tasks, and advice on how to improve your coding style

java problem solving questions online

Click on any topic to practice Java online right away

Practice java code online with codegym.

In Java programming, commands are essential instructions that tell the computer what to do. These commands are written in a specific way so the computer can understand and execute them. Every program in Java is a set of commands. At the beginning of your Java programming practice , it’s good to know a few basic principles:

  • In Java, each command ends with a semicolon;
  • A command can't exist on its own: it’s a part of a method, and method is part of a class;
  • Method (procedure, function) is a sequence of commands. Methods define the behavior of an object.

Here is an example of the command:

The command System.out.println("Hello, World!"); tells the computer to display the text inside the quotation marks.

If you want to display a number and not text, then you do not need to put quotation marks. You can simply write the number. Or an arithmetic operation. For example:

Command to display the number 1.

A command in which two numbers are summed and their sum (10) is displayed.

As we discussed in the basic rules, a command cannot exist on its own in Java. It must be within a method, and a method must be within a class. Here is the simplest program that prints the string "Hello, World!".

We have a class called HelloWorld , a method called main() , and the command System.out.println("Hello, World!") . You may not understand everything in the code yet, but that's okay! You'll learn more about it later. The good news is that you can already write your first program with the knowledge you've gained.

Attention! You can add comments in your code. Comments in Java are lines of code that are ignored by the compiler, but you can mark with them your code to make it clear for you and other programmers.

Single-line comments start with two forward slashes (//) and end at the end of the line. In example above we have a comment //here we print the text out

You can read the theory on this topic here , here , and here . But try practicing first!

Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program.

java problem solving questions online

The two main types in Java are String and int. We store strings/text in String, and integers (whole numbers) in int. We have already used strings and integers in previous examples without explicit declaration, by specifying them directly in the System.out.println() operator.

In the first case “I am a string” is a String in the second case 5 is an integer of type int. However, most often, in order to manipulate data, variables must be declared before being used in the program. To do this, you need to specify the type of the variable and its name. You can also set a variable to a specific value, or you can do this later. Example:

Here we declared a variable called a but didn't give it any value, declared a variable b and gave it the value 5 , declared a string called s and gave it the value Hello, World!

Attention! In Java, the = sign is not an equals sign, but an assignment operator. That is, the variable (you can imagine it as an empty box) is assigned the value that is on the right (you can imagine that this value was put in the empty box).

We created an integer variable named a with the first command and assigned it the value 5 with the second command.

Before moving on to practice, let's look at an example program where we will declare variables and assign values to them:

In the program, we first declared an int variable named a but did not immediately assign it a value. Then we declared an int variable named b and "put" the value 5 in it. Then we declared a string named s and assigned it the value "Hello, World!" After that, we assigned the value 2 to the variable a that we declared earlier, and then we printed the variable a, the sum of the variables a and b, and the variable s to the screen

This program will display the following:

We already know how to print to the console, but how do we read from it? For this, we use the Scanner class. To use Scanner, we first need to create an instance of the class. We can do this with the following code:

Once we have created an instance of Scanner, we can use the next() method to read input from the console or nextInt() if we should read an integer.

The following code reads a number from the console and prints it to the console:

Here we first import a library scanner, then ask a user to enter a number. Later we created a scanner to read the user's input and print the input out.

This code will print the following output in case of user’s input is 5:

More information about the topic you could read here , here , and here .

See the exercises on Types and keyboard input to practice Java coding:

Conditions and If statements in Java allow your program to make decisions. For example, you can use them to check if a user has entered a valid password, or to determine whether a number is even or odd. For this purpose, there’s an 'if/else statement' in Java.

The syntax for an if statement is as follows:

Here could be one or more conditions in if and zero or one condition in else.

Here's a simple example:

In this example, we check if the variable "age" is greater than or equal to 18. If it is, we print "You are an adult." If not, we print "You are a minor."

Here are some Java practice exercises to understand Conditions and If statements:

In Java, a "boolean" is a data type that can have one of two values: true or false. Here's a simple example:

The output of this program is here:

In addition to representing true or false values, booleans in Java can be combined using logical operators. Here, we introduce the logical AND (&&) and logical OR (||) operators.

  • && (AND) returns true if both operands are true. In our example, isBothFunAndEasy is true because Java is fun (isJavaFun is true) and coding is not easy (isCodingEasy is false).
  • || (OR) returns true if at least one operand is true. In our example, isEitherFunOrEasy is true because Java is fun (isJavaFun is true), even though coding is not easy (isCodingEasy is false).
  • The NOT operator (!) is unary, meaning it operates on a single boolean value. It negates the value, so !isCodingEasy is true because it reverses the false value of isCodingEasy.

So the output of this program is:

More information about the topic you could read here , and here .

Here are some Java exercises to practice booleans:

With loops, you can execute any command or a block of commands multiple times. The construction of the while loop is:

Loops are essential in programming to execute a block of code repeatedly. Java provides two commonly used loops: while and for.

1. while Loop: The while loop continues executing a block of code as long as a specified condition is true. Firstly, the condition is checked. While it’s true, the body of the loop (commands) is executed. If the condition is always true, the loop will repeat infinitely, and if the condition is false, the commands in a loop will never be executed.

In this example, the code inside the while loop will run repeatedly as long as count is less than or equal to 5.

2. for Loop: The for loop is used for iterating a specific number of times.

In this for loop, we initialize i to 1, specify the condition i <= 5, and increment i by 1 in each iteration. It will print "Count: 1" to "Count: 5."

Here are some Java coding challenges to practice the loops:

An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. It acts as a container for elements that can be accessed using an index.

What you should know about arrays in Java:

  • Indexing: Elements in an array are indexed, starting from 0. You can access elements by specifying their index in square brackets after the array name, like myArray[0] to access the first element.
  • Initialization: To use an array, you must declare and initialize it. You specify the array's type and its length. For example, to create an integer array that can hold five values: int[] myArray = new int[5];
  • Populating: After initialization, you can populate the array by assigning values to its elements. All elements should be of the same data type. For instance, myArray[0] = 10; myArray[1] = 20;.
  • Default Values: Arrays are initialized with default values. For objects, this is null, and for primitive types (int, double, boolean, etc.), it's typically 0, 0.0, or false.

In this example, we create an integer array, assign values to its elements, and access an element using indexing.

In Java, methods are like mini-programs within your main program. They are used to perform specific tasks, making your code more organized and manageable. Methods take a set of instructions and encapsulate them under a single name for easy reuse. Here's how you declare a method:

  • public is an access modifier that defines who can use the method. In this case, public means the method can be accessed from anywhere in your program.Read more about modifiers here .
  • static means the method belongs to the class itself, rather than an instance of the class. It's used for the main method, allowing it to run without creating an object.
  • void indicates that the method doesn't return any value. If it did, you would replace void with the data type of the returned value.

In this example, we have a main method (the entry point of the program) and a customMethod that we've defined. The main method calls customMethod, which prints a message. This illustrates how methods help organize and reuse code in Java, making it more efficient and readable.

In this example, we have a main method that calls the add method with two numbers (5 and 3). The add method calculates the sum and returns it. The result is then printed in the main method.

All composite types in Java consist of simpler ones, up until we end up with primitive types. An example of a primitive type is int, while String is a composite type that stores its data as a table of characters (primitive type char). Here are some examples of primitive types in Java:

  • int: Used for storing whole numbers (integers). Example: int age = 25;
  • double: Used for storing numbers with a decimal point. Example: double price = 19.99;
  • char: Used for storing single characters. Example: char grade = 'A';
  • boolean: Used for storing true or false values. Example: boolean isJavaFun = true;
  • String: Used for storing text (a sequence of characters). Example: String greeting = "Hello, World!";

Simple types are grouped into composite types, that are called classes. Example:

We declared a composite type Person and stored the data in a String (name) and int variable for an age of a person. Since composite types include many primitive types, they take up more memory than variables of the primitive types.

See the exercises for a coding practice in Java data types:

String is the most popular class in Java programs. Its objects are stored in a memory in a special way. The structure of this class is rather simple: there’s a character array (char array) inside, that stores all the characters of the string.

String class also has many helper classes to simplify working with strings in Java, and a lot of methods. Here’s what you can do while working with strings: compare them, search for substrings, and create new substrings.

Example of comparing strings using the equals() method.

Also you can check if a string contains a substring using the contains() method.

You can create a new substring from an existing string using the substring() method.

More information about the topic you could read here , here , here , here , and here .

Here are some Java programming exercises to practice the strings:

In Java, objects are instances of classes that you can create to represent and work with real-world entities or concepts. Here's how you can create objects:

First, you need to define a class that describes the properties and behaviors of your object. You can then create an object of that class using the new keyword like this:

It invokes the constructor of a class.If the constructor takes arguments, you can pass them within the parentheses. For example, to create an object of class Person with the name "Jane" and age 25, you would write:

Suppose you want to create a simple Person class with a name property and a sayHello method. Here's how you do it:

In this example, we defined a Person class with a name property and a sayHello method. We then created two Person objects (person1 and person2) and used them to represent individuals with different names.

Here are some coding challenges in Java object creation:

Static classes and methods in Java are used to create members that belong to the class itself, rather than to instances of the class. They can be accessed without creating an object of the class.

Static methods and classes are useful when you want to define utility methods or encapsulate related classes within a larger class without requiring an instance of the outer class. They are often used in various Java libraries and frameworks for organizing and providing utility functions.

You declare them with the static modifier.

Static Methods

A static method is a method that belongs to the class rather than any specific instance. You can call a static method using the class name, without creating an object of that class.

In this example, the add method is static. You can directly call it using Calculator.add(5, 3)

Static Classes

In Java, you can also have static nested classes, which are classes defined within another class and marked as static. These static nested classes can be accessed using the outer class's name.

In this example, Student is a static nested class within the School class. You can access it using School.Student.

More information about the topic you could read here , here , here , and here .

See below the exercises on Static classes and methods in our Java coding practice for beginners:

Java Programming Exercises

  • All Exercises
  • Java 8 - Lambdas & Streams
  • Binary Tree

I created this website to help developers improve their programming skills by practising simple coding exercises. The target audience is Software Engineers, Test Automation Engineers, or anyone curious about computer programming. The primary programming language is Java, as it is mature and easy to learn, but you can practice the same problems in any other language (Kotlin, Python, Javascript, etc.).

  • Binary Tree problems are common at Google, Amazon and Facebook coding interviews.
  • Sharpen your lambda and streams skills with Java 8 coding practice problems .
  • Check our Berlin Clock solution , a commonly used code exercise.
  • We have videos too! Check out the FizzBuzz solution , a problem widely used on phone screenings.

How does it work ?

1. Choose difficulty

Easy, moderate or challenging.

2. Choose the exercise

From a list of coding exercises commonly found in interviews.

3. Type in your code

No IDE, no auto-correct... just like the whiteboard interview question.

4. Check results

Typically 3-5 unit tests that verify your code.

[email protected]

Email

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java exercises.

You can test your Java skills with W3Schools' Exercises.

We have gathered a variety of Java exercises (with answers) for each Java Chapter.

Try to solve an exercise by editing some code, or show the answer to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start Java Exercises

Start Java Exercises ❯

If you don't know Java, we suggest that you read our Java Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Write, Run, Solve.

Learn to solve practical problems with software. Master principles of programming whether you’re an amateur, a student, or a professional.

Your browser isn’t supported yet.

Right now, Codus needs a recent version of Chrome or Firefox in order to work properly.

Key Features

Hundreds of problems.

Codus has a library of hundreds of hand-written problems designed to reinforce programming skills.

Auto-saves as you type

Codus saves your solutions as soon as you write them, so you never lose any work, ever.

Robust solution verification

Codus checks every solution against a thorough set of test cases.

Debugging tools

Codus displays both stdout and stderr after every problem run in order to allow robust debugging.

Java Regex Medium Java (Intermediate) Max Score: 25 Success Rate: 92.93%

Java regex 2 - duplicate words medium java (basic) max score: 25 success rate: 91.37%, tag content extractor medium java (basic) max score: 20 success rate: 95.48%, java bigdecimal medium java (basic) max score: 20 success rate: 94.77%, java 1d array (part 2) medium java (basic) max score: 25 success rate: 72.49%, java stack medium java (basic) max score: 20 success rate: 92.20%, java comparator medium java (basic) max score: 10 success rate: 97.45%, java dequeue medium problem solving (intermediate) max score: 20 success rate: 83.74%, java priority queue medium java (intermediate) max score: 20 success rate: 91.13%, can you access medium max score: 15 success rate: 96.77%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

time-travel-ticket

Java Online Coding Tests

Create and send Java coding assessments in 60 seconds, even if you’re not techy. Hand over qualified Java candidates for your Engineering team to interview.

Back to online coding tests

About our Java Coding Tests

We provide your team with realistic and practical coding tests that accurately evaluate candidates’ Java skills. Using solutions like CoderPad Screen, you’ll be able to create Java coding tests in 60 seconds even if you’re not techy.

Our tests are designed to cover essential concepts, object-oriented programming, data structures, algorithms, and more. These tests are crafted by our industry experts, ensuring their alignment with real-world scenarios and their effectiveness in assessing candidates’ abilities. Hiring managers who would like to go further can even customize the test and add their own coding exercises. 

  • Recommended duration: 17-45 min
  • Average number of questions:  20
  • Type of exercises: Multiple choice, coding exercises
  • Test levels : Junior, Senior, Expert
ℹ️ Explore our questions bank and test our candidate experience yourself

Java skills to assess

  • Design thinking
  • Problem solving
  • Mastery of the Java

Jobs using Java

  • Front-End developer
  • Full stack developer

Java Sample Questions

Example question 1.

In this exercise, you have to analyze records of temperature to find the closest to zero.

java problem solving questions online

Implement the function int compute_closest_to_zero(vector<int> ts) which takes an array of temperatures ts and returns the temperature closest to 0.

ℹ️ Preview a sample coding test report

Explore Code Playback

Gain a deeper insight into the thought process and coding abilities of your developer candidates. 

  • Observe their algorithm-building skills and evaluate their approach and coding instincts. 
  • Make a mental note of areas that you would like to explore further in subsequent discussions. 
  • Be vigilant in identifying any questionable or concerning behavior

How to test Java skills to hire for your team?

Relying solely on resumes may not accurately represent a Java developer’s skills, and self-reported skills can be unreliable.

Here are five ways to assess Java developers’ coding skills:

  • Review their programmer portfolio, which showcases Java projects they have worked on and their proficiency in the language.
  • Examine their GitHub account to assess their Java code quality, activity, and involvement in Java-related projects.
  • Inquire about their use of Stack Overflow to gauge their knowledge level and participation in the Java development community.
  • Use programming tests tailored for Java developers, allowing them to solve practical Java problems and assessing their coding skills objectively.
  • Conduct live coding interviews specific to Java, where candidates can demonstrate their coding skills, problem-solving abilities, and knowledge of Java concepts.
💡 To dig deeper > 5 ways to test developers’ skills before hiring

How to approach initial candidate screening effectively?

Some recruiters may have concerns about testing candidates too early in the hiring process, as they fear it might offend or deter them. However, this doesn’t have to be the case. It is crucial to handle this situation appropriately to ensure candidates understand the purpose, feel their time is valued, and recognize their importance.

Follow these guidelines to incorporate early testing while ensuring a positive candidate experience:

  • Job Ad : Clearly communicate that testing is the first step in your hiring process within your job advertisement. By setting this expectation upfront, you eliminate the risk of candidates feeling singled out for testing. Additionally, provide information about the time commitment required so that candidates can plan accordingly.
  • Emphasize Fair Hiring and Diversity: Highlight how the testing process enables fair hiring practices and promotes diversity within your organization. Make it known that your focus is on assessing skills rather than judging candidates based on irrelevant factors. Convey that you are open to considering a diverse pool of candidates, including those without prestigious degrees or individuals starting their coding careers.
  • Concise Assessment: Keep the assessment as brief as possible, respecting candidates’ time. Select an appropriate length for the test, including only the skills that are truly essential for the position. Ideally, aim for a test that can be completed within an hour or less. If you can design an even shorter test that fulfills your requirements, it’s even better.
  • Relevance: Concentrate solely on the skills that are directly applicable to the role. Avoid the temptation to create a laundry list of nice-to-have skills that are unnecessary for the actual job. Demonstrating a pragmatic approach by focusing on skills that have a practical impact on day-to-day tasks is appreciated by developers.
  • Share Results : Provide candidates with their test results to ensure a more fulfilling experience. If you utilize a tool like CoderPad Screen, which automatically generates a brief report and sends it to candidates, you enhance their experience. Candidates who underperform will understand the reasons they weren’t selected for the next stage, and receiving results also serve as an additional incentive for completing the test.
We had no unified approach or tool to assess technical ability. Today, CoderPad Screen enables us to test against a wide selection of languages and is continually updated.

1,000 Companies use CoderPad to Screen and Interview Developers

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Monday, July 1, 2024

  • Top 50 Java Programs from Coding Interviews

Big O Notation cheat sheet

  • 50+ Data Structure and Algorithms Interview Questions
  • 20+ Basic Algorithms Questions from Interviews
  • 20 System Design Interview Questions 
  • How to Crack System Design Interview [The Ultimate Guide]
  • 10 Dynamic Programming Interview Questions
  • 10 Matrix based Coding Problems for Interviews
  • 100+ System Design Interview Questions
  • 25 Recursion based Coding Interview Questions and Answers

31 comments :

Nice collection of interview question

Good Programmas

Good collection

Do you know any other books recommended for coding interviews?

I used: "Cracking the Coding Interview" by Gayle Laakmann McDowell "TOP 30 Java Interview Coding Tasks" by Matthew Urban "Elements of Programming Interviews in Java" by Adnan Aziz, Tsung-Hsien Lee, Amit Prakash "Coding Interview Questions" by Narasimha Karumanchi

nice collection of questions. Thank you.

Really helpful ! Thanks !

String palindrome is found with error.unable to view it

Hello @Unknown, can you give more details? you mean you can't see the solution?

Ah got it, the link is incorrect, I'll correct it.

perfect ...thank you,Guys!

Thanks! for help,guys.

Very nice.. But I need a differential and integral problems in java If any one think about it reply me... We'll discuss about it😊😊😊

Nice thank you

It's very much benificial for us

My problem with this type of question is that most of them do not reflect the types of problems you encounter on the job. A good java programmer knows how to perform task needed by the job. A DB centric application will manipulate many data results efficiently. That might mean knowing lists, iterations, or using lombok. A realtime application will be more focused on things like concurrency. I've used Java professionally since it was in beta nad have never had to shift bits.

Hello Bill, interview and real work is always different. It's part of the culture we have. I think asking these kind of question is to check if people have good fundamental knowledge or not. This is important for engineering a solution rather than just coding. For example, if you know about paging, swap memory, virtual memory you will be better equipped to solve memory related problems of Java application. Just my 2 cent.

Can u plzz help me in solving the below pattern-: 55555 54444 54333 54322 54321

@Unknown, I can give you an hint, use two for loop and a combination of system.out.println() and system.print() to print this pattern

@Unknown public static void main(String[] s) { int i=55555; int r=1111; System.out.println(i); for(int j=0;j<4;j++) { i=i-r; System.out.println(i); r=r/10; }

@Unknown public static void main(String []args){ String num = ""; for(int i = 5; i>=1; i--){ num += i; //System.out.print(i); for(int j = 1; j<=i; j++){ System.out.print(i); } if(i != 1){ System.out.print("\n"+num); } } }

what are the modifiers applicable in java main method

5432 is the answer of program

Very helpful this kind of coding to pass in coding test

Num value is 5

*** * ** ** * *** Please slove this program

Reverse String ..... public class Reve { public static void main(String [] args) { String s="hello java"; String s1=" "; for(int i=s.length()-1;i>=0;i--) { s1=s1+s.CharAt(); } System.out.println("Original String : "+s); System.out.println("Reverse String : "+s1); } }

Can you please add Dynamic Programming Interview questions on this list?

1st non Repeating character and Binary Search were asked.

Any newsletter would you recommend for coding interview preparation?

Post a Comment

Preparing for java and spring boot interview.

  • Join My Newsletter .. Its FREE
  • Everything Bundle (Java + Spring Boot + SQL Interview) for a discount
  • Grokking the Java Interview
  • Grokking the Spring Boot Interview
  • Spring Framework Practice Questions
  • Grokking the SQL Interview
  • Grokking the Java Interview Part 2
  • Grokking the Java SE 17 Developer Certification (1Z0-829 Exam)
  • Spring Professional Certification Practice Test
  • Java SE 11 Certification Practice Test
  • Azure Fundamentals AZ-900 Practice Test
  • Java EE Developer Exam Practice Test
  • Java Foundations 1Z0-811 Exam Practice Test
  • AWS Cloud Practitioner CLF-C02 Exam Practice Test
  • Java SE 17 1Z0-829 Exam Practice Test
  • Azure AI-900 Exam Practice Test
  • 1Z0-829 Java Certification Topic wise Practice Test

My Newsletter articles

  • How to grow financially as Software Engineer?
  • Difference between Microservices and Monolithic Architecture
  • What is Rate Limiter? How does it work
  • Difference between @Component vs @Bean annotations in Spring Framework?
  • Top 10 Software Design Concepts Every Developer should know
  • How does SSO Single Sign On Authentication Works?

Search This Blog

Interview Questions

  • core java interview question (183)
  • interview questions (103)
  • data structure and algorithm (91)
  • Coding Interview Question (82)
  • spring interview questions (52)
  • design patterns (47)
  • object oriented programming (38)
  • SQL Interview Questions (36)
  • thread interview questions (30)
  • collections interview questions (26)
  • database interview questions (16)
  • servlet interview questions (15)
  • hibernate interview questions (11)
  • Programming interview question (6)

Java Tutorials

  • date and time tutorial (26)
  • FIX protocol tutorial (16)
  • Java Certification OCPJP SCJP (30)
  • java collection tutorial (93)
  • java IO tutorial (30)
  • Java JSON tutorial (21)
  • Java multithreading Tutorials (63)
  • Java Programming Tutorials (21)
  • Java xml tutorial (16)
  • jsp-servlet (37)
  • online resources (206)

Get New Blog Posts on Your Email

Get new posts by email:.

  • courses (253)
  • database (50)
  • Eclipse (36)
  • JVM Internals (27)
  • JQuery (23)
  • Testing (21)
  • general (15)

Blog Archive

  • ►  September (70)
  • ►  August (13)
  • What is the delegating filter proxy in Spring Secu...
  • 5 Ways to Loop or Iterate over ArrayList in Java?
  • How to get the selected radio button on click usin...
  • 10 Example of Hashtable in Java – Java Hashtable T...
  • How to sort a Map by keys in Java 8 - Example Tuto...
  • Top 30 Array Interview Questions and Answers for P...
  • What is WeakHashMap in Java? When to use it? Examp...
  • 17 SQL Query Best Practices Every Developer Should...
  • How to declare and initialize two dimensional Arra...
  • What is lazy loading in Hibernate? Lazy vs Eager l...
  • Difference between @Secured vs @RolesAllowed vs @P...
  • How to reverse an ArrayList in place in Java? Exam...
  • How to Remove Duplicates from Array without Using ...
  • 12 Apache HTTP Server Interview Questions Answers ...
  • 17 Scenario Based Debugging Interview Questions fo...
  • 10 Singleton Pattern Interview Questions in Java -...
  • 14 Multicasting Interview Questions and Answers
  • Top 20 Algorithms Interview Problems for Programme...
  • How HashMap works in Java?
  • Top 12 SQL Query Problems for Coding Interviews (w...
  • 42 Programming Interview Questions for 1 to 3 Year...
  • ►  June (9)
  • ►  May (33)
  • ►  April (45)
  • ►  March (10)
  • ►  February (3)
  • ►  January (54)
  • ►  December (30)
  • ►  November (7)
  • ►  October (13)
  • ►  September (176)
  • ►  August (53)
  • ►  July (48)
  • ►  June (4)
  • ►  May (199)
  • ►  April (134)
  • ►  March (35)
  • ►  February (11)
  • ►  January (11)
  • ►  December (6)
  • ►  November (1)
  • ►  September (1)
  • ►  August (25)
  • ►  July (44)
  • ►  June (33)
  • ►  May (14)
  • ►  April (37)
  • ►  March (7)
  • ►  February (17)
  • ►  January (22)
  • ►  December (69)
  • ►  November (37)
  • ►  October (23)
  • ►  September (45)
  • ►  August (146)
  • ►  July (223)
  • ►  June (1)
  • ►  May (1)
  • ►  April (2)
  • ►  March (6)
  • ►  January (1)
  • ►  December (1)
  • ►  October (1)
  • ►  August (1)
  • ►  May (5)
  • ►  April (13)
  • ►  March (5)
  • ►  November (4)
  • ►  July (2)
  • ►  April (1)
  • ►  July (1)
  • Privacy Policy
  • Terms and Conditions
  • DSA Tutorial
  • Data Structures

Linked List

Dynamic Programming

  • Binary Tree
  • Binary Search Tree
  • Divide & Conquer
  • Mathematical

Backtracking

  • Branch and Bound
  • Pattern Searching

Top 75 DSA Questions

In this post, we present a list of the top 75 data structures and algorithms (DSA) questions to help you prepare for a thorough revision for interviews at leading tech companies like Meta, Google , Amazon , Apple , Microsoft, etc . This list helps you to cover an extensive variety of DSA questions ensuring you don’t miss any key concepts that could appear in the interview.

  • Next Permutation
  • Stock Buy and Sell – Multiple Transactions Allowed
  • Minimize the Heights
  • First Missing Positive
  • String to Integer – Your Own atoi()
  • Anagram Check
  • First Non-Repeating Character
  • Min Chars to Add for Palindrome
  • Sort 0s, 1s and 2s
  • Count Inversions
  • Insert and Merge Interval
  • Merge two sorted arrays without extra space
  • Chocolate Distribution Problem
  • Search in Rotated Sorted Array
  • Peak Element
  • K-th element of two sorted arrays
  • Allocate Minimum Pages
  • Kth Missing Positive Number
  • Spiral Traversal
  • Search in a sorted matrix
  • Set Matrix Zeroes
  • Print all pairs with given sum
  • Longest Subsequence with Adjacent Difference of 0 or 1
  • Longest Consecutive Sequence
  • Count Subarrays with given XOR

Two Pointer Technique

  • Triplet Sum
  • Longest Substring With Distinct Characters
  • Trapping Rain Water
  • Longest Subarray with Equal No of 0s and 1s
  • Product of Array except Self
  • Find Starting Petrol Pump for Circular Tour
  • Reverse a linked list in groups
  • Segregate even and odd nodes in a Linked List
  • Clone a Linked List
  • Remove Loop in Linked List
  • Permutations of a String
  • Construct Tree from Inorder and Preorder
  • Boundary Traversal
  • Count all K Sum Paths in Binary Tree
  • Fixing Two nodes of BST
  • Largest BST in a Tree
  • Merge K Sorted Lists
  • Median of a Stream
  • Top K Frequent Elements in an Array
  • Longest Valid Parentheses
  • Largest Area in a Histogram
  • Maximum and Minimum of every window size

Queue and Deque

  • Sliding Window Maximum
  • Maximum score with jumps of at most length K
  • Subset Sum Problem
  • Longest Increasing Subsequence
  • Longest Palindromic Subsequence
  • Count Palindromic Substring
  • Minimum Jumps to Reach End
  • Coin Change – Minimum Coins
  • Stock Buy and Sell – Max K Transactions Allowed
  • House Robber II
  • Count Possible Decodings of a Digit Sequence
  • Minimum Platforms
  • Job Sequencing
  • Maximize Partitions with Unique Characters
  • Islands in a Graph
  • Minimum time to Rot Oranges
  • Cycle in an Undirected Graph
  • Cycle in a Directed Graph
  • Topological Sorting
  • Minimum Cost to connect all points
  • City with Fewest Neighbors Within Threshold Distance
  • Email Account Merging
  • Insert and Search in a Trie

author

Similar Reads

Please login to comment....

  • How to Watch NFL on NFL+ in 2024: A Complete Guide
  • Best Smartwatches in 2024: Top Picks for Every Need
  • Top Budgeting Apps in 2024
  • 10 Best Parental Control App in 2024
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • ▼Java Exercises
  • ▼Java Basics
  • Basic Part-I
  • Basic Part-II
  • ▼Java Data Types
  • Java Enum Types
  • ▼Java Control Flow
  • Conditional Statement
  • Recursive Methods
  • ▼Java Math and Numbers
  • ▼Object Oriented Programming
  • Java Constructor
  • Java Static Members
  • Java Nested Classes
  • Java Inheritance
  • Java Abstract Classes
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • Object-Oriented Programming
  • ▼Exception Handling
  • Exception Handling Home
  • ▼Functional Programming
  • Java Lambda expression
  • ▼Multithreading
  • Java Thread
  • Java Multithreading
  • ▼Data Structures
  • ▼Strings and I/O
  • File Input-Output
  • ▼Date and Time
  • ▼Advanced Concepts
  • Java Generic Method
  • ▼Algorithms
  • ▼Regular Expressions
  • Regular Expression Home
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java Conditional Statement : Exercises, Practice, Solution

Java conditional statement exercises [32 exercises with solution].

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

1. Write a Java program to get a number from the user and print whether it is positive or negative.

Test Data Input number: 35 Expected Output : Number is positive Click me to see the solution

2. Write a Java program to solve quadratic equations (use if, else if and else).

Test Data Input a: 1 Input b: 5 Input c: 1 Expected Output : The roots are -0.20871215252208009 and -4.7912878474779195 Click me to see the solution

3. Write a Java program that takes three numbers from the user and prints the greatest number.

Test Data Input the 1st number: 25 Input the 2nd number: 78 Input the 3rd number: 87 Expected Output : The greatest: 87 Click me to see the solution

4. Write a Java program that reads a floating-point number and prints "zero" if the number is zero. Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000.

Test Data Input a number: 25 Expected Output : Input value: 25 Positive number

Click me to see the solution

5. Write a Java program that takes a number from the user and generates an integer between 1 and 7. It displays the weekday name.

Test Data Input number: 3 Expected Output : Wednesday

6. Write a Java program that reads two floating-point numbers and tests whether they are the same up to three decimal places.

Test Data Input floating-point number: 25.586 Input floating-point another number: 25.589 Expected Output : They are different

7. Write a Java program to find the number of days in a month.

Test Data Input a month number: 2 Input a year: 2016 Expected Output : February 2016 has 29 days

8. Write a Java program that requires the user to enter a single character from the alphabet. Print Vowel or Consonant, depending on user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.

Test Data Input an alphabet: p Expected Output : Input letter is Consonant

9. Write a Java program that takes a year from the user and prints whether it is a leap year or not.

Test Data Input the year: 2016 Expected Output : 2016 is a leap year

10. Write a Java program to display the first 10 natural numbers.

Expected Output :

11. Write a Java program to display n terms of natural numbers and their sum.

Test Data Input the number: 2 Expected Output :

Click me to see the solution.

12. Write a program in Java to input 5 numbers from the keyboard and find their sum and average.

Test Data Input the 5 numbers : 1 2 3 4 5 Expected Output :

13. Write a Java program to display the cube of the given number up to an integer.

Test Data Input number of terms : 4 Expected Output :

14. Write a Java program to display the multiplication table of a given integer.

Test Data Input the number (Table to be calculated) : Input number of terms : 5 Expected Output :

15. Write a Java program that displays the sum of n odd natural numbers.

Test Data Input number of terms is: 5 Expected Output :

16. Write a Java program to display the pattern like a right angle triangle with a number.

Test Data Input number of rows : 10 Expected Output :

17. Write a program in Java to make such a pattern like a right angle triangle with a number which repeats a number in a row.

The pattern is as follows :

18. Write a Java program to make such a pattern like a right angle triangle with the number increased by 1.

The pattern like :

19. Write a Java program to make such a pattern like a pyramid with a number that repeats in the same row.

20. Write a Java program to print Floyd's Triangle.

Test Data Input number of rows : 5 Expected Output :

21. Write a Java program to display the pattern like a diamond.

Test Data Input number of rows (half of the diamond) : 7 Expected Output :

22. Write a Java program to display Pascal's triangle.

Test Data Input number of rows: 5 Expected Output :

23. Write a Java program to generate the following * triangles.

Test Data Input the number: 6 Expected Output :

24. Write a Java program to generate the following @'s triangle.

25. Write a Java program to display the number rhombus structure.

Test Data Input the number: 7 Expected Output :

26. Write a Java program to display the following character rhombus structure.

27. Write a Java program that reads an integer and check whether it is negative, zero, or positive.

Test Data Input a number: 7 Expected Output :

28. Write a Java program that reads a floating-point number. If the number is zero it prints "zero", otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000.

Test Data Input a number: -2534 Expected Output :

29. Write a Java program that reads an positive integer and count the number of digits the number (less than ten billion) has.

Test Data Input an integer number less than ten billion: 125463 Expected Output :

30. Write a Java program that accepts three numbers and prints "All numbers are equal" if all three numbers are equal, "All numbers are different" if all three numbers are different and "Neither all are equal or different" otherwise.

Test Data Input first number: 2564 Input second number: 3526 Input third number: 2456 Expected Output :

31. Write a program that accepts three numbers from the user and prints "increasing" if the numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and "Neither increasing or decreasing order" otherwise.

Test Data Input first number: 1524 Input second number: 2345 Input third number: 3321 Expected Output :

32. Write a Java program that accepts two floating­point numbers and checks whether they are the same up to two decimal places.

Test Data Input first floating­point number: 1235 Input second floating­point number: 2534 Expected Output :

Java Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/conditional-statement/index.php

  • Weekly Trends and Language Statistics

IMAGES

  1. basic problem solving in java

    java problem solving questions online

  2. Java Solved Programs, Problems with Solutions

    java problem solving questions online

  3. Problem Solving Modules in Java

    java problem solving questions online

  4. Coursera: Java Programming Solving Problems With Software Answers

    java problem solving questions online

  5. Java Problem Solving Tutorial: Left to Right Evaluation

    java problem solving questions online

  6. Problem Solving Skills in Java Programming

    java problem solving questions online

VIDEO

  1. L2-Q2-Accepting User Inputs in Java

  2. Problem Solving java-2

  3. LeetCode in Java

  4. java problem solving

  5. Java Interview Question and Answers

  6. LeetCode in Java

COMMENTS

  1. Solve Java

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  2. Java programming Exercises, Practice, Solution

    The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. It is recommended to do these exercises by yourself first before checking the solution.

  3. Practice Java

    Complete your Java coding practice with our online Java practice course on CodeChef. Solve over 180 coding problems and challenges to get better at Java. ... Multiple Choice Question: Easy: CodeChef Learn Problem Solving: 287: Multiple Choice Question: Easy: Learning SQL: 339: Multiple Choice Question: Easy: Parking Charges: 416: 6.

  4. 800+ Java Practice Challenges // Edabit

    English. Practice Java coding with fun, bite-sized exercises. Earn XP, unlock achievements and level up. It's like Duolingo for learning to code.

  5. Java Exercises

    In Java Interviews, Regex questions are generally asked by Int. 5 min read. ... It is a general perception that the approach using loops is treated as naive approach to solve a problem statement. But still, there is a huge scope of improvisation here. So basically, a loop statement allows us to execute a statement or group of statements ...

  6. Java Coding Practice

    Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program. Exercise 1 Exercise 2 Exercise 3. Start task.

  7. Java Programming Exercises with Solutions

    Highlights. Binary Tree problems are common at Google, Amazon and Facebook coding interviews.; Sharpen your lambda and streams skills with Java 8 coding practice problems.; Check our Berlin Clock solution, a commonly used code exercise.; We have videos too! Check out the FizzBuzz solution, a problem widely used on phone screenings.

  8. Java Exercises

    We have gathered a variety of Java exercises (with answers) for each Java Chapter. Try to solve an exercise by editing some code, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  9. Codus · Easy, Efficient Code Practice in Java

    Debugging tools. Codus displays both stdout and stderr after every problem run in order to allow robust debugging. Practice Java programming skills online. Solve hundreds of practice problems for free. Create an account today to start learning.

  10. Solve Java

    Medium Java (Intermediate) Max Score: 20 Success Rate: 91.15%. Solve Challenge. Can You Access? Medium Max Score: 15 Success Rate: 96.76%. Solve Challenge. Status. Solved. Unsolved. ... Medium Problem Solving (Intermediate) Max Score: 20 Success Rate: 83.73%. Solve Challenge. Java Priority Queue. Medium Java (Intermediate) Max Score: 20 Success ...

  11. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  12. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  13. Online Java Coding Test

    Example Question 1. In this exercise, you have to analyze records of temperature to find the closest to zero. Implement the function int compute_closest_to_zero(vector<int> ts) which takes an array of temperatures ts and returns the temperature closest to 0. Preview a sample coding test report.

  14. Learn Java Problem Solving

    Learn problem solving in Java from our online course and tutorial. You will learn basic math, conditionals and step by step logic building to solve problems easily. 4.6 ... Such fantastic types of questions! After solving these problems, it helps to enhance learning capability and fosters even more eagerness about coding knowledge. (5.0) rk7312899.

  15. Java Object Oriented Programming

    Object-oriented programming: Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or properties), and the code is in the form of procedures (often known as methods). A Java class file is a file (with the .class ...

  16. Practice

    Solve Problem. Platform to practice programming problems. Solve company interview questions and improve your coding intellect.

  17. Java Basic Programming Exercises

    Write a Java program to test if an array of integers contains an element 10 next to 10 or an element 20 next to 20, but not both. Click me to see the solution. 94. Write a Java program to rearrange all the elements of a given array of integers so that all the odd numbers come before all the even numbers. Click me to see the solution. 95.

  18. Top 50 Java Programming Interview Questions

    Consider that, for a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number. 5. Write a Java program to print a Fibonacci sequence using recursion. A Fibonacci sequence is one in which each number is the sum of the two previous numbers.

  19. Top 50 Java Programs from Coding Interviews

    Here is a big list of Java programs for Job Interviews. As I said, it includes questions from problem-solving, linked list, array, string, matrix, bitwise operators and other miscellaneous parts of programming. Once you are gone through these questions, you can handle a good number of questions on real Job interviews. 1. Fibonacci series

  20. Java Collection Exercises

    Java Collection Exercises [126 exercises with solution] Java Collection refers to a framework provided by Java to store and manipulate groups of objects. It offers a set of interfaces (like List, Set, Queue, etc.) and classes (like ArrayList, HashSet, PriorityQueue, etc.) that provide different ways to organize and work with collections of ...

  21. Online Coding Practice Problems & Challenges

    Welcome to Practice! Practice over 5000+ problems and challenges in coding languages like Python, Java, JavaScript, C++, SQL and HTML. Start with beginner friendly challenges and solve hard problems as you become better. Use these practice problems and challenges to prove your coding skills. Old practice page Recent Contest Problems.

  22. Java Stream

    Write a Java program to calculate the sum of all even, odd numbers in a list using streams. 4. Write a Java program to remove all duplicate elements from a list using streams. 5. Write a Java program to count the number of strings in a list that start with a specific letter using streams.

  23. Top 75 DSA Questions

    Java Interview Questions. Java Interview Questions; Core Java Interview Questions-Freshers; Java Multithreading Interview Questions; OOPs Interview Questions and Answers; ... A Greedy Algorithm is defined as a problem-solving strategy that makes the locally optimal choice at each step of the algorithm, with the hope that this will lead to a ...

  24. Java Exercises: Conditional Statement exercises

    Write a Java program to solve quadratic equations (use if, else if and else). Test Data Input a: 1 Input b: 5 Input c: 1 Expected Output: The roots are -0.20871215252208009 and -4.7912878474779195 Click me to see the solution. 3. Write a Java program that takes three numbers from the user and prints the greatest number. Test Data Input the 1st ...