Java Coding Practice

java homework questions

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 homework questions

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 homework questions

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:

Close

Welcome.please sign up.

By signing up or logging in, you agree to our Terms of service and confirm that you have read our Privacy Policy .

Already a member? Go to Log In

Welcome.please login.

Forgot your password

Not registered yet? Go to Sign Up

Practice questions on Java Classes and Objects

BlogsDope App

Pythonista Planet Logo

45 Java Programming Exercises With Solutions

If you have learned the basics of Java , it is the right time to solve some practice problems. Practicing and solving problems will help you master the Java programming language and take your skills to the next level.

In this post, I have put together some Java coding problems that you can use for practice. I have also provided the Java code solutions and the corresponding output for your reference.

Try to solve these problems by yourself and get better at Java. Let’s dive right in.

Java Programming Exercises With Solutions

1. Java program to check whether the given number is even or odd

2. java program to convert the temperature in centigrade to fahrenheit, 3. java program to find the area of a triangle whose three sides are given, 4. java program to find out the average of a set of integers, 5. java program to find the product of a set of real numbers, 6. java program to find the circumference and area of a circle with a given radius, 7. java program to check whether the given integer is a multiple of 5, 8. java program to check whether the given integer is a multiple of both 5 and 7, 9. java program to find the average of 5 numbers using a while loop, 10. java program to display the given integer in the reverse order, 11. java program to find the geometric mean of n numbers, 12. java program to find the sum of the digits of an integer using a while loop, 13. java program to display all the multiples of 3 within the range 10 to 50, 14. java program to display all integers within the range 100-150 whose sum of digits is an even number, 15. java program to check whether the given integer is a prime number or not, 16. java program to generate the prime numbers from 1 to n, 17. java program to find the roots of a quadratic equation, 18. java program to print the numbers from a given number n till 0 using recursion, 19. java program to find the factorial of a number using recursion, 20. java program to display the sum of n numbers using an array, 21. java program to implement linear search, 22. java program to implement binary search, 23. java program to find the number of odd numbers in an array, 24. java program to find the largest number in an array without using built-in functions, 25. java program to insert a number to any position in an array, 26. java program to delete an element from an array by index, 27. java program to check whether a string is a palindrome or not, 28. java program to implement matrix addition, 29. java program to implement matrix multiplication, 30. java program to check leap year, 31. java program to find the nth term in a fibonacci series using recursion, 32. java program to print fibonacci series using iteration, 33. java program to implement a calculator to do basic operations, 34. java program to find your weight on mars.

Mars’ gravity is about 38% of Earth’s. Write a program that will calculate your weight on Mars.

  • Declare all variables at the top of the class.
  • Initial variables are to be of float type.
  • After making the calculations, assign the result to a new variable, this time of the double type.
  • After assigning the assignment, write the variable double to the console, limiting its length to 4 decimal places.
  • Cast the above variable of double type to a new variable of int type.
  • Cast the above variable of type int to a new variable of type char.
  • Do any math operation on this variable char type and assign the value of this activity to the new variable int type.
  • Each of the above actions should be written to the console, adding some text explaining what has been done.

35. Java Program to Check Whether the Generated Random Number Is Even or Odd

Write a program that generates a random number between 1 and 100 (you can use the Random () method from the Math class.

In the next step check whether it is an even or an odd number. Each of the above actions should be written to the console.

36. Java Program to Find the Number of Containers You Need

Choose an odd number between 50 and 100 and save it as an int variable telling us how many Lego bricks we have (e.g. amountOfBricks ), then select an even number between 5 and 10 stating how many Lego blocks fit in one container (e.g.: containerCapacity ) and save it as an int variable as well.

Write a program that will calculate how many full containers we have, how many containers, in general, are full and not full, and how many blocks are in the container that is not completely full (use the modulo operator for this).

37. Java Program to Calculate Taxes

Using the double types, implement the following: Suppose a product costs 9.99 net, calculate its gross value (we assume VAT of 23%). Then multiply it by 10,000 (i.e., we sold 10,000 pcs of this product), and calculate this value excluding VAT.

Implement the above actions using the Big Decimal class. Print on the console all computed values and compare their values. What conclusions do you have?

38. Calculate BMI Using Java

The user enters his height (in inches) and weight (in pounds). The variables passed by the user are assigned to the float type. After calculating the BMI value, the value will be assigned to the appropriate range and the correct message will appear on the console. You can use the if-else-if ladder for printing the message on the console.

Intervals of BMI index:

  • 16.00 or less = starvation
  • 16.00-16.99 = emaciation
  • 17.00-18.49 = underweight
  • 18.50-22.99 = normal, low range
  • 23.00-24.99 = normal high range
  • 25.00-27.49 = overweight low range
  • 27.50-29.99 = overweight high range
  • 30.00-34.99 = 1st degree obesity
  • 35.00-39.99 = 2nd degree obesity
  • 40.00 or above = 3rd degree obesity

39. Java Program to Find the Sum of Even Numbers

Write a program that sums even numbers from 1 to 100 using for loop.

40. Java Program to Find the Largest and Smallest Numbers From Random Numbers

Write a program that will use the while loop to find the largest and smallest number from the set of 10 randomly drawn integers from 1 to 100. In this task, do not use arrays or other collections.

41. Java Program to Calculate the Area of a Rectangle

Write a program that follows the rules of object-oriented programming and will calculate the area of the rectangle.

You need to create two classes, one RectangleArea for the logic of your program and the Main class. In the Main class, we create the RectangleArea object and call three methods on it.

The methods you should create are:

  • getData(), gets side lengths from the
  • computeField(), performs
  • fieldDisplay(), displays info and result.

42. Returning Information About an Object in Java

Declare the class Car and define the following fields of this class (with the access modifier private): model, brand, year, price, color, and quantity.

Create a constructor of this class consisting of the previously mentioned fields. Create methods to return each of the fields and methods to set values for each of the fields. Additionally, create the sell() method (simulating car sales) which will change the value of the quantity field when called.

The last method to create is the toString() method that returns an object of type String and prints the names of all fields of a given object and values.

Create another class with the main() method in it. Create an object of the Car class by using the constructor. Call the toString() method and print the details.

Call the sell() method. Print all fields (using the previously declared getter methods of the object field).

Using the setter methods, change some fields of the object. Call the toString() method and print the details to notice the changes.

43. Filling an Array Using For Loops in Java

Write a program that creates a 10-element array and puts the numbers from 9 to 0 in it.

Use the classic for loop to fill the array, and in the condition, use the  array.length  method. Use for-each loop as a second loop to display the value of the array.

44. Java Program to Find the Largest and Smallest Numbers From an Array of Random Numbers

Write a program that will create a one-dimensional array with 10 elements that are chosen randomly from 1 to 100. Then use a loop to find the smallest and largest element in the array.

45. Two-dimensional Array in Java

Write a program that creates a two-dimensional array with dimensions of 10×10 and named matrix. On the diagonal of this matrix, put the numbers from 0 to 9 and the number 0 everywhere else. Additionally, the program should calculate the sum of the elements on the diagonal.

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

6 thoughts on “ 45 Java Programming Exercises With Solutions ”

What a wonderful template! I found what I needed and more, Keep It Up Legend <3

* *2 *2* *2*4 *2*4*

Drawn above pattern in java ?

Your Centigrade converter doesn’t work. You need 9f instead of 9, or rounding will give you the wrong answer.

Thank you for pointing out the mistake. I have corrected the code.

It is to most and very workfull 🤩🤩

You have done it well, sir

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name and email in this browser for the next time I comment.

Recent Posts

Introduction to Modular Programming with Flask

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules. In this tutorial, let's understand what modular...

Introduction to ORM with Flask-SQLAlchemy

While Flask provides the essentials to get a web application up and running, it doesn't force anything upon the developer. This means that many features aren't included in the core framework....

java homework questions

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

Browse Course Material

Course info, instructors.

  • Adam Marcus

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

Introduction to programming in java, assignments.

MIT Open Learning

Java Programming

Homework help & tutoring.

Java Programming

Our name 24HourAnswers means you can submit work 24 hours a day - it doesn't mean we can help you master what you need to know in 24 hours. If you make arrangements in advance, and if you are a very fast learner, then yes, we may be able to help you achieve your goals in 24 hours. Remember, high quality, customized help that's tailored around the needs of each individual student takes time to achieve. You deserve nothing less than the best, so give us the time we need to give you the best.

If you need assistance with old exams in order to prepare for an upcoming test, we can definitely help. We can't work with you on current exams, quizzes, or tests unless you tell us in writing that you have permission to do so. This is not usually the case, however.

We do not have monthly fees or minimum payments, and there are no hidden costs. Instead, the price is unique for every work order you submit. For tutoring and homework help, the price depends on many factors that include the length of the session, level of work difficulty, level of expertise of the tutor, and amount of time available before the deadline. You will be given a price up front and there is no obligation for you to pay. Homework library items have individual set prices.

We accept credit cards, debit cards, PayPal, Venmo, ApplePay, and GooglePay.

Over the past two decades, Java has grown to become one of the most widely used programming languages in the industry, as it is taught in colleges and universities around the globe. If you are studying computer science, you will need to become proficient in java programming through a college course. This programming language will likely serve as a fundamental tool you will employ in future classes, making it essential that you have a full understanding of how to use it.

Even simple Java homework assignments can provide the extra practice needed to help you gain a more thorough understanding of the language, so it's crucial you get help with your Java programming class when you have questions or feel uncertain about how to approach an assignment. 

At 24HourAnswers, we recognize the importance of Java in the computer science field, and, whatever your stage of study, we have a team of veteran Java developers, experienced software designers and computer scientists ready to help with your Java assignments, or to assist you with your Java programming coursework. 

Get Help With Java Programming Homework

Using our services for Java assignment help gives you access to valuable tools and professional insights that will enhance your learning experience. Because the majority of our team members have received advanced degrees in their respective fields, they understand the volume and content of your coursework. As a result, they also know how to help you succeed and provide Java homework help that you won't find anywhere else. 

Working with our tutors for Java programming assistance gives you the opportunity to:

  • Ask any specific or general questions about Java programming.
  • Review in-class lessons to improve your understanding of Java. 
  • Prepare for upcoming in-class exams or quizzes.
  • Inquire about specific aspects of a Java programming assignment.
  • Discover the most effective approaches for Java-related issues.

24HourAnswers Online Java Tutors

We strive to give all students access to our highly qualified tutors to help promote success in demanding courses in college. Our online Java tutors include individuals with advanced degrees in their fields, such as software developers and Java designers themselves. With their experienced and credentialed background, they can provide the Java assignment help you need in current and future college programming courses.

When you work one-on-one with our team of Java tutors, you will:

  • Receive help tailored to your style of learning.
  • Gain access to round-the-clock assistance.
  • Feel more confident in your Java programming abilities.
  • Improve your in-class performance. 
  • Develop a more thorough understanding of real-life Java applications.

Because our tutors are constantly standing by to help you succeed in your Java programming courses, you can use our services at any time. Whether in the early morning or the middle of the night, our team of professionals will provide the answers you need to reach your full potential in your Java programming course. 

Contact Us for Java Assignment Help

Our services are useful for all college students taking Java programming classes. Whether you're just starting to learn Java programming or you want to become more proficient in an advanced course, our professional Java tutors can offer the services you need to achieve your educational goals.

With your personal dedication to your education and our team's Java programming background, you'll have all the tools you need to get the most out of your programming class. You can feel free to ask our tutors questions, submit your assignments for extra Java homework help or simply learn more about the program itself. 

At 24HourAnswers, our goal is to help you succeed inside the classroom, and we'll help you every step of the way. Schedule your first session with one of our tutors today or submit your Java assignments for homework help.

Java Programming Software

Java is developed using the Oracle Java Development Kit (JDK). The most popular version of the JDK which is typically used for application development and in coursework is Java Standard Edition (SE) version 8. To get started developing Java using the JDK, download JDK 8 here , selecting the version corresponding to your operating system.

After downloading the Java Development Kit (JDK), an integrated development environment (IDE) is used to write code in the Java programming language. There are a number of popular tools which are commonly used for Java software development.

Popular Java IDEs:

  • Eclipse: https://www.eclipse.org/downloads/
  • NetBeans: https://netbeans.org/
  • IntelliJ IDEA: https://www.jetbrains.com/idea/
  • BlueJ: https://www.bluej.org/
  • DrJava: http://www.drjava.org/
  • JCreator: http://www.jcreator.com/
  • jGRASP: https://www.jgrasp.org/

Among the options for development environments, Eclipse is the program of choice which is most commonly used for Java program development. Eclipse is an open-source IDE which supports the creation of Java workspaces for more complex Java development projects, and it supports the development and use of plug-ins which extend the core functionality of the program. Download Eclipse now to begin writing programs in Java.

Java source code is organized in classes, in which each class either contains code which can be executed, or contains the definition of a class, which can be referenced and instantiated by another class in the program. Within a program, these classes belong to packages where each package is a grouping of classes that contain a common set of roles, functions, and objectives. Part of becoming a great software developer involves thinking about how best to organize your code. Plan a program out in advance using pseudocode or a skeleton of the overall project. This will help you identify what packages and classes will be needed in the overall program, as well as guiding you to consider how the different parts of the program will depend on and affect each other.

Now that you have the Java Development Kit, the Eclipse integrated development environment, and a program in mind, you have all the tools needed to dive into Java programming. Whether your program is an introductory level Java assignment or a more complicated graduate-level algorithms project, our Java online tutors are ready to assist with your Java programming assignment to help you design and create great software.

Our Java online tutors are available anytime to offer Java programming assignment help or guide your understanding and mastery of your Java programming coursework. For any Java programming challenge—big or small—bring us the question, and we have the answers! 

College Java Programming Homework Help

Since we have tutors in all Java Programming related topics, we can provide a range of different services. Our online Java Programming tutors will:

  • Provide specific insight for homework assignments.
  • Review broad conceptual ideas and chapters.
  • Simplify complex topics into digestible pieces of information.
  • Answer any Java Programming related questions.
  • Tailor instruction to fit your style of learning.

With these capabilities, our college Java Programming tutors will give you the tools you need to gain a comprehensive knowledge of Java Programming you can use in future courses.

24HourAnswers Online Java Programming Tutors

Our tutors are just as dedicated to your success in class as you are, so they are available around the clock to assist you with questions, homework, exam preparation and any Java Programming related assignments you need extra help completing.

In addition to gaining access to highly qualified tutors, you'll also strengthen your confidence level in the classroom when you work with us. This newfound confidence will allow you to apply your Java Programming knowledge in future courses and keep your education progressing smoothly.

Because our college Java Programming tutors are fully remote, seeking their help is easy. Rather than spend valuable time trying to find a local Java Programming tutor you can trust, just call on our tutors whenever you need them without any conflicting schedules getting in the way.

StudyMonkey

Your personal ai java tutor.

Learn Smarter, Not Harder with Java AI

Introducing StudyMonkey, your AI-powered Java tutor .

StudyMonkey AI can tutor complex Java homework questions, enhance your essay writing and assess your work—all in seconds.

No more long all-nighters

24/7 solutions to Java questions you're stumped on and essays you procrastinated on.

No more stress and anxiety

Get all your Java assignments done with helpful answers in 10 seconds or less.

No more asking friends for Java help

StudyMonkey is your new smart bestie that will never ghost you.

No more staying after school

AI Java tutoring is available 24/7, on-demand when you need it most.

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.

AI Tutor for any subject

American college testing (act), anthropology, advanced placement exams (ap exams), arabic language, archaeology, biochemistry, chartered financial analyst (cfa) exam, communications, computer science, certified public accountant (cpa) exam, cultural studies, cyber security, dental admission test (dat), discrete mathematics, earth science, elementary school, entrepreneurship, environmental science, farsi (persian) language, fundamentals of engineering (fe) exam, gender studies, graduate management admission test (gmat), graduate record examination (gre), greek language, hebrew language, high school entrance exam, high school, human geography, human resources, international english language testing system (ielts), information technology, international relations, independent school entrance exam (isee), linear algebra, linguistics, law school admission test (lsat), machine learning, master's degree, medical college admission test (mcat), meteorology, microbiology, middle school, national council licensure examination (nclex), national merit scholarship qualifying test (nmsqt), number theory, organic chemistry, project management professional (pmp), political science, portuguese language, probability, project management, preliminary sat (psat), public policy, public relations, russian language, scholastic assessment test (sat), social sciences, secondary school admission test (ssat), sustainability, swahili language, test of english as a foreign language (toefl), trigonometry, turkish language, united states medical licensing examination (usmle), web development, step-by-step guidance 24/7.

Receive step-by-step guidance & homework help for any homework problem & any subject 24/7

Ask any Java question

StudyMonkey supports every subject and every level of education from 1st grade to masters level.

Get an answer

StudyMonkey will give you an answer in seconds—multiple choice questions, short answers, and even an essays are supported!

Review your history

See your past questions and answers so you can review for tests and improve your grades.

It's not cheating...

You're just learning smarter than everyone else

How Can StudyMonkey Help You?

Hear from our happy students.

"The AI tutor is available 24/7, making it a convenient and accessible resource for students who need help with their homework at any time."

"Overall, StudyMonkey is an excellent tool for students looking to improve their understanding of homework topics and boost their academic success."

Upgrade to StudyMonkey Premium!

You have used all of your answers for today!

Why not upgrade to StudyMonkey Premium and get access to all features?

Take advantage of our 14 day free trial and try it out for yourself!

java homework questions

Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.

  • online courses
  • certification
  • free resources

Saturday, September 16, 2023

10 programming questions and exercises for java programmers, java programing questions exercises for beginners to practices.

Practice questions and exercises for Java Beginners

can you send me please some complex program exercise on my email:[email protected] plz plzzz

java homework questions

yes why not dude. please contact me via [email protected]

java homework questions

i have a doubt! Is there any way of iterating through strings in java without using predefs??

Hello Thiru, what is predefs? never heard about it?

To the previous commenter, even for experienced programmers some of these problems are still usefull to sharpen your skills with. A solid base will improve your overall ability and infact research into finding an efficint method of finding the factorial of an integer is still being conducted, if I'm not mistaken.

A good one would be to create an alarm clock that can work in both letters and numbers. Another would be fixing code for a program you garbled. Still, these are good school style exercises! Thank you.

I was looking for some beginners Java questions for my training course. I loved your collection, they are not too difficult, easy to understand but only thing is that they lack novelty. They are quite old Java questions. Though I would like to use these, I am also putting my own e.g. 1) Write a Java program to get all hashtags and mentioned in a twitter message? (This would be a good String matching exercise in Java, as you can use regular expression, can split string etc. As hashtags starts with '#' and mentioned strats with '@' character. 2) Count How many characters a String contains, without including any white space e.g. \t \n etc.

can you show the output of 1st programme

Admin can you post more Java programs which are used for improving programming skill and also useful for interviews(these 10 questions are good but want more and more like such questions friend....)

Exercise 10 for anyone interested, simple version. public class pyramidDrawing { public static void main(String[] args) { simpleDrawing(10); arrayDrawing(10); } public static void simpleDrawing(int number) { for(int i = 1; i <= number; i++) { for(int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } for(int v = number; v >= 1; v--) { for(int q = 1; q <= v; q++) { System.out.print("*"); } System.out.println(); } } public static void arrayDrawing(int number) { List numere = new ArrayList(); for(int numar = 1 ; numar <= number; numar++) { numere.add(numar); } for(int i = 0; i < numere.size(); i++) { if(i % 2 == 0) { for(int j = 0; j <= i; j++) { System.out.print(numere.get(i)); } System.out.println(); } } for(int v = numere.size(); v >= 0; v--) { if(v % 2 != 0) { for(int q = 1; q <= v; q++) { System.out.print(numere.get(v-1)); } System.out.println(); } } } }

* ** *** **** ***** ****** ******* ******** ********* ********** ********** ********* ******** ******* ****** ***** **** *** ** * 1 333 55555 7777777 999999999 999999999 7777777 55555 333 1

Updated one, as we no need to repeat the biggest number of stars or number for example 999999999, and also the argument in simpleDrawing(10) has to be 1,3,5,7,9,11or so on not 10 import java.util.ArrayList; import java.util.List; public class pyramidDrawing { public static void main(String[] args) { simpleDrawing(7); arrayDrawing(10); } public static void simpleDrawing(int number) { for(int i = 1; i <= number; i+=2) { for(int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } for(int v = number-2; v >= 1; v-=2) { for(int q = 1; q <= v; q++) { System.out.print("*"); } System.out.println(); } } public static void arrayDrawing(int number) { List numere = new ArrayList(); for(int numar = 1 ; numar <= number; numar++) { numere.add(numar); } for(int i = 0; i < numere.size(); i++) { if(i % 2 == 0) { for(int j = 0; j <= i; j++) { System.out.print(numere.get(i)); } System.out.println(); } } for(int v = numere.size()-2; v >= 0; v--) { if(v % 2 != 0) { for(int q = 1; q <= v; q++) { System.out.print(numere.get(v-1)); } System.out.println(); } } } }

just a question, you cant put more than 8 digits as the largest no. of digits for double (largest data type according to my knowledge, being only a 10th grade novice) right?

Dear admin,please give me the answer of no6..

import java.util.Scanner; public class ArmstrongNumber { public static void main(String[] args) { int org, temp , sum = 0 , r; Scanner in = new Scanner(System.in); System.out.println("Enter the number to find its armstrong number or not"); org = in.nextInt(); // System.out.println(org); temp = org; while (temp != 0) { r =temp % 10; sum = sum +(r*r*r); temp = temp - r; temp = temp / 10; } if (org == sum) { System.out.println("the number " + org+ " is armstrong number"); } else { System.out.println("the number " + org+ " is not armstrong number"); } } }

public class ArmstrongNo { public static void main(String args[]) { double n,a,b,c,d,e,f; double g,h; System.out.print("enter n"); n=TextIO.getInt(); g=n/100; a=Math.floor(g); d=n-100*a; h=d/10; b=Math.floor(h); e=d-10*b; c=e; f=Math.pow(a,3)+Math.pow(b,3)+Math.pow(c,3); if (f==n){ System.out.println("Yes"); } else { System.out.println("No"); } }}

My solution for part 4, im a beginner. import java.util.Scanner; public class Tutorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("compare if Power of 2"); while(true){ System.out.println("Input your number:"); double num = sc.nextInt(); double power=1; int j=0; for(int i=0;i<100;i++){ power=Math.pow(2, i); //System.out.println("num = "+power); if (num==power){ j++; } } if (j>0){ System.out.println("IS a power of 2"); } else System.out.println("NOT a power of 2"); } } }

if you try to keep dividing the number by 2 and the number perfectly divided by 2 with 0 as remainder until you get 1 in the end then it is power of 2 otherwise it is not. import java.util.Scanner; public class PowerOfTwo { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int num = scan.nextInt(); while(num%2==0 && num!=0) { num = num/2; } if(num == 1) System.out.println("Number is power of 2"); else System.out.println("Number is not power of 2"); } }

Too easy programs...........

A Dynamic Solution: public class PrintStructure { public static final int START = 1; public static final int MAX = 10; public static final int STEP_SIZE = 3; public static void main(String[] args) { int noOfLoops = (MAX - START) / STEP_SIZE; noOfLoops++; int noOfPrintingStars = START; boolean startDecreasing = false; for (int i = 0; i < (noOfLoops * 2 - 1); i++) { for (int j = 0; j < noOfPrintingStars; j++) { System.out.print("*"); } System.out.println(); if (startDecreasing) { noOfPrintingStars = noOfPrintingStars - STEP_SIZE; } else { noOfPrintingStars = noOfPrintingStars + STEP_SIZE; } if (noOfPrintingStars == MAX) { startDecreasing = true; } } } }

3. Write a program that reads from the user four integers representing the numerators and denominators of two fractions, calculates the results of the two fractions and displays the values of the fractions sum, subtraction, multiplication and division.

3. Write a program that reads from the user four integers representing the numerators and denominators of two fractions, calculates the results of the two fractions and displays the values of the fractions sum, subtraction, multiplication and division. Sample run: Enter the numerator and denominator of the first fraction: 6 4 Enter the numerator and denominator of the second fraction: 8 5 The sum is: 3.1 The subtraction is: -0.1 The multiplication is: 2.4 The division is: 0.9375

2. Write a program that reads in from the user an integer (num) between 1000 and 9999. Then it prompts the user to enter an integer (d) between 0 and 9 and a character (ch). Your program should replace the second and the last digit in num with d and it should display the character that precedes (ch) followed by the number after the change and then the character that comes after (ch). Use the division and modulus operators to extract the digits from num. Sample run: Enter an integer between 1000 and 9999: 2134 Enter a digit (between 0 and 9): 6 Enter a character: b Number was 2134. Result: a2636c.

import java.io.*; import java.text.*; public class Fraction { public static void main(String a[])throws IOException { DataInputStream r = new DataInputStream(System.in); System.out.print("Enter the numerator and denominator of the first fraction : "); String firstNum = r.readLine(); System.out.print("Enter the numerator and denominator of the second fraction : "); String secondNum = r.readLine(); ComputeFraction cf = new ComputeFraction(firstNum,secondNum); System.out.println("The sum is: " + cf.getSum()); System.out.println("The subtraction is: " + cf.getDiff()); System.out.println("The multiplication is: " + cf.getProduct()); System.out.println("The division is: " + cf.getQuotient()); } } class ComputeFraction { DecimalFormat df = new DecimalFormat("#.##"); double num1; double num2; public ComputeFraction(String firstNum, String secondNum) { String arr1[] = firstNum.split(" "); String arr2[] = secondNum.split(" "); num1 = Double.parseDouble(arr1[0]) / Double.parseDouble(arr1[1]); num2 = Double.parseDouble(arr2[0]) / Double.parseDouble(arr2[1]); } public double getSum() { return Double.parseDouble(df.format(num1+num2)); } public double getDiff() { return Double.parseDouble(df.format(num1-num2)); } public double getProduct() { return Double.parseDouble(df.format(num1*num2)); } public double getQuotient() { return Double.parseDouble(df.format(num1/num2)); } }

Solution for Question 2: import java.util.ArrayList; import java.util.Scanner; class Actions{ @SuppressWarnings("unused") private int num; @SuppressWarnings("unused") private int d; @SuppressWarnings("unused") private char ch; public void perform(int num, int d, char ch) { this.num=num; this.d=d; this.ch=ch; ArrayList list =new ArrayList(); String [] numberString = Integer.toString(num).split(""); list.add(Character.toString((char) (ch-1))); list.add(numberString[1]); list.add(Integer.toString(d)); list.add(numberString[3]); list.add(Integer.toString(d)); list.add(Character.toString((char) (ch+1))); StringBuilder result= new StringBuilder(); for (String s: list) result.append(s); System.out.println("Temp Result : "+result); } } public class Tricky { public static void main (String[] args ){ System.out.println("Please enter Number between 1000 to 9999 :"); @SuppressWarnings("resource") int num = new Scanner(System.in).nextInt(); System.out.println("Please enter Number between 0 to 9 :"); @SuppressWarnings("resource") int d = new Scanner(System.in).nextInt(); System.out.println("Please enter character :"); @SuppressWarnings("resource") char ch = new Scanner(System.in).next().charAt(0); @SuppressWarnings("rawtypes") Actions acs = new Actions(); acs.perform(num,d,ch); } }

1. Write a program that takes three double values x0, v0, and t from the user and prints the value x0 +v0t +g t2/2, where g is the constant 9.78033. This value is the displacement in meters after t seconds when an object is thrown straight up from initial position x0 at velocity v0 meters per second. Sample run: Enter the value of x0, v0 and t: 0 2 2 The displacement in meters after 2 seconds when an object is thrown straight up from initial position 0 at velocity 2meters per second is: 23.56066

public static void printPyramid(int n) { char s = '*'; for (int i = 1; i <= n/2; i++) { for(int j=(i*2-1);j>0;j--){ System.out.print("* "); } System.out.println(); } for (int i = n/2+1; i >= 0; i--) { for(int j=(i*2-1);j>0;j--){ System.out.print("* "); } System.out.println(); } }

Whats the answer for the second one?

Can you post string related coding question? Please send to this mail: [email protected]

here is my list of programs for practice list of Java Program Java Program to convert celsius to Farenheit and vice-versa area of circle perimeter of circle are of rectangle perimeter of rectangle print alphabets print multiplication table largetst of three integers floyd's triangle pascal triangle add matrices transpose matrix multiply matrix perfect number or not find common elements between two arrays binary to decimal conversion inverse of matrix

exercise for anyone interested? 1. Write a program that will print the following output 1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 18 8 4 2 1 exercise number 2 2. Write a class named “Stock” to model a stock. The properties and methods of the class are shown in figure below. The method “changePercent” computes the percentage of the change of the current price vs the previous closing price. Write a client program to test the “Stock” class. In the client program, create a Stock object with the stock symbol SUNW, name Sun Microsystem Inc, previous closing price of 100. Set a new current price randomly and display the price change percentage. Stock private String symbol private String name private double previousClosingPrice private double currentPrice public Stock() public Stock(String symbol, String name) public String getSymbol() public String getName() public double getPreviousClosingPrice() public double getCurrentPrice() public void setSymbol(String symbol) public void setName(String name) public void setPreviousClosingPrice(double price) public void setCurrentPrice(double price) public double changePercent()

1. Write a program that will print the following output 1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 18 8 4 2 1

import java.util.Scanner; public class PracticeDemo { public static void getNumber(int number){ int middle=1; String start="1",end="1",output; System.out.println(start); for(int i=1;i<=number;i++){ middle=middle*2; output=start+" "+middle+" "+end; System.out.println(output); start=start+" "+middle; end=middle+" "+end; } } public static void main(String [] args){ Scanner sc=new Scanner(System.in); System.out.println("Enter the number"); int x=sc.nextInt(); getNumber(x); sc.close(); } } output: 1 1 2 1 1 2 4 2 1 1 2 4 8 4 2 1 1 2 4 8 16 8 4 2 1 1 2 4 8 16 32 16 8 4 2 1 1 2 4 8 16 32 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 256 512 256 128 64 32 16 8 4 2 1 1 2 4 8 16 32 64 128 256 512 1024 512 256 128 64 32 16 8 4 2 1

I would say we should have i<number, instead of i<=number , So that the correct number of rows will print

yes you are right.

Program#1 //for beginners Question: Write a program to count and print the frequency of word in a sentence(both accepted from the user) For example:Inputs//sentence-The lazy lion jumped over the the sharp fence) just kidding! word to be searched-the(irrespective of the case) The normal way of doing it wud be a little difficult nested loops and compare each letter after finding the match of the first letter. Ill show u my way of doing!! import java.io.*; class freqWORD { int count=0; public void main()throws IOException { BufferedReader b=new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter a line"); String line=b.readLine(); System.out.println("Enter thew word to be searched"); String word=b.readLine(); line=" "+line +" " ; line=line.replace(word, "0"); for(int i=0; i<line.length(); i++) { if(line.charAt(i)=='0'&&line.charAt(i+1)==' '&&line.charAt(i-1)==' ') { count++; } } System.out.println("the word is repeated " +count +" times"); System.out.println(line); } } Better?!

The easiest way would be below: import java.io.*; class freqWORD { public static void main(String[] args)throws IOException { int count=0; BufferedReader b=new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter a line"); String line=b.readLine(); System.out.println("Enter thew word to be searched"); String word=b.readLine(); String lines[] = line.split(" "); for( String s: lines){ if (word.equals(s)){ count++; } } System.out.println("the word is repeated " +count +" times"); System.out.println(line); } }

java homework questions

Wap to find the product of first 20 numbers and display in proper format.

I have a ques. How to create application by taking integer to make palidrome coding....

Write a program in Java in DD array to convert all the elements into next prime numbers and display the changed array

Answer: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; class Solution{ public int[] strArrayToIntArray(String[] a){ int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) { b[i] = Integer.parseInt(a[i]); } return b; } public int nextPrime(int num) { num++; for (int i = 2; i <num; i++) { if(num%i == 0) { num++; i=2; } else{ continue; } } return num; } public int[] nextPrime(int[] data) { for (int i=0;i<data.length;i++){ data[i]=nextPrime(data[i]); } return data; } } public class NextPrime { public static void main (String[] args) throws IOException{ System.out.println("Enter the numbers Separated space "); BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); String s =br.readLine(); String [] question = s.split(" "); Solution sol = new Solution(); int[] data = sol.strArrayToIntArray(question); int [] result = sol.nextPrime(data); System.out.println("Result is :"+Arrays.toString(result)); } }

write a program in java to accept a string from user by command line argument and display the vowel ?

Hello @Unknown, you can find the solution of displaying vowel or counting vowel here

Solution: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class vowelCount { public static void main (String [] args) throws IOException{ BufferedReader b=new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter a line"); String line=b.readLine(); String[] solution = line.split("(?!^)"); System.out.println("Word is :" +line); System.out.println("Vowels are :"); for (String s :solution) { char c= s.charAt(0); switch(c){ case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println(c); break; default: } } } }

public class Pattern { public static void main(String args[]){ int[][] table = new int[4][4]; for(int row=0; row<table.length; row++) { for(int col=0; col<table[row].length; col++){ System.out.print(" "+row*col+" "); } System.out.println(); } } } output: 0 0 0 0 0 1 2 3 0 2 4 6 0 3 6 9 Output needed is: 0 1 2 3 1 1 2 3 2 2 4 6 3 3 6 9 what did i do wrong?

try below code... for(int row=0; row<table.length; row++) { System.out.print(row+" "); for(int col=1; col<table[row].length; col++){ if(row!=0) System.out.print(row*col+" "); else System.out.print(col+" "); } System.out.println(); }

Sir can you solve this problem? : Write a java multiple choice examination program. with 10 questions only (need a specific question). Let the user choose answer and at the end of the program output the total points to the user, output also the number of correct and wrong answer an: if the user got 8-10 say "Your in A class" f the user got 5-7 say "Your in B class" f the user got 0-4 say "Your Fail" Note: 1. always ask the user if she/he wants to repeat the exam. 2. if yes = repeat the exam 3. if no = exit from the program.

Hi, Sorry for the delay. I have added sample basis of two questions in the below program. import java.util.*; public class JavaOnlineTest { public static String questions(){ Scanner sc=new Scanner(System.in); int output=0; System.out.println("1)Who is the 45th president of USA?"); System.out.println("1.Barrack Obama 2.Hillary Clinton 3.Donald Trump 4.George W Bush"); int answer=sc.nextInt(); if(answer==3) output+=1; else output+=0; System.out.println("2)Who is the 1st Prime Minister of India?"); System.out.println("1.Subash Chandra Bose 2.Jawahar Lal Nehru 3.Sardar Vallabhai Patel 4.Mahatma Gandhi"); answer=sc.nextInt(); if(answer==2) output+=1; else output+=0; //proceed for 3rd question here. System.out.println("Your result out of 10 is "+output); if(output>=0&&output<5){ System.out.println("You've Failed"); }else if(output>4 && output<8){ System.out.println("Your in B Class"); }else if(output>7 && output<=10){ System.out.println("Your in A Class"); } System.out.println("Do you want to retake the test"); System.out.println("Type 'Y' or 'N'"); String retaking=sc.next().trim(); return retaking; } public static void main(String [] args){ boolean retake; String retaking; while(true){ retaking=questions(); if(retaking.equalsIgnoreCase("Y")){ retake=true; }else if(retaking.equalsIgnoreCase("N")){ System.out.println("Good Luck!..."); retake=false; retaking="N"; break; } } } }

Solve this plss.. fLOW CHART thta accetps a number in kilowatts then display its equivalent number in.Hint:1watt=0.0001 Kilowatt. solve this in java programming

A good one is given the length of a your output media (how wide your paper or screen is) print Pascal's Triangle in Triangle form. Stop when the next line of output will exceed your media width. You can do it two ways ... 1 is figure out how how to space the numbers so they all take the same amount of space (the "center" of the numbers are spaced the same from line to line and from each other; this makes a nice looking triangle, but is harder). 2 an easier version is to center the triangle on the page (left to right) but in each line of numbers the number are separated from each other by only one space You can get more lines in the triangle, but the "sides" are not straight and the relationship between elements gets skewed; however this is much easier.

Good questions, can you also post answer, that would be very useful for other readers?

Hi! I need help please. I need the code for this exercise please. At a certain store they sell blank CD's with the following discounts: * 10% for 120 or more * 5% for 50 or more * 1% for 15 or more * no discount for 14 or less Write a program that asks for a number of discs bought and outputs the correct discount.

aaaaa bbbbb AAAAA BBBBB CAN ANY ONE HELP MET

Write switch case program to show given date(dd/mm/yy) in words format. import java.util.Scanner; class Date{ public static void main(String[] args) { String dow; String wowby; String yowby; Double n1,n2,res; Scanner scan = new Scanner (System.in); System.out.print("Enter Date (dd/mm/yy): "); String date = scan.nextLine(); String dd = date.substring(0,2); String mm = date.substring(3,5); String yy = date.substring(6,8); int d = Integer.valueOf(dd); int m = Integer.valueOf(mm); int y = Integer.valueOf(yy); boolean valid = ((d>=1) && (d<31)); //||((m>=1) && (m<12));//||((y>=00) && (y<99)); if(!valid) System.out.print("Invalid date"); else { switch (dd) { case "01": System.out.print("First of "); switch (mm) { case "01": System.out.print("January,2020"); break;

WAP to accept two numbers and find the average OF THE AVERAGES OF THEIR DIGITS

Write a program that reads in from the user an integer (num) between 1000 and 9999. Then it prompts the user to enter an integer (d) between 0 and 9 and a character (ch). Your program should replace the second and the last digit in num with d and it should display the character that precedes (ch) followed by the number after the change and then the character that comes after (ch). Use the division and modulus operators to extract the digits from num.

Feel free to comment, ask questions if you have any doubt.

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview, 3) list the features of java programming language..

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.
  • Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

4) What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

5) What is the difference between JDK, JRE, and JVM?

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

  • Standard Edition Java Platform
  • Enterprise Edition Java Platform
  • Micro Edition Java Platform

6) How many types of memory areas are allocated by JVM?

Many types:

  • Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
  • Heap: It is the runtime data area in which the memory is allocated to the objects
  • Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
  • Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
  • Native Method Stack: It contains all the native methods used in the application.

7) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.

9) What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

10) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

11) What is classloader?

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  • Bootstrap ClassLoader : This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
  • Extension ClassLoader : This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  • System/Application ClassLoader : This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

12) Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:

compile it by javac .java

run it by java A

13) Is delete, next, main, exit or null keyword in java?

14) if i don't provide any arguments on the command line, then what will the value stored in the string array passed into the main() method, empty or null.

It is empty, but not null.

15) What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

16) What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

17) What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.

18) What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static .

19) What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

20) What is the output of the following Java program?

The output of the above code will be

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint . Therefore, the output will be 30Javatpoint .

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020 .

21) What is the output of the following Java program?

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint .

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpoint to produce the output as Javatpoint200 .

22) What is the output of the following Java program?

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.

Core Java - OOPs Concepts: Initial OOPs Interview Questions

There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. However, they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions, etc. for better understanding.

23) What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object's data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

24) What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

25) What is the difference between an object-oriented programming language and object-based programming language?

There are the following basic differences between the object-oriented language and object-based language.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects, for example, JavaScript has window object.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc.

26) What will be the initial value of an object reference which is defined as an instance variable?

All object references are initialized to null in Java.

Core Java - OOPs Concepts: Constructor Interview Questions

27) what is the constructor.

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

28) How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

Java Constructors

29) What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java default constructor

30) Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the constructor). More Details.

31)Is constructor inherited?

No, The constructor is not inherited.

32) Can you make a constructor final?

No, the constructor can't be final.

33) Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

34) What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

35) What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructors vs Methods

36) What is the output of the following Java program?

The output of the following program is:

Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the two integer parameters is called.

37) What is the output of the following Java program?

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

38) What is the output of the following Java program?

There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.

Core Java - OOPs Concepts: static keyword Interview Questions

39) what is the static variable.

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Static Variable

40) What is the static method?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable.

41) What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.

42) Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation. More Details.

43) Can we override the static methods?

44) what is the static block.

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

45) Can we execute a program without main() method?

Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible. More Details.

46) What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

47) What is the difference between static (class) method and instance method?

48) can we make constructors static.

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

49) Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

50) Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.

Core Java - OOPs Concepts: Inheritance Interview Questions

51) what is this keyword in java.

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.

java this keyword

52) What are the main uses of this keyword?

There are the following uses of this keyword.

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke the current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as an argument in the constructor call.
  • this can be used to return the current class instance from the method.

53) Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

54) Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.

55) How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

56) What are the advantages of passing this into a method instead of the current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.

  • this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

57) What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Multiple inheritance is not supported in Java through class.

58) Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

  • Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
  • Runtime polymorphism cannot be achieved without using inheritance.
  • We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
  • Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
  • Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.

59) Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.

60) Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

61) What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

Employee.java

62) What is composition?

Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

63) What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

64) Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.

65) What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

66) How can constructor chaining be done by using the super keyword?

67) what are the main uses of the super keyword.

There are the following uses of super keyword.

  • super can be used to refer to the immediate parent class instance variable.
  • super can be used to invoke the immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.

68) What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

69) What is the output of the following Java program?

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.

70) Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

71)What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

Core Java - OOPs Concepts: Method Overloading Interview Questions

72) what is method overloading.

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.

  • By Changing the number of arguments
  • By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

73) Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

74) Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.

75) Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

76) What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.

Java Method Overloading with Type Promotion

As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or double and so on. Consider the following example.

77) What is the output of the following Java program?

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.

Core Java - OOPs Concepts: Method Overriding Interview Questions

78) what is method overriding:.

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

79) Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

80) Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

81) Can we override the overloaded method?

82) difference between method overloading and overriding., 83) can we override the private methods.

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

84) Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

85) Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

86) What is the output of the following Java program?

87) can you have virtual functions in java.

Yes, all functions in Java are virtual by default.

88) What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.

89) What is the output of the following Java program?

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.

Core Java - OOPs Concepts: final keyword Interview Questions

90) what is the final variable.

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

final keyword in java

91) What is the final method?

If we change any method to a final method, we can't override it. More Details.

92) What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

93) What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

94) Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block. More Details.

95) Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

96) What is the output of the following Java program?

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

97) What is the output of the following Java program?

The getDetails() method is final; therefore it can not be overridden in the subclass.

98) Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

100) What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

You may also like:

  • Java Interview Questions
  • SQL Interview Questions
  • Python Interview Questions
  • JavaScript Interview Questions
  • Angular Interview Questions
  • Selenium Interview Questions
  • Spring Boot Interview Questions
  • HR Interview Questions
  • C Programming Interview Questions
  • C++ Interview Questions
  • Data Structure Interview Questions
  • DBMS Interview Questions
  • HTML Interview Questions
  • IAS Interview Questions
  • Manual Testing Interview Questions
  • OOPs Interview Questions
  • .Net Interview Questions
  • C# Interview Questions
  • ReactJS Interview Questions
  • Networking Interview Questions
  • PHP Interview Questions
  • CSS Interview Questions
  • Node.js Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AWS Interview Questions
  • Accounting Interview Questions

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

Java Tutorial

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

Java is a popular programming language.

Java is used to develop mobile apps, web apps, desktop apps, games and much more.

Examples in Each Chapter

Our "Try it Yourself" editor makes it easy to learn Java. You can edit Java code and view the result in your browser.

Try it Yourself »

Click on the "Run example" button to see how it works.

We recommend reading this tutorial, in the sequence listed in the left menu.

Java is an object oriented language and some concepts may be new. Take breaks when needed, and go over the examples as many times as needed.

Java Exercises

Test yourself with exercises.

Insert the missing part of the code below to output "Hello World".

Start the Exercise

Advertisement

Test your Java skills with a quiz.

Start Java Quiz

Learn by Examples

Learn by examples! This tutorial supplements all explanations with clarifying examples.

See All Java Examples

My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study W3Schools without using My Learning.

java homework questions

Java Keywords

Java String Methods

Java Math Methods

Download Java

Download Java from the official Java web site: https://www.oracle.com

Java Exam - Get Your Diploma!

Kickstart your career.

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. Do my Java homework

    java homework questions

  2. Solved 2 Java programming questions

    java homework questions

  3. Solved In this assignment you will write a java program that

    java homework questions

  4. Help with Java Programming Assignment in 2020

    java homework questions

  5. Java Programming Homework Help

    java homework questions

  6. Solved Homework: Homework01. Write a Java program that

    java homework questions

VIDEO

  1. CS Home Work / UE5 Development

  2. Writing methods in Java

  3. 1. JavaSimpleHW 1-3

  4. 1. JavaSimpleHW 1-1

  5. 1. Java Simple ANS 1-6

  6. 1. Java Simple ANS 1-7

COMMENTS

  1. 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. ... Java is the foundation for virtually every type of networked application and is the global standard for developing and ...

  2. 10 Java Code Challenges for Beginners

    Learn JavaScript Learn to Code with Blockly 10 Java code challenges to practice your new skills 1. Word reversal For this challenge, the input is a string of words, and the output should be the words in reverse but with the letters in the original order. For example, the string "Dog bites man" should output as "man bites Dog."

  3. Java Exercises

    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 Good luck!

  4. 800+ Java Practice Challenges // Edabit

    Very Easy Return the Sum of Two Numbers Create a method that takes two integers as arguments and returns their sum. Examples SumOfTwoNumbers (3, 2) 5 SumOfTwoNumbers (-3, -6) -9 SumOfTwoNumbers (7, 3) 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab.

  5. 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.

  6. Java Basic Programming Exercises

    JavaFx Exercises Home ..More to come.. a. -5 + 8 * 6 b. (55+9) % 9 c. 20 + -3*5 / 8 d. 5 + 15 / 3 * 2 - 8 % 3 Write a Java program that takes two numbers as input and displays the product of two numbers. 2.9760461760461765 Write a Java program to print the area and perimeter of a circle. Click me to see the solution

  7. Questions to practice for Java

    Practice questions on Java. Let's program. Know data-types. Java Operators. Input by user. Decide if or else. Loop loop loop. Have your own methods. Java Array. Characters and string. Java Classes and Objects. Java Array of Objects. subclass. Java Constructor Overloading. More about methods. Java Abstract class. FOLLOW US. CATEGORIES. PRO ...

  8. Practice questions of Java

    Practice questions on Java Classes and Objects Level 1 Level 2 Level 1 1. Write a program to print the area of a rectangle by creating a class named 'Area' having two methods. First method named as 'setDim' takes length and breadth of rectangle as parameters and the second method named as 'getArea' returns the area of the rectangle.

  9. Java Programming

    Exercise 20. At Quizlet, we're giving you the tools you need to take on any subject without having to carry around solutions manuals or printing out PDFs! Now, with expert-verified solutions from Java Programming 9th Edition, you'll learn how to solve your toughest homework problems. Our resource for Java Programming includes answers to ...

  10. 45 Java Programming Exercises With Solutions

    45 Java Programming Exercises With Solutions Written by Ashwin Joy in Programming If you have learned the basics of Java, it is the right time to solve some practice problems. Practicing and solving problems will help you master the Java programming language and take your skills to the next level.

  11. Java Programming Exercises with Solutions

    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. Java Programming Exercises to Improve your Coding Skills with Solutions.

  12. Java Collection Exercises

    Java Collection: TreeSet Exercises [16 exercises with solution] 1. Write a Java program to create a tree set, add some colors (strings) and print out the tree set. Click me to see the solution. 2. Write a Java program to iterate through all elements in a tree set. Click me to see the solution.

  13. Assignments

    BouncingBox.java . DrawGraphics.java . 6 Graphics strikes back! assn06.zip (This ZIP file contains: 6 .java files.) 7 Magic squares Mercury.txt . Luna.txt . Solutions . Course Info Instructors Evan Jones; Adam Marcus; Eugene Wu; Departments Electrical Engineering and Computer Science ...

  14. Java Programming Language Questions and Answers

    Explain the answers. 1. Each pair of digits has a chance 1/100 of being 33... View Answer Simulate the performance of an investment that has an expected return of 6.0% per year with a standard...

  15. Online Java Programming Homework Help

    1 hour avg response $15-$50 hourly rate Le Hoang (Expert25) Bachelor of Science (B.S.) I'm good at Computer Science. I always provide detailed answers to questions that students may have while reading my solutions. Mathematics Computer Science Engineering +43 4.8/5 (4,242+ sessions) 40 minutes avg response Alec (duova) Master of Science (M.S.)

  16. Java Interview Questions and Answers (2023 Updated)

    Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Whether you are a fresher, a graduate, or an experienced candidate with several years of Java programming experience - preparation for a java Interview is a daunting task. In this article, we will provide a comprehensive guide to Java Interview Questions ...

  17. Java homework question

    The code is kind of awful; for each else content the code declare and instantiate a variable which will never be used (as a variable declared in a block can't be used outside the said block) your compiler will say that your code is not a valid statement and won't compile.. Plus, most of the if will never pass because the condition can't be accessed. For example :

  18. Free AI Java Homework Helper

    StudyMonkey Your Personal AI Java Tutor Subject * Java Any subject Computer Science History Java Language Math Science --- More Subjects --- Accounting American College Testing (ACT) Algebra Algorithms Anatomy Anthropology Advanced Placement Exams (AP Exams) Arabic Language Archaeology Astronomy BAR Exam Biochemistry Biology Botany Business C++ C#

  19. 10 Programming questions and exercises for Java Programmers

    And, If you need to refresh your Data Structure and algorithm skills to solve these Programming questions and exercise then check out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It's a great course to brush up on essential data structures like an array, linked list, binary tree, hash table, stack, queue, and basic techniques like recursion, dynamic programming, greedy ...

  20. 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 ...

  21. 300 Core Java Interview Questions (2023)

    300 Core Java Interview Questions | Set 1. There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers.

  22. math

    int num = 1, divisor1 = 1, divisor2 = 1, divSum = 0, perfNum1 = 0, perfNum2 = 0, perfNum3 = 0, perfNum4 = 0; Note: These changes will make your code compile but it isn't yet correct. As this is homework, try and see if you can make an attempt to fix it yourself. A couple of cleanups to make things look a bit nicer.

  23. Java Tutorial

    Click on the "Run example" button to see how it works. We recommend reading this tutorial, in the sequence listed in the left menu. Java is an object oriented language and some concepts may be new. Take breaks when needed, and go over the examples as many times as needed.