Java Coding Practice

core java assignments for practice

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

core java assignments for practice

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.

core java assignments for practice

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

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

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

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

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

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

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

This program will display the following:

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

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

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

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

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

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

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

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

The syntax for an if statement is as follows:

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

Here's a simple example:

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

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

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

The output of this program is here:

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

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

So the output of this program is:

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

Here are some Java exercises to practice booleans:

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

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

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

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

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

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

Here are some Java coding challenges to practice the loops:

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

What you should know about arrays in Java:

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

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

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

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

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

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

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

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

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

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

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

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

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

Example of comparing strings using the equals() method.

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

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

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

Here are some Java programming exercises to practice the strings:

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

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

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

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

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

Here are some coding challenges in Java object creation:

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

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

You declare them with the static modifier.

Static Methods

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

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

Static Classes

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

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

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

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

Java Guides

Java Guides

Search this blog, core java mcq - top 100 questions and answers.

Welcome to this comprehensive guide featuring 100 Multiple-Choice Questions (MCQs) on Core Java. Java remains one of the most popular, versatile, and widely-used programming languages in the world, and understanding its core concepts is essential for anyone aspiring to become proficient in it. Whether you are a beginner, an intermediate programmer, or even an expert looking for a quick refresher, this blog post is your go-to resource.

We've curated these questions to cover all the important Core Java topics such as variables, data types, operators, control statements, loops, arrays, methods, inheritance, polymorphism, interfaces, packages, exception handling, multithreading, and much more. This ensures a rounded understanding of Java’s fundamentals.

But we didn’t stop there! Each question is followed by the correct answer as well as an explanation. These explanations are designed to reinforce your knowledge and help clarify any doubts you may have.

Are you ready to level up your Java skills? Let's dive into the quiz!

1. Who developed the Java programming language?

Explanation:.

Java was developed by Sun Microsystems. Later, Oracle acquired Sun Microsystems in 2010.

2. In which year was the first version of Java released?

The first version of Java, Java 1.0, was officially released by Sun Microsystems in 1995.

3. What was the original name for Java?

Java was initially called "Oak." It was developed by Sun Microsystems' Green Team, led by James Gosling.

4. What does JVM stand for?

JVM stands for Java Virtual Machine. It is a virtualization engine that enables Java applications to run on various hardware platforms without modification.

5. Which of the following is responsible for converting bytecode into machine code?

JVM is responsible for converting bytecode (intermediate code) into machine code, ensuring Java's "Write Once, Run Anywhere" philosophy.

6. What does JDK include?

JDK (Java Development Kit) includes the Java Runtime Environment (JRE) and other tools like the Java compiler (javac).

7. Which of the following is NOT a part of the JRE?

The Java compiler (javac) is a part of the JDK (Java Development Kit) and not the JRE (Java Runtime Environment).

8. What is the primary function of JRE?

JRE (Java Runtime Environment) is responsible for providing the runtime environment where Java programs can be executed.

9. Can you run a Java program without JRE?

JRE (Java Runtime Environment) is essential for running Java programs. Without it, the Java bytecode cannot be executed.

10. Is JVM platform-independent?

While Java code (bytecode) is platform-independent, JVMs are not. Each operating system has its own JVM.

11. Which operator is used to perform bitwise "AND" operation?

The & operator is used to perform a bitwise "AND" operation.

12. What does the == operator compare in Java objects?

For objects, the == operator compares references, not the content of the objects. To compare the content, you would typically use the .equals() method.

13. Which operator is used for logical "AND" operation?

The && operator is used for the logical "AND" operation and is short-circuiting, meaning it won't evaluate the second operand if the first one is false.

14. Which of the following is a unary operator?

Unary operators are operators that act on a single operand. +, -, and ! are all unary operators in Java.

15. Which operator has the highest precedence?

Parentheses () have the highest precedence in Java and are used to explicitly specify the order of evaluation in expressions.

16. What is the output of the expression true || false?

The || operator is a logical OR. The result of true || false is true.

17. Which of the following is not a primitive data type in Java?

String is a reference data type, not a primitive data type.

18. What is the default value of the int data type?

The default value of the int data type is 0. In Java, each primitive data type has a default value.

19. Which of the following data types can store a floating-point number?

The double data type can store floating-point numbers. There's also float, but it wasn't listed among the options.

20. Which data type can store a single character?

The char data type is used to store a single character.

21. How many bits does the long data type use?

The long data type uses 64 bits to store its values.

22. What's the main difference between int and Integer in Java?

int is a primitive data type, whereas Integer is a wrapper class that provides methods to operate on the int data type.

23. Which loop construct in Java is best suited when the number of iterations is known?

The for loop in Java is best suited when the number of iterations is known.

24. What is the purpose of the continue statement in a loop?

The continue statement in Java is used to skip the current iteration of a loop and move to the next iteration.

25. Which loop construct in Java is best suited when the number of iterations is unknown?

The while loop in Java is used when the number of iterations is unknown or depends on a certain condition.

26. What is the key difference between a while loop and a do-while loop in Java?

The key difference between a while loop and a do-while loop in Java is the timing of the condition check. In a while loop, the condition is checked before the loop body is executed, whereas in a do-while loop, the condition is checked after the loop body is executed.

27. Which loop construct guarantees that the loop body is executed at least once?

The do-while loop in Java guarantees that the loop body is executed at least once, as the condition is checked after the loop body is executed.

28. What is an infinite loop?

An infinite loop in Java is a loop that never terminates naturally unless interrupted externally or using a break statement.

29. Which statement is used to exit a loop prematurely?

The break statement in Java is used to exit a loop prematurely and continue with the execution of the code outside the loop.

30. Which loop construct is best suited for iterating over an array or a collection?

The for loop in Java is best suited for iterating over an array or a collection, as it provides a convenient way to control the iteration using an index or an iterator.

31. How do you declare an array in Java?

Arrays in Java can be declared using either int[] arrayName; or int arrayName[];.

32. Which method is used to get the length of an array in Java?

The length property is used to get the number of elements in an array, e.g., arrayName.length.

33. How do you initialize an array in Java?

Arrays can be initialized using the new keyword followed by the type, and values enclosed in curly braces.

34. What happens when you try to access an array element with an index that is out of bounds?

Accessing an element outside the array's range will throw an ArrayIndexOutOfBoundsException.

35. How can you check if two arrays are equal in Java?

The Arrays.equals() method is the correct way to check if two arrays are equal. Using the == operator checks for reference equality, not the content.

36. How do you access the fourth element of an array named numbers?

Arrays use zero-based indexing, which means the fourth element is accessed using index 3.

37. Which of the following operators is used for concatenation of two strings?

In Java, the + operator is overloaded for string concatenation. When used between two strings, it concatenates them.

38. Which of the following creates a mutable string?

StringBuilder is a mutable sequence of characters, whereas String is immutable.

39. In Java, strings are:

Once a String object is created, its content cannot be modified. Hence, it's considered immutable.

40. How do you find the length of a string named 'example'?

The length() method returns the number of characters in a string.

41. What is the result of the expression "Java" + "Programming"?

The + operator concatenates two strings without adding any extra spaces.

42. Which method is used to compare two strings for equality?

The equals() method compares the content of two strings. The == operator compares the memory addresses, not the content.

43. Which class can create a string that is thread-safe?

StringBuffer is thread-safe, whereas StringBuilder is not.

44. What is the root class for all Java classes?

The Object class is the root of the Java class hierarchy. Every class has Object as a superclass.

45. What is polymorphism?

Polymorphism allows objects to be treated as instances of their parent class, leading to simplified code and a way to use objects dynamically.

46. What is encapsulation in Java?

Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts. The main idea behind encapsulation is to bind together the data (attributes) and the methods (functions) that operate on the data into a single unit or class. It also serves to hide the internal state of an object and requires the use of methods to access the object's data. This ensures that unwanted or unexpected modifications don't occur.

47. What is inheritance in Java?

Inheritance is a mechanism in Java that allows a class to inherit properties and behaviors from another class. It promotes code reuse by enabling the creation of subclasses that inherit the attributes and methods of a superclass. Subclasses can also add their own unique attributes and methods.

48. What is polymorphism in Java?

Polymorphism refers to the ability of an object to take on many forms or have multiple behaviors. In Java, polymorphism is achieved through method overriding and method overloading. It allows objects of different classes to be treated as objects of a common superclass, providing flexibility and extensibility.

49. What are abstract classes in Java?

Abstract classes in Java cannot be instantiated directly and are typically used as blueprints for creating objects. They can contain abstract methods (methods without implementation) and regular methods. Abstract classes provide a way to define common behavior and enforce specific methods to be implemented by subclasses.

50. What is the purpose of the "super" keyword in Java?

The "super" keyword in Java is used to refer to the superclass (or parent class) of the current object. It is commonly used to invoke the superclass constructor or methods within the subclass. The "super" keyword allows for code reuse and accessing superclass members that may be overridden in the subclass.

51. What is the purpose of the "this" keyword in Java?

The "this" keyword in Java is used to refer to the current object within an instance method or constructor. It is often used to distinguish between instance variables and method parameters or to access methods and variables of the current object.

52. What is the purpose of the "final" keyword in Java?

The "final" keyword in Java can be used to prevent the inheritance of a class, overriding of a method, or modification of a variable's value. When a class, method, or variable is declared as final, it cannot be further extended, overridden, or modified, respectively.

53. What is an interface in Java?

An interface in Java is a blueprint that can be used to implement classes. It can have methods and variables, but the methods are abstract by default.

54. Which keyword is used to implement an interface?

The implements keyword is used by classes to implement an interface.

55. Can an interface extend another interface in Java?

Interfaces can extend other interfaces in Java, allowing an interface to inherit abstract methods from another interface.

56. Can an interface have a constructor?

Interfaces cannot have constructors because they cannot be instantiated.

57. Which of the following access modifiers are implicitly applied to variables in an interface?

Variables in an interface are implicitly public, static, and final.

58. Is it possible to create an instance of an interface?

We cannot instantiate an interface directly. However, we can create reference variables of an interface type.

59. How many interfaces can a Java class implement?

A Java class can implement any number of interfaces.

60. Can an interface inherit from a class?

An interface cannot inherit from a class. It can only extend other interfaces.

61. Can an interface method be declared as final?

Methods in an interface are implicitly abstract, and abstract methods cannot be final.

62. In Java 9, which type of methods can be added to interfaces to share code between methods?

Starting from Java 9, interfaces can have private methods, which can help in sharing code between methods without exposing them to external classes.

63. An interface with no methods is known as?

An interface with no defined methods is known as a marker interface. It is used to mark classes that support certain capabilities.

64. Which keyword is used to define a default method in an interface?

The "default" keyword is used to define a default method in an interface.

65. Are all methods in an interface abstract?

Prior to Java 8, all methods in an interface were implicitly abstract. However, with Java 8 and onwards, interfaces can have default and static methods.

66. Which of these can be contained in an interface?

An interface can contain abstract methods, constants (public, static, final variables), static methods, and default methods.

67. Which Java feature helps achieve multiple inheritance?

In Java, multiple inheritance is achieved through interfaces. A class can implement multiple interfaces, thereby inheriting the abstract methods of all the interfaces.

68. What is the default access modifier of a method in an interface in Java?

Interface methods are public by default since the idea is for them to be implemented by other classes.

69. Why were default methods introduced in Java 8 interfaces?

Default methods allow developers to add new methods to interfaces with an implementation without affecting classes that already use this interface.

70. Starting from which Java version can an interface contain method implementations?

From Java 8 onwards, interfaces can have default and static method implementations.

71. What is the purpose of the instanceof operator?

The instanceof operator is used to check if an object belongs to a particular class or implements a particular interface.

72. Which keyword is used to declare a class variable?

The static keyword is used to declare a class variable which is common to all instances of a class.

73. Which keyword is used to prevent a class from being inherited?

A class declared as final cannot be subclassed or extended.

74. Which keyword is used to create an instance of a class?

The new keyword is used to instantiate an object from a class.

75. Which keyword is used to inherit the properties and methods from another class?

The extends keyword is used to inherit properties and methods from another class.

76. Which keyword is used to refer to the current instance of a class?

The this keyword is used to refer to the current instance of a class.

77. Which keyword in Java is used for importing packages into a program?

The import keyword is used to import a package or a class into a Java program.

78. What does the transient keyword indicate in a Java class?

The transient keyword indicates that the variable should not be serialized when the class instance is persisted.

79. Which of these is a checked exception?

IOException is a checked exception. Checked exceptions need to be either caught or declared in the method signature using the throws keyword.

80. Which of the following can be used to create a custom checked exception?

To create a custom-checked exception, you can extend the Exception class.

81. Which of these is an unchecked exception?

ArithmeticException, like all subclasses of RuntimeException, is an unchecked exception.

82. Which keyword is used to manually throw an exception in Java?

The throw keyword is used to explicitly throw an exception.

83. Which of these classes is the superclass of all Exception and Error classes?

The Throwable class is the superclass of all exception and error classes.

84. What does the finally block do?

The finally block is executed irrespective of whether an exception is thrown or caught.

85. Which keyword in Java is used for constant variables?

In Java, the final keyword is used to declare constant variables.

86. In Java, what is the primary purpose of the Thread class?

The Thread class in Java is primarily used for creating and executing threads.

87. Which method is used to start the execution of a thread?

The start() method is used to initiate the execution of a thread. It internally calls the run() method.

88. What does the join() method do when called on a thread object?

The join() method makes the currently executing thread wait until the thread on which it's called completes its execution.

89. Which method can be used to momentarily pause the execution of the current thread?

The sleep() method is used to pause the execution of the current thread for a specified period.

90. Which interface provides an alternative to extending the Thread class?

The Runnable interface provides an alternative way to define thread execution behavior without the need to extend the Thread class.

91. What is a daemon thread in Java?

Daemon threads are background threads that usually run continuously, performing tasks like garbage collection.

92. Which interface represents a collection of objects in which duplicate values can be stored?

The List interface in Java allow the addition of duplicate elements.

93. What will be the initial capacity of an ArrayList if it is created with the no-argument constructor?

The default initial capacity of an ArrayList (when created with the no-argument constructor) is 10.

94. What does a Set guarantee?

A Set guarantees no duplicate elements but does not guarantee any specific order of elements.

95. Which List implementation is synchronized?

Vector is synchronized, whereas ArrayList and LinkedList are not.

96. Which interface represents a key-value pair mechanism?

The Map interface represents a key-value pair mapping.

97. Which method is used to check if a Collection is empty?

The isEmpty() method is used to check if a Collection is empty.

98. What does the Collections class sort() method do?

The sort() method in the Collections class sorts the elements in ascending order.

99. What is the key difference between HashSet and TreeSet?

HashSet does not maintain any order whereas TreeSet maintains elements in a sorted order.

100. Which Collection does not allow null values?

Hashtable does not allow null keys or null values.

101. Which method is used to insert an object at a specific position in a List?

The add(index, element) method is used to insert an element at a specific position in a List.

102. Which class provides a thread-safe implementation of the List interface?

Vector is a thread-safe implementation of the List interface.

103. Which interface provides methods to traverse through a collection?

The Iterator interface provides methods to traverse through a collection.

Related Java and Advanced Java Tutorials/Guides

Related quizzes:, post a comment.

Leave Comment

My Top and Bestseller Udemy Courses

  • Spring 6 and Spring Boot 3 for Beginners (Includes Projects)
  • Building Real-Time REST APIs with Spring Boot
  • Building Microservices with Spring Boot and Spring Cloud
  • Full-Stack Java Development with Spring Boot 3 & React
  • Testing Spring Boot Application with JUnit and Mockito
  • Master Spring Data JPA with Hibernate
  • Spring Boot Thymeleaf Real-Time Web Application - Blog App

Check out all my Udemy courses and updates: Udemy Courses - Ramesh Fadatare

Copyright © 2018 - 2025 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub

core java assignments for practice

Java Tutorial

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

You can test your Java skills with W3Schools' Exercises.

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

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

Count Your Score

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

Start Java Exercises

Start Java Exercises ❯

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

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

Welcome to Java! Easy Max Score: 3 Success Rate: 97.05%

Java stdin and stdout i easy java (basic) max score: 5 success rate: 96.86%, java if-else easy java (basic) max score: 10 success rate: 91.37%, java stdin and stdout ii easy java (basic) max score: 10 success rate: 92.71%, java output formatting easy java (basic) max score: 10 success rate: 96.54%, java loops i easy java (basic) max score: 10 success rate: 97.67%, java loops ii easy java (basic) max score: 10 success rate: 97.32%, java datatypes easy java (basic) max score: 10 success rate: 93.69%, java end-of-file easy java (basic) max score: 10 success rate: 97.92%, java static initializer block easy java (basic) max score: 10 success rate: 96.12%, cookie support is required to access hackerrank.

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

50 Java Projects with Source Code for All Skill Levels

Faraz Logo

By Faraz - February 26, 2024

50 Java projects with complete source code, suitable for beginners to experts. Dive into practical coding with these hands-on examples.

Explore 50 Java Projects with Source Code for All Skill Levels.jpg

Java, being one of the most popular programming languages globally, offers a vast array of opportunities for enthusiasts to practice and enhance their coding skills. Engaging in practical projects is one of the most effective ways to master Java programming. Here, we'll explore 50 Java projects with source code across different levels of complexity, suitable for beginners, intermediates, and advanced learners.

Table of Contents

Introduction to Java Projects

Java projects provide hands-on experience and are instrumental in reinforcing theoretical concepts. They offer a practical understanding of Java's syntax, structure, and functionality. Moreover, working on projects enables developers to tackle real-world problems, fostering creativity and problem-solving skills.

1. Calculator

50 Java Projects - Calculator

AuthorHouari ZEGAI
TechnologiesJava
Source Code

Houari ZEGAI's Calculator project offers a great opportunity for beginners to delve into Java programming. This simple yet effective project helps learners understand fundamental concepts like variables, operators, and basic user input/output. With clear, commented code, ZEGAI's Calculator is a fantastic starting point for those new to Java development. By studying and tinkering with this project, beginners can grasp core principles while gaining confidence in their coding abilities.

2. Guess the Number Game

50 Java Projects - Guess the Number Game

AuthorFaraz
TechnologiesJava
Source Code

The "Guess the Number" game is a classic Java project suitable for programmers of all skill levels. This interactive game challenges players to guess a randomly generated number within a specified range. With simple yet engaging gameplay, the "Guess the Number" project provides an excellent opportunity for beginners to practice essential Java concepts while having fun.

3. Currency Converter

50 Java Projects - Currency Converter

AuthorNaeem Rashid
TechnologiesJava
Source Code

The Currency Converter project is a practical and useful Java application that allows users to convert between different currencies. This project is suitable for programmers at various skill levels, providing an opportunity to apply Java programming concepts in a real-world scenario.

In the Currency Converter project, users input an amount in one currency and select the currency they wish to convert it to. The application then retrieves the latest exchange rates from a reliable source, such as an API, and performs the conversion calculation. By implementing this functionality, learners can gain valuable experience working with APIs, handling user input, and performing mathematical operations in Java.

4. Digital Clock

50 Java Projects - Digital Clock

AuthorDanish Khan
TechnologiesJava
Source Code

The Digital Clock project is a straightforward yet engaging Java application that displays the current time in a digital format. This project is suitable for beginners and intermediate programmers alike, offering an opportunity to practice essential Java concepts while creating a useful utility.

In the Digital Clock project, programmers utilize Java's date and time functionality to retrieve the current system time and display it on the screen. By incorporating graphical user interface (GUI) components such as labels and timers, learners can create an interactive clock display that updates in real-time. This hands-on approach allows beginners to familiarize themselves with GUI programming concepts while practicing core Java skills.

5. ToDo App

50 Java Projects - todo app

AuthorIsis Add-ons
TechnologiesJava
Source Code

The ToDo App project is a practical Java application that helps users organize their tasks and manage their daily activities efficiently. This project is suitable for programmers looking to develop their Java skills while creating a useful productivity tool.

In the ToDo App project, users can add tasks to a list, mark them as completed, and remove them as needed. By implementing features such as user input handling, task manipulation, and list management, learners gain valuable experience in Java programming fundamentals. Additionally, this project provides an opportunity to explore concepts like data structures, file handling, and user interface design.

6. QRCodeFX

50 Java Projects - QRCodeFX

AuthorHouari Zegai
TechnologiesJavaFX
Source Code

QRCodeFX is an exciting Java project that allows programmers to generate QR codes dynamically. This project leverages JavaFX, a powerful library for building graphical user interfaces, to create an interactive application for generating and displaying QR codes.

7. Weather Forecast App

50 Java Projects - Weather Forecast App

AuthorPanagiotis Drakatos
TechnologiesJava and Swing
Source Code

The Weather Forecast App project is an exciting Java application that provides users with up-to-date weather information for their location and other selected areas. This project combines Java programming with APIs to create a dynamic and user-friendly weather forecasting tool.

In the Weather Forecast App, users can input their location or select a specific city to view current weather conditions, including temperature, humidity, wind speed, and more. By integrating with a weather API, such as OpenWeatherMap, programmers can retrieve real-time weather data and display it in a clear and visually appealing format.

8. Temperature Converter Tool

50 Java Projects - Temperature Converter Tool

AuthorNikhil Deep
TechnologiesJava
Source Code

The Temperature Converter Tool is a handy Java application that allows users to convert temperatures between different units, such as Celsius, Fahrenheit, and Kelvin. This project provides a practical opportunity for programmers to develop their Java skills while creating a useful utility for everyday use.

In the Temperature Converter Tool, users can input a temperature value along with the unit of measurement (e.g., Celsius, Fahrenheit, or Kelvin) and select the desired output unit. The application then performs the conversion calculation and displays the result, allowing users to quickly and easily convert temperatures with precision.

9. Word Counter Tool

50 Java Projects - Word Counter Tool

AuthorSaurav Kumar
TechnologiesJavaFX
Source Code

The Word Counter Tool is a versatile Java application designed to analyze text and provide valuable insights into word frequency and usage. This project offers programmers a practical opportunity to hone their Java skills while creating a useful utility for text analysis.

In the Word Counter Tool, users can input a block of text or upload a text file, and the application will analyze the content to determine the frequency of each word. By utilizing Java's string manipulation capabilities and data structures such as maps or arrays, programmers can efficiently process the text and generate a comprehensive word count report.

10. Scientific Calculator

50 Java Projects - Scientific Calculator

AuthorVaishnavi Lugade
TechnologiesJava Swing
Source Code

The Scientific Calculator project is an advanced Java application that provides users with a wide range of mathematical functions and operations beyond basic arithmetic. This project is ideal for programmers looking to expand their Java skills while creating a powerful utility for scientific calculations.

In the Scientific Calculator, users can input mathematical expressions, including functions such as trigonometric, logarithmic, and exponential functions, and the application will evaluate and display the result accurately. By leveraging Java's math libraries and implementing parsing algorithms, programmers can create a robust calculator capable of handling complex mathematical computations with precision.

11. Tic Tac Toe

50 Java Projects - Tic Tac Toe

AuthorHouari Zegai
TechnologiesJava (Swing)
Source Code

The Tic Tac Toe project is a classic Java game that provides users with an opportunity to engage in a fun and strategic multiplayer experience. This project is perfect for programmers looking to apply their Java skills while creating an interactive game with simple rules and dynamic gameplay.

In the Tic Tac Toe game, two players take turns marking spaces on a 3x3 grid with their respective symbols (typically X and O), aiming to form a horizontal, vertical, or diagonal line of their symbols before their opponent. By implementing logic to handle user input, validate moves, and check for win conditions, programmers can create a fully functional and enjoyable game experience.

12. Drag and Drop Application

50 Java Projects - Drag and Drop Application

The Drag and Drop Application is a dynamic Java project that enables users to interact with graphical elements by dragging and dropping them across the application's interface. This project provides programmers with an opportunity to explore Java's graphical user interface (GUI) capabilities while creating an intuitive and interactive user experience.

13. Snake Game

50 Java Projects - Snake Game

AuthorJan Bodnar
TechnologiesJava and Swing
Source Code

The Snake Game project is a classic Java game that provides users with an entertaining and addictive gaming experience. This project offers programmers an opportunity to apply their Java skills while creating a dynamic and interactive game with simple yet challenging gameplay mechanics.

In the Snake Game, players control a snake that moves around a grid, consuming food items to grow longer while avoiding collisions with the walls of the grid or the snake's own body. By implementing logic to handle player input, update the snake's position, and detect collisions, programmers can create a compelling and immersive gaming experience.

14. Resume Builder

50 Java Projects - Resume Builder

AuthorMohd Shahbaz
TechnologiesJava Swing
Source Code

The Resume Builder project is a practical Java application designed to assist users in creating professional resumes efficiently. This project offers programmers an opportunity to apply their Java skills while developing a useful tool for individuals seeking to showcase their qualifications and experiences effectively.

15. Student Management System

50 Java Projects - Student Management System

AuthorBitto Kazi
TechnologiesJava
Source Code

The Student Management System project is a comprehensive Java application designed to streamline administrative tasks related to student information and academic records. This project offers programmers an opportunity to apply their Java skills while developing a robust and efficient system for managing student data.

In the Student Management System, administrators can perform various tasks such as adding new students, updating existing records, managing course enrollments, and generating reports. By implementing features such as database integration, user authentication, and data validation, programmers can create a reliable and user-friendly platform for organizing and accessing student information.

16. Rock Paper Scissors

50 Java Projects - Rock Paper Scissors

AuthorDarsh Jain
TechnologiesJava
Source Code

The Rock Paper Scissors project is a classic Java game that provides users with a simple yet entertaining gaming experience. This project offers programmers an opportunity to practice their Java skills while creating a fun and interactive game of chance.

In the Rock Paper Scissors game, players compete against the computer by selecting one of three options: rock, paper, or scissors. The winner is determined based on the rules of the game: rock beats scissors, scissors beats paper, and paper beats rock. By implementing logic to handle player input, generate random computer choices, and determine the outcome of each round, programmers can create an engaging gaming experience.

17. Hangman Game

50 Java Projects - Hangman Game

Authormkole
TechnologiesJava
Source Code

The Hangman Game project is a classic Java game that provides users with a challenging and engaging word-guessing experience. This project offers programmers an opportunity to practice their Java skills while creating a fun and interactive game of wit and strategy.

In the Hangman Game, players attempt to guess a secret word by suggesting letters one at a time. For each incorrect guess, a part of a hangman figure is drawn. The game continues until the player correctly guesses the word or the hangman figure is completed. By implementing logic to handle player input, manage the game state, and select random words, programmers can create an immersive gaming experience.

50 Java Projects - WebCam

AuthorHouari Zegai
TechnologiesJava
Source Code

The Webcam Application project is a Java application designed to interface with a webcam device and capture video or images. This project offers programmers an opportunity to apply their Java skills while creating a versatile tool for webcam usage.

19. Attendance Management System

50 Java Projects - Attendance Management System

AuthorAnum Ramzan
TechnologiesJava and SQL Server
Source Code

The Attendance Management System project is a comprehensive Java application designed to streamline attendance tracking and management processes in educational institutions or workplaces. This project offers programmers an opportunity to apply their Java skills while developing a robust and efficient system for managing attendance records.

In the Attendance Management System, administrators can perform various tasks such as recording attendance, generating attendance reports, managing leave requests, and tracking attendance trends over time. By implementing features such as user authentication, data encryption, and access control, programmers can create a secure and reliable platform for monitoring attendance data.

20. Chess Game

50 Java Projects - Chess Game

Author-
TechnologiesJava Swing UI
Source Code

The Chess Game project is a Java application that offers users a classic and strategic gaming experience. This project provides programmers with an opportunity to apply their Java skills while creating a sophisticated and engaging game of chess.

In the Chess Game, players take turns moving their pieces across an 8x8 grid, aiming to capture their opponent's pieces and ultimately checkmate their opponent's king. By implementing logic to handle player input, validate moves, and simulate game states, programmers can create a challenging and immersive gaming experience.

21. Vehicle Rental Management System

50 Java Projects - Vehicle Rental Management System

AuthorMalaka Madushan
TechnologiesJava
Source Code

The Vehicle Rental Management System is a comprehensive Java application designed to streamline the process of managing vehicle rentals for rental agencies or businesses. This project offers programmers an opportunity to apply their Java skills while developing a robust and efficient system for handling rental operations.

In the Vehicle Rental Management System, administrators can perform various tasks such as adding new vehicles to the inventory, managing rental reservations, tracking rental durations and payments, and generating reports. By implementing features such as database integration, user authentication, and data validation, programmers can create a reliable and user-friendly platform for managing vehicle rentals.

22. Quiz App

50 Java Projects - Quiz

AuthorHouari Zegai
TechnologiesJava and MySQL
Source Code

The Quiz App project is a Java application designed to provide users with an interactive and educational quiz experience. This project offers programmers an opportunity to apply their Java skills while creating a dynamic and engaging platform for quiz-taking.

In the Quiz App, users can choose from a variety of quiz topics or categories, such as science, history, literature, or general knowledge. The application presents users with multiple-choice questions related to the selected topic and provides instant feedback on their answers. By implementing logic to handle user input, track scores, and display quiz results, programmers can create an immersive and rewarding quiz experience.

23. Voting Management System

50 Java Projects - Voting Management System

AuthorNiraj Ranjan
TechnologiesJava Swing and Postgres
Source Code

The Voting Management System is a sophisticated Java application designed to facilitate the management of voting processes in elections or organizational decision-making. This project offers programmers an opportunity to apply their Java skills while developing a secure and efficient system for managing voting operations.

In the Voting Management System, administrators can oversee various aspects of the voting process, including voter registration, ballot creation, voter authentication, vote counting, and result reporting. By implementing features such as user authentication, encryption algorithms, and audit trails, programmers can create a robust and tamper-resistant platform for conducting fair and transparent elections.

24. Electricity Billing System

50 Java Projects - Electricity Billing System

AuthorAdarsh Verma
TechnologiesJava Swing and MySQL
Source Code

The Electricity Billing System is a Java application designed to automate and streamline the process of managing electricity bills for customers. This project offers programmers an opportunity to apply their Java skills while developing an efficient and user-friendly system for billing and invoicing.

In the Electricity Billing System, administrators can perform various tasks such as adding new customers, recording meter readings, calculating electricity consumption, generating bills, and processing payments. By implementing features such as database integration, billing algorithms, and user interfaces, programmers can create a reliable and accurate platform for managing electricity billing operations.

25. Online Shopping Cart (E-Commerce Website)

50 Java Projects - Online Shopping Cart E-Commerce Website

AuthorShashi Raj
TechnologiesJava, Servlet, and MySQL
Source Code

The Online Shopping Cart project is a comprehensive Java application designed to provide users with a seamless and convenient online shopping experience. This project offers programmers an opportunity to apply their Java skills while developing a feature-rich and user-friendly e-commerce platform.

In the Online Shopping Cart, users can browse through a catalog of products, add items to their cart, and proceed to checkout to complete their purchase. By implementing features such as user authentication, product search functionality, shopping cart management, and secure payment processing, programmers can create a robust and reliable platform for online shopping.

26. Online BookStore

50 Java Projects - Online BookStore

AuthorShashi Raj
TechnologiesJava
Source Code

The Online Bookstore project is a dynamic Java application that provides users with a convenient platform to browse, search, and purchase books online. This project offers programmers an opportunity to apply their Java skills while developing a comprehensive and user-friendly e-commerce platform specifically tailored for books.

In the Online Bookstore, users can explore a vast catalog of books across different genres, authors, and topics. They can easily search for specific titles, view book details, read reviews, and add books to their shopping cart for purchase. By implementing features such as user authentication, secure payment processing, and order management, programmers can create a seamless and enjoyable shopping experience for book enthusiasts.

27. Connect4

50 Java Projects - Connect4

The Connect4 Game project is a Java application that offers users a classic and engaging gaming experience. This project provides programmers with an opportunity to apply their Java skills while developing a strategic and entertaining game of Connect 4.

In the Connect4 Game, two players take turns dropping colored discs into a vertical grid with the goal of connecting four discs of their color horizontally, vertically, or diagonally. By implementing logic to handle player input, validate moves, and detect winning conditions, programmers can create an immersive and challenging gaming experience.

28. Event Management System

50 Java Projects - Event Management System

AuthorAnkur Gangwar
TechnologiesJava AWT, Swing, and MySQL
Source Code

The Event Management System is a comprehensive Java application designed to streamline the planning and organization of events for various purposes, such as conferences, weddings, or corporate gatherings. This project offers programmers an opportunity to apply their Java skills while developing a versatile and efficient system for managing event logistics.

In the Event Management System, administrators can perform various tasks such as creating event schedules, managing guest lists, coordinating vendors and suppliers, and tracking expenses and budgets. By implementing features such as user authentication, calendar integration, and communication tools, programmers can create a centralized platform for planning and executing events seamlessly.

29. Puzzle Game

50 Java Projects - Puzzle Game

The Puzzle Game project is an engaging Java application that challenges users with a variety of mind-bending puzzles to solve. This project provides programmers with an opportunity to apply their Java skills while creating an entertaining and intellectually stimulating gaming experience.

In the Puzzle Game, players are presented with a series of puzzles, each requiring a unique solution or strategy to complete. These puzzles may include logic puzzles, pattern recognition challenges, maze navigation tasks, or spatial reasoning exercises. By implementing logic to generate puzzles, validate player inputs, and track progress, programmers can create a dynamic and immersive gaming experience.

30. Pacman Game

50 Java Projects - Pacman Game

AuthorJan Bodnar
TechnologiesJava
Source Code

The Pacman Game project is a classic Java application that brings to life the iconic arcade game experience. This project offers programmers an opportunity to apply their Java skills while recreating the nostalgic and beloved gameplay of Pacman.

In the Pacman Game, players control the iconic character Pacman as they navigate through a maze, eating pellets and avoiding ghosts. The objective is to clear the maze of all pellets while avoiding contact with the ghosts, which will result in losing a life. By implementing logic to handle player input, control Pacman's movement, and manage ghost behavior, programmers can recreate the thrilling and addictive gameplay of Pacman.

31. Space Invaders Game

50 Java Projects - Space Invaders Game

The Space Invaders Game project is a thrilling Java application that immerses players in an epic battle against invading alien forces. This project provides programmers with an opportunity to apply their Java skills while recreating the classic arcade gaming experience of Space Invaders.

In the Space Invaders Game, players control a spaceship at the bottom of the screen, tasked with defending Earth from waves of descending alien invaders. The player can move the spaceship horizontally to dodge enemy fire and shoot projectiles to eliminate the invading aliens. By implementing logic to handle player input, manage alien movement patterns, and detect collisions, programmers can recreate the fast-paced and addictive gameplay of Space Invaders.

32. Breakout Game

50 Java Projects - Breakout Game

The Breakout Game project is an exhilarating Java application that challenges players to smash through rows of bricks using a bouncing ball and a paddle. This project offers programmers an opportunity to apply their Java skills while recreating the timeless and addictive gameplay of Breakout.

In the Breakout Game, players control a paddle at the bottom of the screen, tasked with bouncing a ball to break through a wall of bricks at the top. The player must maneuver the paddle to keep the ball in play and prevent it from falling off the bottom of the screen. By implementing logic to handle player input, simulate ball movement and collision detection, and manage brick destruction, programmers can recreate the fast-paced and exciting gameplay of Breakout.

33. Tetris Game

50 Java Projects - Tetris Game

The Tetris Game project is an exciting Java application that challenges players to manipulate falling tetrominoes to create complete lines and clear the playing field. This project provides programmers with an opportunity to apply their Java skills while recreating the iconic and addictive gameplay of Tetris.

In the Tetris Game, players control the descent of tetrominoes—geometric shapes composed of four square blocks— as they fall from the top of the screen to the bottom. The player can rotate and maneuver the tetrominoes to fit them into gaps and create solid lines across the playing field. By implementing logic to handle player input, simulate tetromino movement and rotation, and detect line completions, programmers can recreate the fast-paced and challenging gameplay of Tetris.

34. Minesweeper Game

50 Java Projects - Minesweeper Game

The Minesweeper Game project is a captivating Java application that challenges players to uncover hidden mines on a grid-based playing field while avoiding detonating any of them. This project provides programmers with an opportunity to apply their Java skills while recreating the engaging and strategic gameplay of Minesweeper.

In the Minesweeper Game, players are presented with a grid of squares, some of which conceal hidden mines. The objective is to uncover all the non-mine squares without triggering any mines. Players can reveal the contents of a square by clicking on it, and clues provided by adjacent squares indicate the number of mines in proximity. By implementing logic to handle player input, reveal squares, and detect game-ending conditions, programmers can recreate the challenging and thought-provoking gameplay of Minesweeper.

50 Java Projects - ChatFx

AuthorHouari Zegai
TechnologiesJavaFX and Socket
Source Code

ChatFx is a Java-based chat application that provides users with a platform to engage in real-time text-based conversations. This project offers programmers an opportunity to apply their Java skills while developing a dynamic and interactive chat system.

36. Chrome Dino Game

50 Java Projects - Chrome Dino Game

AuthorNabhoneel Majumdar
TechnologiesJava
Source Code

The Chrome Dino Game Clone project is a Java application inspired by the classic side-scrolling endless runner game found in Google Chrome's offline page. This project offers programmers an opportunity to apply their Java skills while recreating the simple yet addictive gameplay of the Chrome Dino Game.

In the Chrome Dino Game Clone, players control a dinosaur character that automatically runs forward on a desert landscape. The objective is to jump over obstacles such as cacti and birds while avoiding collisions. By implementing logic to handle player input for jumping, detect collisions with obstacles, and generate random obstacle patterns, programmers can recreate the fast-paced and challenging gameplay of the Chrome Dino Game.

37. Web Scraping

50 Java Projects - Web Scrapping

AuthorHouari Zegai
TechnologiesJava and JSoup
Source Code

Web scraping refers to the process of extracting data from websites. It's a valuable technique for gathering information from the web for various purposes, such as data analysis, market research, or content aggregation. In Java, developers can leverage libraries like Jsoup to perform web scraping efficiently and effectively.

Jsoup is a Java library that provides a convenient API for working with HTML documents. With Jsoup, developers can easily parse HTML, navigate the document structure, and extract relevant data using CSS selectors or DOM traversal methods.

38. Text Editor

50 Java Projects - Text Editor

AuthorPH7 de Soria
TechnologiesJava
Source Code

A Text Editor is a fundamental tool used for creating, editing, and managing text-based documents. Building a Text Editor application in Java provides an excellent opportunity for programmers to apply their skills while creating a versatile and user-friendly tool for text manipulation.

In Java, developers can leverage libraries like JavaFX to create graphical user interfaces (GUIs) for their applications. JavaFX offers a rich set of features for building interactive and visually appealing desktop applications, making it well-suited for developing a Text Editor.

39. Tender Management System

50 Java Projects - Tender Management System

AuthorShashi Raj
TechnologiesJava, JSP, and MySQL
Source Code

A Tender Management System is a comprehensive software solution designed to streamline the process of tendering, from initial announcement to final contract award. This system facilitates the entire tender lifecycle, including tender creation, submission, evaluation, and contract management. Building a Tender Management System in Java presents an opportunity for developers to create a powerful tool that enhances efficiency and transparency in the tendering process.

40. Hotel Reservation System

50 Java Projects - Hotel Reservation System

AuthorHouari Zegai
TechnologiesJavaEE, MySQL, and Bootstrap
Source Code

A Hotel Reservation System is a software application designed to streamline the process of booking accommodations and managing reservations for hotels, resorts, or other lodging establishments. Building a Hotel Reservation System in Java provides developers with an opportunity to create a comprehensive solution that enhances the efficiency and customer experience of hotel management.

41. Train Ticket Reservation System

50 Java Projects - Train Ticket Reservation System

AuthorShashi Raj
TechnologiesJava, Servlet, and Oracle
Source Code

A Train Ticket Reservation System is a software application designed to facilitate the booking of train tickets and management of reservations for railway passengers. Building a Train Ticket Reservation System in Java provides developers with an opportunity to create a comprehensive solution that enhances the efficiency and convenience of train travel.

42. School Management System

50 Java Projects - School Management System

AuthorHouari Zegai
TechnologiesJavaFX, JFoenix, Jasper Reports, and MySQL
Source Code

A School Management System is a comprehensive software solution designed to streamline various administrative tasks within educational institutions. This system helps manage student information, class schedules, attendance records, grading, and communication between teachers, students, and parents. Building a School Management System in Java provides an efficient way to organize and automate processes, ultimately enhancing the effectiveness of school administration.

43. Banking System

50 Java Projects - Banking System

AuthorHendi Santika
TechnologiesJava, Springboot, Angular, and MySQL
Source Code

A Banking System is a software application used by financial institutions to manage customer accounts, transactions, and other banking operations. This system facilitates activities such as account management, fund transfers, loan processing, and online banking services. Building a Banking System in Java involves implementing secure and efficient algorithms for managing financial transactions, ensuring data integrity and confidentiality, and providing a seamless user experience for customers.

44. Restaurant Management System

50 Java Projects - Restaurant Management System

AuthorShahin Alam
TechnologiesJava
Source Code

A Restaurant Management System is a software platform used by restaurants and food service establishments to manage various aspects of their operations, including order management, inventory control, table reservations, and billing. This system helps streamline restaurant workflows, improve efficiency, and enhance the dining experience for customers. Building a Restaurant Management System in Java involves designing user-friendly interfaces, integrating with point-of-sale devices, and implementing features such as menu customization, order tracking, and kitchen management.

45. Library Management System

50 Java Projects - Library Management System

AuthorMuhammed Afsal Villan
TechnologiesJavaFX
Source Code

A Library Management System is a software application used by libraries to manage their collections, circulation, and patron services. This system helps librarians track books, manage borrower information, automate check-in and check-out processes, and generate reports on library usage. Building a Library Management System in Java involves designing a database schema to store book and patron information, implementing search and retrieval functionalities, and providing a user-friendly interface for library staff and patrons to interact with the system.

46. Mail Sender

50 Java Projects - Mail Sender

A Mail Sender is a software application used to compose, send, and manage emails. This tool facilitates communication by allowing users to send messages to one or more recipients over email. Building a Mail Sender in Java involves integrating with email protocols such as SMTP (Simple Mail Transfer Protocol) or using third-party email APIs to handle email delivery and management.

47. 2048 Game

50 Java Projects - 2048

The 2048 Game is a popular single-player puzzle game where players slide numbered tiles on a grid to combine them and create a tile with the number 2048. Building a 2048 Game in Java involves implementing game mechanics such as tile movement, tile merging, scoring, and game over conditions. Developers can use graphical libraries like JavaFX or Swing to create a user interface for the game.

48. Table Generator

50 Java Projects - Table Generator

AuthorHouari Zegai
TechnologiesJavaFX and JFoenix
Source Code

A Table Generator is a tool used to create tables or grids with specified dimensions and content. This tool is often used in document preparation, web development, or data analysis to generate structured data displays. Building a Table Generator in Java involves designing a user interface for users to input table parameters such as rows, columns, and content, and then generating the table output dynamically.

49. Health Care Management System

50 Java Projects - Health Care Management System

AuthorHeshan Eranga
TechnologiesJava
Source Code

A Health Care Management System is a software application used by healthcare providers to manage patient records, appointments, medical history, and other administrative tasks. This system helps streamline healthcare workflows, improve patient care, and enhance operational efficiency. Building a Health Care Management System in Java involves integrating with healthcare standards such as HL7 (Health Level Seven) for data exchange and implementing features such as patient registration, appointment scheduling, and electronic health record (EHR) management.

50. Energy Saving System

50 Java Projects - Energy Saving System

AuthorNaeem Rashid
TechnologiesJavFX
Source Code

An Energy Saving System is a software application used to monitor, analyze, and optimize energy usage in buildings, facilities, or industrial processes. This system helps identify energy inefficiencies, track energy consumption patterns, and implement strategies to reduce energy consumption and costs. Building an Energy Saving System in Java involves integrating with sensors, meters, and building management systems to collect energy data, performing data analysis to identify energy-saving opportunities, and implementing control algorithms to optimize energy usage in real-time.

Engaging in Java projects with source code is an invaluable aspect of learning and mastering the language. Whether you're a novice aiming to solidify your foundation or an experienced developer seeking to enhance your skills, embarking on practical projects offers a rewarding learning experience. By exploring projects across different levels of complexity, developers can broaden their understanding, tackle challenges, and unleash their creativity in the world of Java programming.

Q1. Where can I find Java projects with source code for beginners?

Beginners can find Java projects on platforms like GitHub, CodeProject, and tutorial websites catering specifically to novice programmers.

Q2. How do Java projects help in learning programming?

Java projects provide hands-on experience, reinforce theoretical concepts, and promote problem-solving skills crucial for mastering programming.

Q3. Are Java projects suitable for advanced developers?

Yes, advanced developers can benefit from Java projects by tackling complex problems, exploring new technologies, and contributing to open-source projects.

Q4. Can I modify existing Java projects to suit my requirements?

Absolutely! Modifying existing Java projects allows developers to customize functionality, experiment with different approaches, and enhance their coding skills.

Q5. Are there online communities for discussing Java projects and seeking help?

Yes, numerous online forums and programming communities exist where developers can share ideas, seek assistance, and collaborate on Java projects.

math-formulas-and-notations-in-html-and-css.webp

That’s a wrap!

Thank you for taking the time to read this article! I hope you found it informative and enjoyable. If you did, please consider sharing it with your friends and followers. Your support helps me continue creating content like this.

Stay updated with our latest content by signing up for our email newsletter ! Be the first to know about new articles and exciting updates directly in your inbox. Don't miss out—subscribe today!

If you'd like to support my work directly, you can buy me a coffee . Your generosity is greatly appreciated and helps me keep bringing you high-quality articles.

Thanks! Faraz 😊

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox, latest post.

Create Sticky Notes with HTML, CSS, and JavaScript (Source Code)

Create Sticky Notes with HTML, CSS, and JavaScript (Source Code)

Learn how to create interactive sticky notes using HTML, CSS, and JavaScript with our comprehensive step-by-step tutorial. Perfect for web developers of all levels.

Create a Jewellery Website Landing Page using HTML, CSS, and JavaScript

Create a Jewellery Website Landing Page using HTML, CSS, and JavaScript

July 01, 2024

Create Hospital Website Template using HTML, CSS, and JavaScript

Create Hospital Website Template using HTML, CSS, and JavaScript

June 26, 2024

Create Dental Clinic Landing Page with HTML and Tailwind CSS

Create Dental Clinic Landing Page with HTML and Tailwind CSS

How to Create a Medical Email Newsletter with HTML and CSS

How to Create a Medical Email Newsletter with HTML and CSS

Create Fortnite Buttons Using HTML and CSS - Step-by-Step Guide

Create Fortnite Buttons Using HTML and CSS - Step-by-Step Guide

Learn how to create Fortnite-style buttons using HTML and CSS. This step-by-step guide includes source code and customization tips.

How to Create a Scroll Down Button: HTML, CSS, JavaScript Tutorial

How to Create a Scroll Down Button: HTML, CSS, JavaScript Tutorial

March 17, 2024

How to Create a Trending Animated Button Using HTML and CSS

How to Create a Trending Animated Button Using HTML and CSS

March 15, 2024

Create Interactive Booking Button with mask-image using HTML and CSS (Source Code)

Create Interactive Booking Button with mask-image using HTML and CSS (Source Code)

March 10, 2024

Create Shimmering Effect Button: HTML & CSS Tutorial (Source Code)

Create Shimmering Effect Button: HTML & CSS Tutorial (Source Code)

March 07, 2024

Create a Whack-a-Mole Game with HTML, CSS, and JavaScript | Step-by-Step Guide

Create a Whack-a-Mole Game with HTML, CSS, and JavaScript | Step-by-Step Guide

Learn how to create a Whack-a-Mole game using HTML, CSS, and JavaScript. Follow this step-by-step guide to build, style, and add logic to your game. Get the complete source code and tips for enhancements.

Create Your Own Bubble Shooter Game with HTML and JavaScript

Create Your Own Bubble Shooter Game with HTML and JavaScript

May 01, 2024

Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

April 01, 2024

Building a Fruit Slicer Game with HTML, CSS, and JavaScript (Source Code)

Building a Fruit Slicer Game with HTML, CSS, and JavaScript (Source Code)

December 25, 2023

Create Connect Four Game Using HTML, CSS, and JavaScript (Source Code)

Create Connect Four Game Using HTML, CSS, and JavaScript (Source Code)

December 07, 2023

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

Master the art of color picking with Vibrant.js. This tutorial guides you through building a custom color extractor tool using HTML, CSS, and JavaScript.

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

January 04, 2024

Crafting Custom Alarm and Clock Interfaces using HTML, CSS, and JavaScript

Crafting Custom Alarm and Clock Interfaces using HTML, CSS, and JavaScript

November 30, 2023

Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

October 30, 2023

URL Keeper with HTML, CSS, and JavaScript (Source Code)

URL Keeper with HTML, CSS, and JavaScript (Source Code)

October 26, 2023

Creating a Responsive Footer with Tailwind CSS (Source Code)

Creating a Responsive Footer with Tailwind CSS (Source Code)

Learn how to design a modern footer for your website using Tailwind CSS with our detailed tutorial. Perfect for beginners in web development.

Crafting a Responsive HTML and CSS Footer (Source Code)

Crafting a Responsive HTML and CSS Footer (Source Code)

November 11, 2023

Create an Animated Footer with HTML and CSS (Source Code)

Create an Animated Footer with HTML and CSS (Source Code)

October 17, 2023

Bootstrap Footer Template for Every Website Style

Bootstrap Footer Template for Every Website Style

March 08, 2023

How to Create a Responsive Footer for Your Website with Bootstrap 5

How to Create a Responsive Footer for Your Website with Bootstrap 5

August 19, 2022

Start training on this collection. Each time you skip or complete a kata you will be taken to the next kata in the series. Once you cycle through the items in the collection you will revert back to your normal training routine.

Description Edit

Get starting with your java coding practice with these java exercises. There is a wide range of java problems to solve.

Delete This Collection

Deleting the collection cannot be undone.

Collect: kata

Loading collection data...

You have not created any collections yet.

Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.

Get started now by creating a new collection .

Set the name for your new collection. Remember, this is going to be visible by everyone so think of something that others will understand.

  • ▼Java Exercises
  • Basic Part-I
  • Basic Part-II
  • Conditional Statement
  • Recursive Methods
  • Java Enum Types
  • Exception Handling
  • Java Inheritance
  • Java Abstract Classes
  • Java Thread
  • Java Multithreading
  • Java Lambda expression
  • Java Generic Method
  • Object-Oriented Programming
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • File Input-Output
  • Regular Expression
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java Array: Exercises, Practice, Solution

Java array exercises [79 exercises with solution].

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

1. Write a Java program to sort a numeric array and a string array.

Click me to see the solution

2. Write a Java program to sum values of an array.

3. Write a Java program to print the following grid.

Expected Output :

4. Write a Java program to calculate the average value of array elements.

5. Write a Java program to test if an array contains a specific value.

6. Write a Java program to find the index of an array element.

7. Write a Java program to remove a specific element from an array.

8. Write a Java program to copy an array by iterating the array.

9. Write a Java program to insert an element (specific position) into an array.

10. Write a Java program to find the maximum and minimum value of an array.

11. Write a Java program to reverse an array of integer values.

12. Write a Java program to find duplicate values in an array of integer values.

13. Write a Java program to find duplicate values in an array of string values.

14. Write a Java program to find common elements between two arrays (string values).

15. Write a Java program to find common elements between two integer arrays.

16. Write a Java program to remove duplicate elements from an array.

17. Write a Java program to find the second largest element in an array.

18. Write a Java program to find the second smallest element in an array.

19. Write a Java program to add two matrices of the same size.

20. Write a Java program to convert an array to an ArrayList.

21. Write a Java program to convert an ArrayList to an array.

22. Write a Java program to find all pairs of elements in an array whose sum is equal to a specified number.

23. Write a Java program to test two arrays' equality.

24. Write a Java program to find a missing number in an array.

25. Write a Java program to find common elements in three sorted (in non-decreasing order) arrays.

26. Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-zero) array elements.

27. Write a Java program to find the number of even and odd integers in a given array of integers.

28. Write a Java program to get the difference between the largest and smallest values in an array of integers. The array must have a length of at least 1.

29. Write a Java program to compute the average value of an array of integers except the largest and smallest values.

30. Write a Java program to check if an array of integers is without 0 and -1.

31. Write a Java program to check if the sum of all the 10's in the array is exactly 30. Return false if the condition does not satisfy, otherwise true.

32. Write a Java program to check if an array of integers contains two specified elements 65 and 77.

33. Write a Java program to remove duplicate elements from a given array and return the updated array length. Sample array: [20, 20, 30, 40, 50, 50, 50] After removing the duplicate elements the program should return 4 as the new length of the array. 

34. Write a Java program to find the length of the longest consecutive elements sequence from an unsorted array of integers. Sample array: [49, 1, 3, 200, 2, 4, 70, 5] The longest consecutive elements sequence is [1, 2, 3, 4, 5], therefore the program will return its length 5. 

35. Write a Java program to find the sum of the two elements of a given array equal to a given integer. Sample array: [1,2,4,5,6] Target value: 6. 

36. Write a Java program to find all the distinct triplets such that the sum of all the three elements [x, y, z (x ≤ y ≤ z)] equal to a specified number. Sample array: [1, -2, 0, 5, -1, -4] Target value: 2. 

37. Write a Java program to create an array of its anti-diagonals from a given square matrix. 

Example: Input : 1 2 3 4 Output: [ [1], [2, 3], [4] ]

38. Write a Java program to get the majority element from an array of integers containing duplicates.  

Majority element: A majority element is an element that appears more than n/2 times where n is the array size.

39. Write a Java program to print all the LEADERS in the array.   Note: An element is leader if it is greater than all the elements to its right side.

40. Write a Java program to find the two elements in a given array of positive and negative numbers such that their sum is close to zero.  

41. Write a Java program to find the smallest and second smallest elements of a given array.  

42. Write a Java program to separate 0s and 1s in an array of 0s and 1s into left and right sides.  

43. Write a Java program to find all combinations of four elements of an array whose sum is equal to a given value.  

44. Write a Java program to count the number of possible triangles from a given unsorted array of positive integers.   Note: The triangle inequality states that the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side.

45. Write a Java program to cyclically rotate a given array clockwise by one.  

46. Write a Java program to check whether there is a pair with a specified sum in a given sorted and rotated array.  

47. Write a Java program to find the rotation count in a given rotated sorted array of integers.  

48. Write a Java program to arrange the elements of an array of integers so that all negative integers appear before all positive integers.  

49. Write a Java program to arrange the elements of an array of integers so that all positive integers appear before all negative integers.  

50. Write a Java program to sort an array of positive integers from an array. In the sorted array the value of the first element should be maximum, the second value should be a minimum, third should be the second maximum, the fourth should be the second minimum and so on.  

51. Write a Java program that separates 0s on the left hand side and 1s on the right hand side from a random array of 0s and 1.  

52. Write a Java program to separate even and odd numbers from a given array of integers. Put all even numbers first, and then odd numbers.  

53. Write a Java program to replace every element with the next greatest element (from the right side) in a given array of integers. There is no element next to the last element, therefore replace it with -1. 

54. Write a Java program to check if a given array contains a subarray with 0 sum.  

Example: Input : nums1= { 1, 2, -2, 3, 4, 5, 6 } nums2 = { 1, 2, 3, 4, 5, 6 } nums3 = { 1, 2, -3, 4, 5, 6 } Output: Does the said array contain a subarray with 0 sum: true Does the said array contain a subarray with 0 sum: false Does the said array contain a subarray with 0 sum: true

55. Write a Java program to print all sub-arrays with 0 sum present in a given array of integers.  

Example: Input : nums1 = { 1, 3, -7, 3, 2, 3, 1, -3, -2, -2 } nums2 = { 1, 2, -3, 4, 5, 6 } nums3= { 1, 2, -2, 3, 4, 5, 6 } Output: Sub-arrays with 0 sum : [1, 3, -7, 3] Sub-arrays with 0 sum : [3, -7, 3, 2, 3, 1, -3, -2] Sub-arrays with 0 sum : [1, 2, -3] Sub-arrays with 0 sum : [2, -2]

56. Write a Java program to sort a binary array in linear time.   From Wikipedia, Linear time: An algorithm is said to take linear time, or O(n) time, if its time complexity is O(n). Informally, this means that the running time increases at most linearly with the size of the input. More precisely, this means that there is a constant c such that the running time is at most cn for every input of size n. For example, a procedure that adds up all elements of a list requires time proportional to the length of the list, if the adding time is constant, or, at least, bounded by a constant. Linear time is the best possible time complexity in situations where the algorithm has to sequentially read its entire input. Therefore, much research has been invested into discovering algorithms exhibiting linear time or, at least, nearly linear time. This research includes both software and hardware methods. There are several hardware technologies which exploit parallelism to provide this. An example is content-addressable memory. This concept of linear time is used in string matching algorithms such as the Boyer–Moore algorithm and Ukkonen's algorithm.

Example: Input : b_nums[] = { 0, 1, 1, 0, 1, 1, 0, 1, 0, 0 } Output: After sorting: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

57. Write a Java program to check if a sub-array is formed by consecutive integers from a given array of integers.  

Example: Input : nums = { 2, 5, 0, 2, 1, 4, 3, 6, 1, 0 } Output: The largest sub-array is [1, 7] Elements of the sub-array: 5 0 2 1 4 3 6

58. Given two sorted arrays A and B of size p and q, write a Java program to merge elements of A with B by maintaining the sorted order i.e. fill A with first p smallest elements and fill B with remaining elements.  

Example: Input : int[] A = { 1, 5, 6, 7, 8, 10 } int[] B = { 2, 4, 9 } Output: Sorted Arrays: A: [1, 2, 4, 5, 6, 7] B: [8, 9, 10]

59. Write a Java program to find the maximum product of two integers in a given array of integers.  

Example: Input : nums = { 2, 3, 5, 7, -7, 5, 8, -5 } Output: Pair is (7, 8), Maximum Product: 56

60. Write a Java program to shuffle a given array of integers.  

Example: Input : nums = { 1, 2, 3, 4, 5, 6 } Output: Shuffle Array: [4, 2, 6, 5, 1, 3]

61. Write a Java program to rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements.  

Example: Input : nums= { 1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14 } Output: Array with every second element is greater than its left and right elements: [1, 4, 2, 9, 3, 8, 5, 10, 7, 14, 12]

62. Write a Java program to find equilibrium indices in a given array of integers.  

Example: Input : nums = {-7, 1, 5, 2, -4, 3, 0} Output: Equilibrium indices found at : 3 Equilibrium indices found at : 6

63. Write a Java program to replace each element of the array with the product of every other element in a given array of integers.  

Example: Input : nums1 = { 1, 2, 3, 4, 5, 6, 7} nums2 = {0, 1, 2, 3, 4, 5, 6, 7} Output: Array with product of every other element: [5040, 2520, 1680, 1260, 1008, 840, 720] Array with product of every other element: [5040, 0, 0, 0, 0, 0, 0, 0]

64. Write a Java program to find the Longest Bitonic Subarray in a given array.  

A bitonic subarray is a subarray of a given array where elements are first sorted in increasing order, then in decreasing order. A strictly increasing or strictly decreasing subarray is also accepted as bitonic subarray.

Example: Input : nums = { 4, 5, 9, 5, 6, 10, 11, 9, 6, 4, 5 } Output: The longest bitonic subarray is [3,9] Elements of the said sub-array: 5 6 10 11 9 6 4 The length of longest bitonic subarray is 7

65. Write a Java program to find the maximum difference between two elements in a given array of integers such that the smaller element appears before the larger element.  

Example: Input : nums = { 2, 3, 1, 7, 9, 5, 11, 3, 5 } Output: The maximum difference between two elements of the said array elements 10

66. Write a Java program to find a contiguous subarray within a given array of integers with the largest sum.  

In computer science, the maximum sum subarray problem is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers. Formally, the task is to find indices and with, such that the sum is as large as possible.

Example: Input : int[] A = {1, 2, -3, -4, 0, 6, 7, 8, 9} Output: The largest sum of contiguous sub-array: 30

67. Write a Java program to find the subarray with the largest sum in a given circular array of integers.  

Example: Input : nums1 = { 2, 1, -5, 4, -3, 1, -3, 4, -1 } nums2 = { 1, -2, 3, 0, 7, 8, 1, 2, -3 } Output: The sum of subarray with the largest sum is 6 The sum of subarray with the largest sum is 21

68. Write a Java program to create all possible permutations of a given array of distinct integers.  

Example: Input : nums1 = {1, 2, 3, 4} nums2 = {1, 2, 3} Output: Possible permutations of the said array: [1, 2, 3, 4] [1, 2, 4, 3] .... [4, 1, 3, 2] [4, 1, 2, 3] Possible permutations of the said array: [1, 2, 3] [1, 3, 2] ... [3, 2, 1] [3, 1, 2]

69. Write a Java program to find the minimum subarray sum of specified size in a given array of integers.  

Example: Input : nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10} Output: Sub-array size: 4 Sub-array from 0 to 3 and sum is: 10

70. Write a Java program to find the smallest length of a contiguous subarray of which the sum is greater than or equal to a specified value. Return 0 instead.  

Example: Input : nums = {1, 2, 3, 4, 6} Output: Minimum length of a contiguous subarray of which the sum is 8, 2

71. Write a Java program to find the largest number from a given list of non-negative integers.  

Example: Input : nums = {1, 2, 3, 0, 4, 6} Output: Largest number using the said array numbers: 643210

72. Write a Java program to find and print one continuous subarray (from a given array of integers) that if you only sort the said subarray in ascending order then the entire array will be sorted in ascending order.  

Example: Input : nums1 = {1, 2, 3, 0, 4, 6} nums2 = { 1, 3, 2, 7, 5, 6, 4, 8} Output: Continuous subarray: 1 2 3 0 Continuous subarray: 3 2 7 5 6 4

73. Write a Java program to sort a given array of distinct integers where all its numbers are sorted except two numbers.  

Example: Input : nums1 = { 3, 5, 6, 9, 8, 7 } nums2 = { 5, 0, 1, 2, 3, 4, -2 } Output: After sorting new array becomes: [3, 5, 6, 7, 8, 9] After sorting new array becomes: [-2, 0, 1, 2, 3, 4, 5]

74. Write a Java program to find all triplets equal to a given sum in an unsorted array of integers.  

Example: Input : nums = { 1, 6, 3, 0, 8, 4, 1, 7 } Output: Triplets of sum 7 (0 1 6) (0 3 4)

75. Write a Java program to calculate the largest gap between sorted elements of an array of integers.  

Example: Original array: [23, -2, 45, 38, 12, 4, 6] Largest gap between sorted elements of the said array: 15

76. Write a Java program to determine whether numbers in an array can be rearranged so that each number appears exactly once in a consecutive list of numbers. Return true otherwise false.  

Example: Original array: [1, 2, 5, 0, 4, 3, 6] Check consecutive numbers in the said array!true

77. Write a Java program that checks whether an array of integers alternates between positive and negative values.  

Example: Original array: [1, -2, 5, -4, 3, -6] Check the said array of integers alternates between positive and negative values!true

78. Write a Java program that checks whether an array is negative dominant or not. If the array is negative dominant return true otherwise false.  

Example: Original array of numbers: [1, -2, -5, -4, 3, -6] Check Negative Dominance in the said array!true

79. Write a Java program that returns the missing letter from an array of increasing letters (upper or lower). Assume there will always be one omission from the array.  

Example: Original array of elements: [p, r, s, t] Missing letter in the said array: q

Java Code Editor:

More to Come !

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

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Javatpoint Logo

  • Design Pattern

JavaTpoint

Core Java Quiz | Java Online Test

There are a list of core java quizzes such as basics quiz, oops quiz, string handling quiz, array quiz, exception handling quiz, collection framework quiz etc.

After clearing the exam, play our Belt Series Quiz and earn points. These points will be displayed on your profile page.

Java Basics Quiz

Java array quiz, java oops quiz, string handling quiz, exception hand. quiz, multithreading quiz, collection quiz, java misc. quiz.

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

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

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

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

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

RSS Feed

Uploaded avatar of jmrunkle

Practice 147 exercises in Java

Learn and practice Java by completing 147 exercises that explore different concepts and ideas.

Explore the Java exercises on Exercism

Unlock more exercises as you progress. They’re great practice and fun to do!

  • C Program : Remove All Characters in String Except Alphabets
  • C Program : Sorting a String in Alphabetical Order – 2 Ways
  • C Program : Remove Vowels from A String | 2 Ways
  • C Program To Check Whether A Number Is Even Or Odd | C Programs
  • C Program To Count The Total Number Of Notes In A Amount | C Programs
  • C Program To Print Number Of Days In A Month | Java Tutoring
  • C Program To Check If Vowel Or Consonant | 4 Simple Ways
  • C Program To Find Reverse Of An Array – C Programs
  • C Program To Input Any Alphabet And Check Whether It Is Vowel Or Consonant
  • C Program To Find Maximum Between Three Numbers | C Programs
  • C Program To Check A Number Is Negative, Positive Or Zero | C Programs
  • C Program To Check If Alphabet, Digit or Special Character | C Programs
  • C Program To Check Character Is Uppercase or Lowercase | C Programs
  • C Program Inverted Pyramid Star Pattern | 4 Ways – C Programs
  • C Program To Check Whether A Character Is Alphabet or Not
  • C Program To Check Whether A Year Is Leap Year Or Not | C Programs
  • C Program Area Of Triangle | C Programs
  • C Program To Calculate Profit or Loss In 2 Ways | C Programs
  • C Program To Check If Triangle Is Valid Or Not | C Programs
  • C Program Find Circumference Of A Circle | 3 Ways
  • C Program To Check Number Is Divisible By 5 and 11 or Not | C Programs
  • C Program Hollow Diamond Star Pattern | C Programs
  • C Program Area Of Rectangle | C Programs
  • X Star Pattern C Program 3 Simple Ways | C Star Patterns
  • C Program Area Of Rhombus – 4 Ways | C Programs
  • C Program To Find Area Of Semi Circle | C Programs
  • C Program Area Of Isosceles Triangle | C Programs
  • C Program Area Of Parallelogram | C Programs
  • Mirrored Rhombus Star Pattern Program In c | Patterns
  • C Program Check A Character Is Upper Case Or Lower Case
  • C Program Area Of Trapezium – 3 Ways | C Programs
  • C Program Area Of Square | C Programs
  • C Program To Find Volume of Sphere | C Programs
  • C Program to find the Area Of a Circle
  • C Program Area Of Equilateral Triangle | C Programs
  • Hollow Rhombus Star Pattern Program In C | Patterns
  • C Program To Calculate Volume Of Cube | C Programs
  • C Program To Count Total Number Of Notes in Given Amount
  • C Program To Find Volume Of Cone | C Programs
  • C Program To Calculate Perimeter Of Rhombus | C Programs
  • C Program To Calculate Perimeter Of Rectangle | C Programs
  • C Program To Calculate Perimeter Of Square | C Programs
  • C Program Volume Of Cuboid | C Programs
  • C Program Count Number Of Words In A String | 4 Ways
  • C Program To Left Rotate An Array | C Programs
  • C Program To Search All Occurrences Of A Character In String | C Programs
  • C Program Volume Of Cylinder | C Programs
  • C Program To Remove First Occurrence Of A Character From String
  • C Program To Delete Duplicate Elements From An Array | 4 Ways
  • C Program To Count Occurrences Of A Word In A Given String | C Programs
  • C Square Star Pattern Program – C Pattern Programs | C Programs
  • C Program To Copy All Elements From An Array | C Programs
  • C Program To Compare Two Strings – 3 Easy Ways | C Programs
  • C Program To Toggle Case Of Character Of A String | C Programs
  • C Program To Delete An Element From An Array At Specified Position | C Programs
  • C Mirrored Right Triangle Star Pattern Program – Pattern Programs
  • C Program To Reverse Words In A String | C Programs
  • C Programs – 500+ Simple & Basic Programming Examples & Outputs
  • C Program To Search All Occurrences Of A Word In String | C Programs
  • C Program Inverted Right Triangle Star Pattern – Pattern Programs
  • C Plus Star Pattern Program – Pattern Programs | C
  • C Program To Find Reverse Of A string | 4 Ways
  • C Program To Trim Leading & Trailing White Space Characters From String
  • C Program To Remove Blank Spaces From String | C Programs
  • C Program To Remove Repeated Characters From String | 4 Ways
  • C Program To Remove Last Occurrence Of A Character From String
  • Hollow Square Pattern Program in C | C Programs
  • C Program To Find Maximum & Minimum Element In Array | C Prorams
  • C Program Replace All Occurrences Of A Character With Another In String
  • C Pyramid Star Pattern Program – Pattern Programs | C
  • C Program To Find Last Occurrence Of A Word In A String | C Programs
  • C Program To Count Frequency Of Each Character In String | C Programs
  • C Program To Find Last Occurrence Of A Character In A Given String
  • Rhombus Star Pattern Program In C | 4 Multiple Ways
  • C Program To Check A String Is Palindrome Or Not | C Programs
  • C Program Number Of Alphabets, Digits & Special Character In String | Programs
  • Merge Two Arrays To Third Array C Program | 4 Ways
  • C Program Right Triangle Star Pattern | Pattern Programs
  • C Program To Sort Even And Odd Elements Of Array | C Programs
  • C Program Replace First Occurrence Of A Character With Another String
  • C Program To Trim White Space Characters From String | C Programs
  • C Program To Search An Element In An Array | C Programs
  • C Program To Copy One String To Another String | 4 Simple Ways
  • C Program To Count Number Of Even & Odd Elements In Array | C Programs
  • C Program To Find First Occurrence Of A Word In String | C Programs
  • C Program To Count Occurrences Of A Character In String | C Programs
  • C Program To Concatenate Two Strings | 4 Simple Ways
  • C Program To Sort Array Elements In Ascending Order | 4 Ways
  • Highest Frequency Character In A String C Program | 4 Ways
  • C Program Count Number Of Vowels & Consonants In A String | 4 Ways
  • C Program To Print Number Of Days In A Month | 5 Ways
  • C Program Find Maximum Between Two Numbers | C Programs
  • C Program To Count Frequency Of Each Element In Array | C Programs
  • C Program To Trim Trailing White Space Characters From String | C Programs
  • C Program To Remove First Occurrence Of A Word From String | 4 Ways
  • C Program To Convert Lowercase String To Uppercase | 4 Ways
  • C Program To Convert Uppercase String To Lowercase | 4 Ways
  • C Program To Put Even And Odd Elements Of Array Into Two Separate Arrays
  • Diamond Star Pattern C Program – 4 Ways | C Patterns
  • C Program To Print All Unique Elements In The Array | C Programs
  • C Program Count Number of Duplicate Elements in An Array | C Programs
  • C Program To Find Sum Of All Array Elements | 4 Simple Ways
  • C Program Hollow Inverted Right Triangle Star Pattern
  • C Program Hollow Inverted Mirrored Right Triangle
  • C Program To Sort Array Elements In Descending Order | 3 Ways
  • C Program To Insert Element In An Array At Specified Position
  • C Program To Input Week Number And Print Week Day | 2 Ways
  • C Program To Remove All Occurrences Of A Character From String | C Programs
  • C Program To Count Number Of Negative Elements In Array
  • C Program To Find Lowest Frequency Character In A String | C Programs
  • C Program Hollow Mirrored Rhombus Star Pattern | C Programs
  • 8 Star Pattern – C Program | 4 Multiple Ways
  • C Program To Right Rotate An Array | 4 Ways
  • C Program To Replace Last Occurrence Of A Character In String | C Programs
  • C Program To Read & Print Elements Of Array | C Programs
  • C Program Half Diamond Star Pattern | C Pattern Programs
  • C Program Hollow Mirrored Right Triangle Star Pattern
  • C Program To Find First Occurrence Of A Character In A String
  • C Program To Find Length Of A String | 4 Simple Ways
  • Hollow Inverted Pyramid Star Pattern Program in C
  • C Program To Print All Negative Elements In An Array
  • Right Arrow Star Pattern Program In C | 4 Ways
  • C Program : Check if Two Arrays Are the Same or Not | C Programs
  • C Program : Check if Two Strings Are Anagram or Not
  • C Program Hollow Right Triangle Star Pattern
  • Left Arrow Star Pattern Program in C | C Programs
  • C Program : Capitalize First & Last Letter of A String | C Programs
  • C Program Inverted Mirrored Right Triangle Star Pattern
  • Hollow Pyramid Star Pattern Program in C
  • C Program Mirrored Half Diamond Star Pattern | C Patterns
  • C Program : Non – Repeating Characters in A String | C Programs
  • C Program : Sum of Positive Square Elements in An Array | C Programs
  • C Program : Find Longest Palindrome in An Array | C Programs
  • C Program : To Reverse the Elements of An Array | C Programs
  • C Program Lower Triangular Matrix or Not | C Programs
  • C Program Merge Two Sorted Arrays – 3 Ways | C Programs
  • C Program : Maximum Scalar Product of Two Vectors
  • C Program : Convert An Array Into a Zig-Zag Fashion
  • C Program : Check If Arrays are Disjoint or Not | C Programs
  • C Program : Find Missing Elements of a Range – 2 Ways | C Programs
  • C Program : Minimum Scalar Product of Two Vectors | C Programs
  • C program : Find Median of Two Sorted Arrays | C Programs
  • C Program Transpose of a Matrix 2 Ways | C Programs
  • C Program : To Find Maximum Element in A Row | C Programs
  • C Program Patterns of 0(1+)0 in The Given String | C Programs
  • C Program : Rotate the Matrix by K Times | C Porgrams
  • C Program : Check if An Array Is a Subset of Another Array
  • C Program To Check Upper Triangular Matrix or Not | C Programs
  • C Program : To Find the Maximum Element in a Column
  • C Program : Rotate a Given Matrix by 90 Degrees Anticlockwise
  • C Program : Non-Repeating Elements of An Array | C Programs
  • C Program Sum of Each Row and Column of A Matrix | C Programs

Learn Java Java Tutoring is a resource blog on java focused mostly on beginners to learn Java in the simplest way without much effort you can access unlimited programs, interview questions, examples

Java programs – 500+ simple & basic programs with outputs.

in Java Programs , Java Tutorials June 4, 2024 Comments Off on Java Programs – 500+ Simple & Basic Programs With Outputs

Java programs: Basic Java programs with examples & outputs. Here we covered over the list of 500+ Java simple programs for beginners to advance, practice & understood how java programming works. You can take a pdf of each program along with source codes & outputs.

In case if you are looking out for C Programs , you can check out that link.

We covered major Simple to basic Java Programs along with sample solutions for each method. If you need any custom program you can contact us.

All of our Sample Java programs with outputs in pdf format are written by expert authors who had high command on Java programming. Even our Java Tutorials are with rich in-depth content so that newcomers can easily understand.

1. EXECUTION OF A JAVA PROGRAM   

Static loading :  A block of code would be loaded into the RAM before it executed ( i.e after being loaded into the RAM it may or may not get executed )

Dynamic loading:   A block of code would be loaded into the RAM only when it is required to be executed.

Note:   Static loading took place in the execution of structured programming languages. EX:  c- language

Java  follows the Dynamic loading

–     JVM would not convert all the statements of the class file into its executable code at a time.

–     Once the control comes out from the method, then it is deleted from the RAM and another method of exe type will be loaded as required.

–     Once the control comes out from the main ( ), the main ( ) method would also be deleted from the RAM. This is why we are not able to view the exe contents of a class file.

Simple Hello Word Program

Out of 500+ Simple & Basic Java Programs: Hello world is a first-ever program which we published on our site. Of course, Every Java programmer or C programmer will start with a “Hello World Program”. Followed by the rest of the programs in different Categories.

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

Basic Java Programs – Complete List Here

Advanced simple programming examples with sample outputs, string, array programs.

Sort Programs

Conversion Programs:

Star & Number Pattern Programs

Functions of JVM:

  • It converts the required part if the bytecode into its equivalent executable code.
  • It loads the executable code into the RAM.
  • Executes this code through the local operating system.
  • Deletes the executable code from the RAM.

We know that JVM converts the class file into its equivalent executable code. Now if a JVM is in windows environment executable code that is understood by windows environment only.

Similarly, same in the case with UNIX or other or thus JVM ID platform dependent.

Java, With the help of this course, students can now get a confidant to write a basic program to in-depth algorithms in C Programming or Java Programming to understand the basics one must visit the list 500 Java programs to get an idea.

Users can now download the top 100 Basic Java programming examples in a pdf format to practice.

But the platform dependency of the JVM is not considered while saying Java is platform independent because JVM is supplied free of cost through the internet by the sun microsystems.

Platform independence :

Compiled code of a program should be executed in any operating system, irrespective of the as in OS in which that code had been generated. This concept is known as platform independence.

  • The birth of oops concept took place with encapsulation.
  • Any program contains two parts.
  • Date part and Logic part
  • Out of data and logic the highest priority we have given to data.
  • But in a structured programming language, the data insecurity is high.
  • Thus in a process, if securing data in structured prog. lang. the concept of encapsulation came into existence.
Note: In structured programming lang programs, the global variable play a vital role.

But because of these global variables, there is data insecurity in the structured programming lang programs. i.e functions that are not related to some variables will have access to those variables and thus data may get corrupted. In this way data is unsecured.

“This is what people say in general about data insecurity. But this is not the actual reason. The actual concept is as follows”.

Let us assume that, we have a ‘C’ program with a hundred functions. Assume that it is a project. Now if any upgradation is required, then the client i.e the user of this program (s/w) comes to its company and asks the programmers to update it according to his requirement.

Now we should note that it is not guaranteed that the programmers who developed this program will still be working with that company. Hence this project falls into the hands of new programmers.

Automatically it takes a lot of time to study. The project itself before upgrading it. It may not be surprising that the time required for writing the code to upgrade the project may be very less when compared to the time required for studying the project.

Thus maintenance becomes a problem.

If the new programmer adds a new function to the existing code in the way of upgrading it, there is no guarantee that it will not affect the existing functions in the code. This is because of global variables. In this way, data insecurity is created.

  • To overcome this problem, programmers developed the concept of encapsulation .
  • For example, let us have a struc.prog.lang. program with ten global variables and twenty functions.
  • It is sure that all the twenty functions will not use all the global variables .

Three of the global variables may be used only by two functions. But in a structured prog. Lang like ‘C’ it is not possible to restrict the access of global variables by some limited no of functions.

Every function will have access to all the global variables.

To avoid this problem, programmers have designed a way such that the variables and the functions which are associated with or operate on those variables are enclosed in a block and that bock is called a class and that class and that class is given a name, Just as a function is given a name.

Now the variables inside the block cannot be called as the local variable because they cannot be called as global variables because they are confined to a block and not global.

Hence these variables are known as instance variables

. Prog. Lang. program include < stdio.h> i,j,k,l,m,n; 1 ( ) --- 2 ---- 10 ( ) ---- ( ) ----

_______________________________________________________________

Example 2 :

. Lang program Abc   i,j,k 1 ( ) --- Xyz   l,m,n; 3 ( ) --- 4 ( ) ---

Therefore a class is nothing but grouping data along with its functionalities.

Note 1:  E ncapsulation it’s the concept of binding data along with its corresponding functionalities.

Encapsulations came into existence in order to provide security for the data present inside the program.

Note 2: Any object oriental programming language file looks like a group of classes. Everything is encapsulated. Nothing is outside the class.

  • Encapsulation is the backbone of oop languages.
  • JAVA supports all the oop concepts ( i.e. encapsulation, polymorphism, inheritance) and hence it is known as an object-oriented programming language.
  • C++ breaks the concept of encapsulation because the main ( ) method in a  C++ program is declared outside a class. Hence it is not a pure oop language, in fact, it is a poor oop language.

Related Posts !

core java assignments for practice

LCM Of Two Numbers Java Program | 5 Ways – Programs

July 3, 2024

core java assignments for practice

Java Program Convert Fahrenheit To Celsius | Vice Versa

June 30, 2024

Java Program Count Vowels In A String | Programs

June 27, 2024

X Star Pattern Java Program – Patterns

June 24, 2024

Square Star Pattern Program In Java – Patterns

June 22, 2024

Java Right Arrow Star Pattern Program | Patterns

June 19, 2024

core java assignments for practice

Rhombus Star Pattern Program In Java – Patterns

Java program to print Rhombus star pattern program. We have written the below print/draw Rhombus ...

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

Sharp Tutorial

Java Script

  • Python Programs
  • Java Script Program
  • Java Program
  • Ask Your Question
  • Java Script FAQ
  • CBSE Comp Science Question Paper
  • MDU python question Papers
  • Java Assignment
  • C Assignment
  • Python assignment
  • Java Script Assignment
  • Python Interview Question
  • Video Tutorials
  • 11th,12th Class Python Syllabus CBSE Board
  • ICSE Board 11-12 Computer Syllabus
  • Top 10 Programming Language 2020

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

java-practice

Here are 30 public repositories matching this topic..., andrei-punko / java-interview-coding.

Coding playground for preparation to Java interview

  • Updated Jul 3, 2024

KellzCodes / Java-Practice

#100DaysOfCode Java Practice

  • Updated Dec 10, 2021

Arijit-SE / TCS-Digital-JAVACoding

Here I have solved different type of Coding questions of Java programming of TCS Digital exam

  • Updated May 29, 2023

mariazevedo88 / hackerrank-challenges

A project of solved Java/SQL challenges from HackerRank website

  • Updated Feb 21, 2023

jaigora24 / Java

Questions for practice in Java programming language

  • Updated Jul 11, 2022

anwesh08 / HacktoberFest-2022

Make your first Pull Request on Hacktoberfest 2022. Don't forget to spread love and if you like give us a ⭐️. If you want to contribute to a JS repo for hacktoberfest u can do it here https://github.com/abhipshapatro/JavaScript30

  • Updated Oct 31, 2022

minhaj-313 / Java-Programs---For-Practice

Java-Programs---For-Practice is one of the Java Programming Practice Series By Shaikh Minhaj ( minhaj-313 ). This Series will help you to level up your Programming Skills. This Java Programs are very much helpful for Beginners. If You Have any doubt or query you can ask me here or you can also ask me on My LinkedIn Profile : https://www.linkedin…

  • Updated Sep 23, 2022

uiuxarghya / java-programs

🎁 A collection of Java programs ranging from basic ones to complex programs too.

  • Updated Nov 27, 2023

singhofen / java-projects

These are small Java programs meant for learning the fundamentals of the Java programming language.

  • Updated Aug 17, 2023

Damon0820 / tankWarUseJava

Tank war game use Java in order to practice and learn java language。java基础的一个练习项目-坦克大战

  • Updated Apr 3, 2019

tejaspundpal / Java-programs

This Repo includes some core java programs.

  • Updated Jan 6, 2023

VAIBHAVBAJPAI1402 / Java-Programs

This repository contains various Java Programming problems

  • Updated May 25, 2019

uxlabspk / JavaCodes

java practice codes

  • Updated Jun 23, 2023

A-safarji / java-mini-project

For Java practices and mini-projects

  • Updated Jul 29, 2021

alban-okoby / ds-java_low_level

Learn Java because he is - Simple, Platform Independent, Secure, Multithreaded, Architecture-neutral, Portable ..

  • Updated May 4, 2024

sonmez-hakan / hackerrank-java

Hackerrank Practice Java Solutions

  • Updated Jul 21, 2023

yankeexe / JavaPracticeNotes

☕ Curated Notes of Java.

  • Updated Jul 24, 2018

kavgan / JavaPractice

Practice practice practice. Bubble sort, factorial, powerset, subarray, mergesort, remove duplicates, etc.

  • Updated Feb 1, 2016

gautamthapa / java-practice

Java practice programs.

  • Updated Jan 26, 2023

trolit / grocery-store-themed-API

Java 14, Spring Boot 2 API with JPA(Hibernate), ModalMapper, H2. Can be used to practise front-end development in favourite framework.

  • Updated Nov 27, 2020

Improve this page

Add a description, image, and links to the java-practice topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the java-practice topic, visit your repo's landing page and select "manage topics."

Guru99

Java Tutorial for Beginners: Learn Core Java Programming

James Hartman

Java Tutorial Summary

This Java tutorial for beginners is taught in a practical GOAL-oriented way. It is recommended you practice the code assignments given after each core Java tutorial to learn Java from scratch. This Java programming for beginners course will help you learn basics of Java and advanced concepts.

What is Java?

Java is a class-based object-oriented programming language for building web and desktop applications. It is the most popular programming language and the language of choice for Android programming.

Java Syllabus

First Steps in Java Basics

👉 — An introduction, Definition & Features of Java Platforms
👉 — What is Java Virtual Machine & its Architecture
👉 — How to Download & Install Java JDK 8 in Windows
👉 — How to Download & Install Eclipse to Run Java
👉 — How to Download & Install Java in Linux(Ubuntu)
👉 — How to print in Java with Examples: 3 Methods
👉 — Hello World: How to Create Your First Java Program

Basics Concepts of Object-Oriented Programming (OOPs)

👉 — Learn OOPs Basics with Examples
👉 — What is Java Abstract Class & Method
👉 — Learn with an Example

Java Basics Language Constructs

👉 — What is & Data Types with Example
👉 — Learn with Example
👉 — Declare, Create, Initialize with Example
👉 — How to Create Array of Objects in Java
👉 — How to Use, Methods & Examples

Learn Java String Tutorial

👉 — Java String Manipulation: Functions and Methods
👉 — Learn with Example
👉 — Learn with Example
👉 — Learn with Example
👉 — How to Use with Examples
👉 — Check Substring with Example
👉 — Learn with Example
👉 — Learn with Example
👉 — Learn with Example
👉 — How to convert & Example
👉 — How to compare two Strings in Java (11 Methods)
👉 — What is Hashmap? Features & Example

Most Misunderstood Topics!

👉 — Learn with Example
👉 — What is & How to use with Example

Java Memory Management

👉 — What is, How it Works, Example
👉 — Java Static Method, Variable & Block
👉 — Java Stack and Heap Memory Allocation

Abstract Class & Interface in Java

👉 — Inheritance in Java OOPs with Example
👉 — Polymorphism in Java OOPs with Example
👉 — What is, Abstract Class & Method
👉 — What is Interface in Java with Example
👉 — Know the Difference

Better Late than Never

👉 — What is Constructor in Java? Program Examples
👉 — What is, How to Create/Import Package in Java

Exception Handling in Java

👉 — What is Exception in Java? Examples
👉 — How to Create User Defined Exception in Java
👉 — Throws Keyword in Java with Example

Conditional Loops in Java

👉 — Enhanced for Loop to Iterate Java Array
👉 — Learn Java Switch-Case Statement with Example

Java Advance Stuff!

👉 — Java Math Abs() Round() Ceil() Floor() Min() Methods
👉 — How to Generate Random Number in Java
👉 — SimpleDateFormat, Current Date & Compare
👉 — Learn with Examples
👉 — Method, block, static type
👉 — How to Create a GUI in Java with Examples
👉 — How to Split String with Example
👉 — How to Read File in Java with Example
👉 — Java Reflection API Tutorial with Example
👉 — Learn Groovy Script Step by Step for Beginners
👉 — What is Spring Framework & How to Install
👉 — What is Apache Ant Build Tool?
👉 — What is, How to Install, Report Example
👉 — Kotlin Programming [Code example]
👉 — Scala Programming Language Example & Code

Java Programs

👉 — Check whether number is prime or not
👉 — Convert using Gson and JAXB: JAVA Example
👉 — How to display prime numbers using Java
👉 — How to Convert Char to String in Java (Examples)
👉 — Fibonacci Series Program in Java using Loops & Recursion
👉 — Java Program to Check Armstrong Number
👉 — How to Reverse a String in Java using Recursion
👉 — Check number is Palindrome or Not
👉 — How to Print Star, Pyramid, Number
👉 — Sorting Algorithm Example
👉 — Insertion Sort Algorithm in Java Program with Example
👉 — Java Program for Selection Sorting with Example

Java Differences

👉 — What’s the Difference?
👉 — Key Differences
👉 — 10 Key Differences between Java and C#
👉 — What’s the Difference?
👉 — What is the Difference?
👉 — Key Differences
👉 — What’s the Difference?

Java Interview Questions, Tools & Books

👉 — Top 100 Java Interview Questions & Answers
👉 — 35+ Java 8 Interview Questions and Answers
👉 — Top 80 Most Frequently Asked
👉 — Top 22 Most Frequently Asked
👉 — Top 25 Most Frequently Asked
👉 — Top 22 Most Frequently Asked
👉 — Top 25 Most Frequently Asked
👉 — List of Top 20 Java Tools for Developers
👉 — List of Top 15 BEST Java IDE
👉 — 15 Best Java Programming Books for Beginner
👉 — Download Java Programming Tutorial for Beginners PDF

What will you learn in this Java Tutorial for Beginners?

In this Java tutorial for beginners, you will learn Java programming basics like What is Java platform, JVM, how to install Java, OOPS concepts, variables, class, object, arrays, strings, command-line arguments, garbage collection, inheritance, polymorphism, interface, constructor, packages, etc. You will also learn advanced concepts like switch-case, functions, multithreading, swing, files, API, Java Spring, etc., in this Java basics for beginners guide.

Prerequisites for learning Java Tutorial?

This free Java for beginners tutorial is designed for beginners with little or no Java coding experience. These Java notes for beginners will help beginners to learn Java online for free.

Why Learn Java Programming?

Here are the reasons why you should learn Java:

  • Java is very easy to learn.
  • Java developers are in demand, and it easy to get a job as a Java programmer.
  • It has a good collection of open-source libraries.
  • Java is free.

What are the Benefits of Java?

Here are the benefits of Java:

  • Java is object-oriented.
  • It is platform-independent.
  • You can effortlessly write, compile, and debug programs compare to other programming languages.

Applications of Java Programming

Following are the major applications of Java Programming language:

  • Mobile Applications
  • Web Applications
  • Web and Application servers
  • Enterprise Applications
  • Embedded Applications
  • Desktop GUI Applications

What are the types of Java programs?

Here are the types of Java Program:

  • Stand-alone applications.
  • Web Applications using JSP , Servlet, Spring, Hibernate, JSF, etc.

How do I get real-time exposure to Java?

You can get real-time exposure to Java by coding in live projects. You can join our Live Java Project to get your hands dirty in Java.

Get the Reddit app

A subreddit for all questions related to programming in any language.

I give you the best 200+ assignments I have ever created (Java)

I'm a public school teacher who has taught the basics of programming to nearly 2,000 ordinary students over the past fifteen years.

I have seen a lot of coding tutorials online, but most of them go too fast ! Maybe some people can learn variables and loops and functions all in one day, but not my students.

So after some prompting from my wife, I've finally decided to post a link to the 200+ assignments I have used to teach Java to my own classes.

I almost never lecture.

Students learn programming by DOING it.

They work through the assignments at their own pace.

Each assignment is only SLIGHTLY harder than the previous one.

The concepts move at normal person speed.

Hopefully the programs are at least somewhat interesting.

Anyway, I'll be happy to help anyone get started. Installing the Java compiler (JDK) and getting your first program to compile is BY FAR the hardest part.

My assignments are at programmingbydoing.com .

Cheers, and thanks for reading this far.

-Graham "holyteach" Mitchell

tl;dr - If you've tried to teach yourself to code but quickly got lost and frustrated, then my assignments might be for you.

Edit : Wow! Thanks so much for all the support. I knew my assignments were great for my own students, but it is good to hear others enjoy them, too. Some FAQs:

I've created r/programmingbydoing . Feel free to post questions and help each other out there.

No, there are currently no solutions available. My current students use these assignments, too.

I'm sorry some of the assignments are a bit unclear. I do lecture sometimes, and I didn't write all of the assignments.

Introduction to Java

  • What Is Java? A Beginner's Guide to Java and Its Evolution
  • Why Java is a Popular Programming Language?
  • Top 10 Reasons Why You Should Learn Java
  • Why Java is a Secure language?
  • What are the different Applications of Java?
  • Java for Android: Know the importance of Java in Android
  • What is the basic Structure of a Java Program?
  • What is the difference between C, C++ and Java?
  • Java 9 Features and Improvements
  • Top 10 Java Frameworks You Should Know
  • Netbeans Tutorial: What is NetBeans IDE and how to get started?

Environment Setup

  • How To Set Path in Java?
  • How to Write Hello World Program in Java?
  • How to Compile and Run your first Java Program?
  • Learn How To Use Java Command Line Arguments With Examples

Control Statements

  • What is for loop in java and how to implement it?
  • What is a While Loop in Java and how to use it?
  • What is for-each loop in Java?
  • What is a Do while loop in Java and how to use it?
  • What is a Switch Case In Java?

Java Core Concepts

  • Java Tutorial For Beginners – Java Programming Made Easy!
  • What are the components of Java Architecture?
  • What are Comments in Java? – Know its Types
  • What are Java Keywords and reserved words?
  • What is a Constructor in Java?
  • What is the use of Destructor in Java?
  • Know About Parameterized Constructor In Java With Examples
  • What are Operators in Java and its Types?
  • What Are Methods In Java? Know Java Methods From Scratch
  • What is Conditional Operator in Java and how to write it?
  • What is a Constant in Java and how to declare it?
  • What is JIT in Java? – Understanding Java Fundamentals
  • What You Should Know About Java Virtual Machine?
  • What is the role for a ClassLoader in Java?
  • What is an Interpreter in Java?
  • What is Bytecode in Java and how it works?
  • What is a Scanner Class in Java?
  • What is the Default Value of Char in Java?
  • this Keyword In Java – All You Need To Know
  • What is Protected in Java and How to Implement it?
  • What is a Static Keyword in Java?
  • What is an Array Class in Java and How to Implement it?
  • What is Ternary Operator in Java and how can you use it?
  • What is Modulus in Java and how does it work?
  • What is the difference between Method Overloading And Overriding?
  • Instance variable In Java: All you need to know
  • Know All About the Various Data Types in Java
  • What is Typecasting in Java and how does it work?
  • How to Create a File in Java? – File Handling Concepts
  • File Handling in Java – How To Work With Java Files?

What is a Comparator Interface in Java?

  • Comparable in Java: All you need to know about Comparable & Comparator interfaces
  • What is Iterator in Java and How to use it?
  • Java Exception Handling – A Complete Reference to Java Exceptions
  • All You Need to Know About Final, Finally and Finalize in Java
  • How To Implement Volatile Keyword in Java?
  • Garbage Collection in Java: All you need to know
  • What is Math Class in Java and How to use it?
  • What is a Java Thread Pool and why is it used?
  • Synchronization in Java: What, How and Why?
  • Top Data Structures & Algorithms in Java That You Need to Know
  • Java EnumSet: How to use EnumSet in Java?
  • How to Generate Random Numbers using Random Class in Java?
  • Generics in Java – A Beginners Guide to Generics Fundamentals
  • What is Enumeration in Java? A Beginners Guide
  • Transient in Java : What, Why & How it works?
  • What is Wait and Notify in Java?
  • Swing In Java : Know How To Create GUI With Examples
  • Java AWT Tutorial – One Stop Solution for Beginners
  • Java Applet Tutorial – Know How to Create Applets in Java
  • How To Implement Static Block In Java?
  • What is Power function in Java? – Know its uses
  • Java Array Tutorial – Single & Multi Dimensional Arrays In Java
  • Access Modifiers in Java: All you need to know
  • What is Aggregation in Java and why do you need it?
  • How to Convert Int to String in Java?
  • What Is A Virtual Function In Java?
  • Java Regex – What are Regular Expressions and How to Use it?
  • What is PrintWriter in Java and how does it work?
  • All You Need To Know About Wrapper Class In Java : Autoboxing And Unboxing
  • How to get Date and Time in Java?
  • What is Trim method in Java and How to Implement it?
  • How do you exit a function in Java?
  • What is AutoBoxing and unboxing in Java?
  • What is Factory Method in Java and how to use it?
  • Threads in Java: Know Creating Threads and Multithreading in Java
  • Join method in Java: How to join threads?
  • What is EJB in Java and How to Implement it?
  • What is Dictionary in Java and How to Create it?
  • Daemon Thread in Java: Know what are it's methods
  • How To Implement Inner Class In Java?
  • What is Stack Class in Java and how to use it?

Java Strings

  • What is the concept of String Pool in java?
  • Java String – String Functions In Java With Examples
  • Substring in Java: Learn how to use substring() Method
  • What are Immutable String in Java and how to use them?
  • What is the difference between Mutable and Immutable In Java?
  • BufferedReader in Java : How To Read Text From Input Stream
  • What are the differences between String, StringBuffer and StringBuilder?
  • Split Method in Java: How to Split a String in Java?
  • Know How to Reverse A String In Java – A Beginners Guide
  • What is Coupling in Java and its different types?
  • Everything You Need to Know About Loose Coupling in Java

Objects and Classes

  • Packages in Java: How to Create and Use Packages in Java?
  • Java Objects and Classes – Learn how to Create & Implement
  • What is Object in Java and How to use it?
  • Singleton Class in Java – How to Use Singleton Class?
  • What are the different types of Classes in Java?
  • What is a Robot Class in Java?

What is Integer class in java and how it works?

  • What is System Class in Java and how to implement it?
  • Char in Java: What is Character class in Java?
  • What is the Boolean Class in Java and how to use it?
  • Object Oriented Programming – Java OOPs Concepts With Examples
  • Inheritance in Java – Mastering OOP Concepts
  • Polymorphism in Java – How To Get Started With OOPs?
  • How To Implement Multiple Inheritance In Java?
  • Java Abstraction- Mastering OOP with Abstraction in Java
  • Encapsulation in Java – How to master OOPs with Encapsulation?
  • How to Implement Nested Class in Java?
  • What is the Use of Abstract Method in Java?
  • What is Association in Java and why do you need it?
  • What is the difference between Abstract Class and Interface in Java?
  • What is Runnable Interface in Java and how to implement it?
  • What is Cloning in Java and its Types?
  • What is Semaphore in Java and its use?
  • What is Dynamic Binding In Java And How To Use It?

Java Collections

  • Java Collections – Interface, List, Queue, Sets in Java With Examples
  • List in Java: One Stop Solution for Beginners
  • Java ArrayList: A Complete Guide for Beginners
  • Linked List in Java: How to Implement a Linked List in Java?
  • What are Vector in Java and how do we use it?
  • What is BlockingQueue in Java and how to implement it?
  • How To Implement Priority Queue In Java?
  • What is Deque in Java and how to implement its interface?
  • What are the Legacy Classes in Java?
  • Java HashMap – Know How to Implement HashMap in Java
  • What is LinkedHashSet in Java? Understand with examples
  • How to Implement Map Interface in Java?
  • Trees in Java: How to Implement a Binary Tree?
  • What is the Difference Between Extends and Implements in Java?
  • How to Implement Shallow Copy and Deep Copy in Java
  • How to Iterate Maps in Java?
  • What is an append Method in Java?
  • How To Implement Treeset In Java?
  • Java HashMap vs Hashtable: What is the difference?
  • How to Implement Method Hiding in Java
  • How To Best Implement Concurrent Hash Map in Java?
  • How To Implement Marker Interface In Java?

Java Programs

  • Palindrome in Java: How to check a number is palindrome?

How to check if a given number is an Armstrong number or not?

  • How to Find the largest number in an Array in Java?
  • How to find the Sum of Digits in Java?
  • How To Convert String To Date In Java?
  • Ways For Swapping Two Numbers In Java
  • How To Implement Addition Of Two Numbers In Java?
  • How to implement Java program to check Leap Year?
  • How to Calculate Square and Square Root in Java?
  • How to implement Bubble Sort in Java?
  • How to implement Perfect Number in Java?
  • What is Binary Search in Java? How to Implement it?
  • How to Perform Merge Sort in Java?
  • Top 30 Pattern Program in Java: How to Print Star, Number and Character
  • Know all about the Prime Number program in Java
  • How To Display Fibonacci Series In Java?
  • How to Sort Array, ArrayList, String, List, Map and Set in Java?
  • How To Create Library Management System Project in Java?
  • How To Practice String Concatenation In Java?

How To Convert Binary To Decimal In Java?

  • How To Convert Double To Int in Java?
  • How to convert Char to Int in Java?
  • How To Convert Char To String In Java?
  • How to Create JFrame in Java?
  • What is Externalization in Java and when to use it?
  • How to read and parse XML file in Java?
  • How To Implement Matrix Multiplication In Java?
  • How To Deal With Random Number and String Generator in Java?

Basic Java Programs for Practice With Examples

Advance java.

  • How To Connect To A Database in Java? – JDBC Tutorial
  • Advanced Java Tutorial- A Complete Guide for Advanced Java
  • Servlet and JSP Tutorial- How to Build Web Applications in Java?
  • Introduction to Java Servlets – Servlets in a Nutshell
  • What Is JSP In Java? Know All About Java Web Applications
  • How to Implement MVC Architecture in Java?
  • What is JavaBeans? Introduction to JavaBeans Concepts
  • Know what are the types of Java Web Services?
  • JavaFX Tutorial: How to create an application?
  • What is Executor Framework in Java and how to use it?
  • What is Remote Method Invocation in Java?
  • Everything You Need To Know About Session In Java?
  • Java Networking: What is Networking in Java?
  • What is logger in Java and why do you use it?
  • How To Handle Deadlock In Java?
  • Know all about Socket Programming in Java
  • Important Java Design Patterns You Need to Know About
  • What is ExecutorService in Java and how to create it?
  • Struts 2 Tutorial – One Stop Solution for Beginners
  • What is Hibernate in Java and Why do we need it?
  • What is Maven in Java and how do you use it?
  • What is Machine Learning in Java and how to implement it?

Career Opportunities

  • Java Developer Resume: How to Build an Impressive Resume?
  • What is the Average Java Developer Salary?

Interview Questions

  • Java Interview Questions and Answers
  • Top MVC Interview Questions and Answers You Need to Know in 2024
  • Top 50 Java Collections Interview Questions You Need to Know in 2024
  • Top 50 JSP Interview Questions You Need to Know in 2024
  • Top 50 Hibernate Interview Questions That Are A Must in 2024

Programming & Frameworks

core java assignments for practice

Java is one of the most popular programming languages used in the IT industry. It is simple, robust, and helps us reuse code. In this article, we will examine basic to advanced Java programs to  practice and understand Java fundamentals.

Java Full Course in 10 Hours | Java Tutorial for Beginners [2024] | Java Online Training | Edureka

This Edureka Java Full Course will help you in understanding the various fundamentals of Java Programming and also helps you to became a master in Advanced Java concepts

Below is the list of programs that I will be covering in this article.

What are the basic Java programs for beginners?

  • Calculator Program in Java
  • Factorial Program using Recursion
  • Fibonacci Series Program
  • Palindrome Program in Java
  • Permutation and Combination Program
  • Pattern Programs in Java
  • String Reverse Program in Java
  • Mirror Inverse Program in Java

What are some Advanced Java Programs for practice?

  • Binary Search Program in Java
  • HeapSort Program in Java
  • Removing Elements from ArrayList
  • HashMap Program in Java
  • Circular LinkedList Program in Java
  • Java DataBase Connectivity Program
  • Transpose of a Matrix Program

Let’s get started !

1. Write a Java program to perform basic Calculator operations.

When you think about a calculator, operations like addition, subtraction, multiplication, and division comes into the mind. Let’s implement the basic calculator operations with the help of the below program.

When you execute the above program, the output looks like as shown below:

2. Write a simple Java program to calculate a Factorial of a number.

Factorial of a number is the product of all the positive numbers less than or equal to the number. The factorial of a number n is denoted by n!

Now, let’s write a program and find factorial of a number using recursion.

On executing the above program, you will get factorial of a number as shown below:

3. Write a simple Java program to calculate Fibonacci Series up to n numbers.

It is a series in which the next term is the sum of the preceding two terms. For Example: 0 1 1 2 3 5 8 13…….  Let’s write a Java program to calculate the Fibonacci series.

On executing the above code, the output looks like :

4. Write a Java program to find out whether the given String is Palindrome or not. 

A palindrome is a number, string or a sequence which will be the same even after you reverse the order. For example, RACECAR, if spelled backward will be same as RACECAR.

When you run the code, it will check whether the given string is a palindrome or not as shown below:

5. Write a Java program to calculate Permutation and Combination of 2 numbers.

It is the different arrangements of a given number of elements taken one by one, or some, or all at a time. Let’s have a look at its implementation.

On executing the above code, the output looks like as shown below:

6. Write a program in Java to find out Alphabet and Diamond Pattern.

Here, you can use the   for loop   to print various patterns in Java. I will be implementing two different patterns in this article. First one will be Alphabet A pattern and the next one will be Diamond shaped pattern.  Let’s now see the implementation of the alphabet A pattern.

This will be the output of Diamond-Shaped Pattern program. Now let’s move further and see what’s next.

Related Article: Top 30 Java Pattern Programs

7. Write a Java Program to reverse the letters present in the given String.

This  Java program reverses letters present in the string entered by a user. For example, Hello People will be termed as olleH elpoeP. Let’s implement the same using Java.

The output of the above program will be as shown below:

8. Write a Java Program to check whether the given array is Mirror Inverse or not.

Output: No 

// If the given array was {3,4,2,0,1} then it would have printed yes as the output because the array is mirror inverse.

What are some advanced Java Programs for practice?

1. write a java program to implement a binary search algorithm..

It is a   search   algorithm that finds the position of a target value within a sorted array.   Binary search compares the target value to the middle element of the array. Let’s now see how to implement a binary search algorithm.

On executing the above program, it will locate the element present at the particular index

2. Write a Java program to implement HeapSort Algorithm.

Heap sort   is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. Then repeat the same process for the remaining element. Let’s write the program and understand its working.

3. Write a Java program to remove elements from an ArrayList

ArrayList is the implementation of List Interface where the elements can be dynamically added or removed from the list. Also, the size of the list is increased dynamically if the elements are added more than the initial size. In the below program, I am first inserting elements into the ArrayList and then deleting the elements from the list based on the specification. Let’s understand the code.

Output on execution of the program looks like:

4. Write a program in Java to implement HashMap.

HashMap   is a Map based collection class that is used for storing Key & value pairs, it is denoted as   HashMap <Key, Value> or   HashMap <K, V>. This class makes no guarantees as to the order of the map. It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).  Let’s see how to implement HashMap logic in Java with the help of below program.

On executing the HashMap program, output goes like this:

5. Write a Java program to print the nodes present in the Circular LinkedList

It follows the first thing first approach. Here, the node is an element of the  list , and it has two parts that are, data and next. Data represents the data stored in the node and next is the pointer that will point to the next node. let’s now understand its implementation.

On executing this program, the output will be as shown below:

6. Write a Java program to connect to a SQL DataBase.

On executing the above code, it will establish the connection to the database and retrieve the data present in the database.

7. Write a Java Program to find the Transpose of a given Matrix.

Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].

On executing the above program, output goes like this:

In case you are facing any challenges with these java programs, please comment your problems in the section below. Apart from this Java Programs article, if you want to get trained from professionals on this technology, you can opt for structured training from Edureka!

So this brings us to the end of the Java Programs blog. I hope you found it informative and helped you in understanding Java Fundamentals. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

Check out the Java Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

If you want to start a career in the Node JS Field then check out the Best Node JS Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of this “ Java Programs” article and we will get back to you as soon as possible.

Course NameDateDetails

Class Starts on 3rd August,2024

3rd August

SAT&SUN (Weekend Batch)

Class Starts on 28th September,2024

28th September

SAT&SUN (Weekend Batch)

Recommended videos for you

Effective persistence using orm with hibernate, microsoft sharepoint-the ultimate enterprise collaboration platform, php and mysql : server side scripting for web development, node js express: steps to create restful web app, building web application using spring framework, microsoft .net framework : an intellisense way of web development, building application with ruby on rails framework, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, introduction to java/j2ee & soa, portal development and text searching with hibernate, rapid development with cakephp, create restful web application with node.js express, mastering regex in perl, a day in the life of a node.js developer, nodejs – communication and round robin way, hibernate-the ultimate orm framework, learn perl-the jewel of scripting languages, hibernate mapping on the fly, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, php & mysql : server-side scripting language for web development, recommended blogs for you, java developer skills: important skills of a java developer, a step by step guide to how to setup eclipse ide on windows, everything you need to know about intellij idea ide, how to implement file_exists function in php, what is an er diagram and how to implement it, how to implement str_replace in php, java exceptions cheat sheet – level up your java knowledge, how to implement intval in php, how to best utilize assertions in java, difference between throw throws and throwable in java, node.js npm tutorial – how to get started with npm, all you need to know about switch case in php, all you need to know about javascript objects, what is power function in java – know its uses, top 50 typescript interview questions you must prepare in 2024, join the discussion cancel reply, trending courses in programming & frameworks, full stack web development internship program.

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Course Online

  • 77k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Flutter Application Development Course

  • 12k Enrolled Learners

Spring Framework Certification Course

Node.js certification training course.

  • 10k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

Comprehensive Java Course Certification Train ...

  • 19k Enrolled Learners

C Programming Certification Course

  • 3k Enrolled Learners

Browse Categories

Subscribe to our newsletter, and get personalized recommendations..

Already have an account? Sign in .

20,00,000 learners love us! Get personalised resources in your inbox.

At least 1 upper-case and 1 lower-case letter

Minimum 8 characters and Maximum 50 characters

We have recieved your contact details.

You will recieve an email from us shortly.

Download Interview guide PDF

  • Java Interview Questions

Download PDF

Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java . Before we begin, let's understand what Java is all about.

What is Java? 

Java is a high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications. 

The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, collections interview questions, and some frequently asked Java coding interview questions.

Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java.

So, let’s dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  • Java interview questions for Freshers

Java Intermediate Interview Questions

Java interview questions for experienced, java programming interview questions.

Join our community and share your recent Java interview experiences.

Java Interview Questions for Freshers

1. why is java a platform independent language.

Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

  • The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

2. Why is Java not a pure object oriented language?

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language .

3. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program :

For this java program. The stack and heap memory occupied by java is -

core java assignments for practice

Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 

And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

4. Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that Java is the complete object-oriented programming language because everything in Java is under the classes and we can access them by creating the objects.

But we can even say that Java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is Java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the Integer classes.

5. How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Learn via our Video Courses

6. pointers are used in c/ c++. why does java not make use of pointers.

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

7. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

core java assignments for practice

8. What are the default values assigned to variables and instances in java?

  • There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). 
  • But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. 
  • If it is a reference, then it will be assigned to null. 
  • If it is numeric, then it will assign to 0.
  • If it is a boolean, then it will be assigned to false. Etc.

9. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

core java assignments for practice

10. Tell us something about JIT compiler.

  • JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
  • First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
  • Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
  • JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
  • Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

core java assignments for practice

11. Can you tell the difference between equals() method and equality operator (==) in Java?

We are already aware of the (==) equals operator. That we have used this to compare the equality of the values. But when we talk about the terms of object-oriented programming, we deal with the values in the form of objects. And this object may contain multiple types of data. So using the (==) operator does not work in this case. So we need to go with the . equals() method.

Both [(==) and .equals()] primary functionalities are to compare the values, but the secondary functionality is different. 

So in order to understand this better, let’s consider this with the example -

This code will print true. We know that both strings are equals so it will print true. But here (==) Operators don’t compare each character in this case. It compares the memory location. And because the string uses the constant pool for storing the values in the memory, both str1 and str2 are stored at the same memory location. See the detailed Explanation in Question no 73: Link .

core java assignments for practice

Now, if we modify the program a little bit with -

core java assignments for practice

Then in this case, it will print false. Because here no longer the constant pool concepts are used. Here, new memory is allocated. So here the memory address is different, therefore ( == ) Operator returns false. But the twist is that the values are the same in both strings. So how to compare the values? Here the .equals() method is used.

.equals() method compares the values and returns the result accordingly.  If we modify the above code with - 

Then it returns true.

equals()  ==
This is a method defined in the Object class.  It is a binary operator in Java.
The .equals() Method is present in the Object class, so we can override our custom .equals() method in the custom class, for objects comparison. It cannot be modified. They always compare the HashCode.
This method is used for checking the equality of contents between two objects as per the specified business logic. This operator is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.
  • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
  • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

12. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
  • Using while loop:
  • Using do-while loop:

13. Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

core java assignments for practice

Three constructors are defined here but they differ on the basis of parameter type and their numbers.

14. Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class. 

Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

15. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

Consider the below code snippets: 

16. Comment on method overloading and overriding by citing relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

core java assignments for practice

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding. Let’s give a look at this example:

core java assignments for practice

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

17. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

18. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
  • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • A method declared as final cannot be overridden by its children's classes.
  • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

19. Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

 Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

  • Suppose we use System.exit() in the above statement.
  • If there are fatal errors like Stack overflow, Memory access error, etc.

21. Identify the output of the java program and state the reason.

The above code will generate a compile-time error at Line 7 saying - [error: variable i might already have been initialized] . It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.

22. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.

23. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

24. Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.

Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static. 

25. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

26. Difference between static methods, static variables, and static classes in java.

  • For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.  And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
  • Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.

27. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

28. What is a ClassLoader?

  • Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. 
  • Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

29. What part of memory - Stack or Heap - is cleaned in garbage collection process?

30. what are shallow copy and deep copy in java.

To copy the object's data, we have several methods like deep copy and shallow copy. 

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

  • Shallow copy - The shallow copy only creates a new reference and points to the same object. Example - For Shallow copy, we can do this by -

Now by doing this what will happen is the new reference is created with the name obj2 and that will point to the same memory location.

  • Deep Copy - In a deep copy, we create a new object and copy the old object value to the new object. Example -

Both these objects will point to the memory location as stated below -

core java assignments for practice

Now, if we change the values in shallow copy then they affect the other reference as well. Let's see with the help of an example - 

We can see that in the above code, if we change the values of object1, then the object2 values also get changed. It is because of the reference.

Now, if we change the code to deep copy, then there will be no effect on object2 if it is of type deep copy. Consider some snippets to be added in the above code.

The above snippet will not affect the object2 values. It has its separate values. The output will be

Now we see that we need to write the number of codes for this deep copy. So to reduce this, In java, there is a method called clone().  

The clone() will do this deep copy internally and return a new object. And to do this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

1. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.

core java assignments for practice

  • Multithreading : The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections : In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

2. What is a singleton class in Java? And How to implement a singleton class?

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as -

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance() . And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

3. Which of the below generates a compile-time error? State the reason.

  • int[] n1 = new int[0];
  • boolean[] n2 = new boolean[-200];
  • double[] n3 = new double[2241423798];
  • char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large . It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number ( 2241423798 ) is beyond the capacity of the integer. The maximum array size we can declare is - ( 2147483647 ).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException . 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

4. How would you differentiate between a String, StringBuffer, and a StringBuilder?

  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:

5. Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types : Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

Interface example:

6. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘InterviewBit’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

7. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

8. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

9. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

10. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

11. What do we get in the JDK file?

  • JDK - For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE -  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example - there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM - (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

core java assignments for practice

12. What are the differences between JVM, JRE and JDK in Java?

Criteria JDK  JRE JVM
Abbreviation Java Development Kit Java Runtime Environment Java Virtual Machine
Definition JDK is a complete software development kit for developing Java applications. It comprises JRE, JavaDoc, compiler, debuggers, etc. JRE is a software package providing Java class libraries, JVM and all the required components to run the Java applications. JVM is a platform-dependent, abstract machine comprising of 3 specifications - document describing the JVM implementation requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution.
Main Purpose JDK is mainly used for code development and execution. JRE is mainly used for environment creation to execute the code. JVM provides specifications for all the implementations to JRE.
Tools provided JDK provides tools like compiler, debuggers, etc for code development JRE provides libraries and classes required by JVM to run the program. JVM does not include any tools, but instead, it provides the specification for implementation.
Summary JDK = (JRE) + Development tools JRE = (JVM) + Libraries to execute the application JVM = Runtime environment to execute Java byte code.

13. What are the differences between HashMap and HashTable in Java?

HashMap HashTable
HashMap is not synchronized thereby making it better for non-threaded applications. HashTable is synchronized and hence it is suitable for threaded applications.
Allows only one null key but any number of null in the values. This does not allow null in both keys or values.
Supports order of insertion by making use of its subclass LinkedHashMap. Order of insertion is not guaranteed in HashTable.

14. What is the importance of reflection in Java?

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.

15. What are the different ways of threads usage?

  • Extending the Thread class
  • Implementing the Runnable interface
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

16. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

17. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

18. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘ throw ’ keyword is used to manually throw the exception to the calling method.
  • And the ‘ throws ’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.

19. What are the differences between constructor and method of a class in Java?

Constructor Method
Constructor is used for initializing the object state. Method is used for exposing the object's behavior.
Constructor has no return type. Method should have a return type. Even if it does not return anything, return type is void.
Constructor gets invoked implicitly. Method has to be invoked on the object explicitly.
If the constructor is not defined, then a default constructor is provided by the java compiler. If a method is not defined, then the compiler does not provide it.
The constructor name should be equal to the class name. The name of the method can have any name or have a class name too.
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - A method can be defined as final but it cannot be overridden in its subclasses.
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects. A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.

20. Identify the output of the below java program and Justify your answer.

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

21. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

22. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

core java assignments for practice

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ] .

23. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

24. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
  • In the above example, all the fields except someInfo can be serialized.

25. What happens if the static modifier is not included in the main method signature in Java?

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

26. Consider the below program, identify the output, and also state the reason for that.

The output of the above program will be Hello. Main Method . This is because JVM will always call the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

27. Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

28. What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

29. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

30. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

core java assignments for practice

31. How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

32. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

34. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this() .

core java assignments for practice

35. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.

core java assignments for practice

However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

core java assignments for practice

36. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then the address will be like this -

core java assignments for practice

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)] . So according to this. The starting address of the index 4 will be - [100 + (4*4)] = 116 . And exactly that's what the address is calculated.  Now consider the same with 1 index Array -

core java assignments for practice

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [ Base Address + ((index-1) * no_of_bytes)] .

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

37. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example - To Delete from the front of the linked list, internally the references adjustments happened like this.

core java assignments for practice

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

core java assignments for practice

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

38. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

Return Type Method Description
boolean : This method is used for adding the element at the end of the List. The Datatype of the element is of any type it has been initially assigned with. It returns the boolean indicating successfully inserted or not.
void : This method is the overloaded version of add() method. In this, along with the element, the index is also passed to the method for the specific index the value needs to be inserted. 
boolean : This method helps to add all elements at the end of collections from the list received in the parameter. It contains an iterator that helps to iterate the list and add the elements to the collection.
boolean : This is the overloaded method for addAll() method. In this along with the list, we can pass the specified index from which the list elements need to be added.

39. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -

1. Consider initially that there are 2 elements in the ArrayList. [2, 3] .

core java assignments for practice

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old - [2, 3],    New - [2, 3, null].

core java assignments for practice

  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

core java assignments for practice

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed -

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

core java assignments for practice

2. After searching the element, it needs to shift the element from the right side to fill the index.

core java assignments for practice

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

1. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.

Let’s take an example:

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

2. What is the difference between ‘>>’ and ‘>>>’ operators in java?

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators.

  • ‘>>’ Bitwise Right Shift Operator - This operator shifts each bit to its right position. And this maintains the signed bit.
  • ‘>>>’ Bitwise Right Shift Operator with trailing zero - This operator also shifts each bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit to 0.

Example- Num1 = 8, Num2 = -8.

So the binary form of these numbers are - 

Num1 = 00000000 00000000 00000000 00001000  Num2 = 11111111 11111111 11111111  11111000

‘>>’ Operator : 8 >> 1 (Shift by one bit) : 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 11111111 11111111 11111111  11111100

‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 01111111 11111111 11111111 11111100

3. What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let’s understand with the help of an example. 

  • Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically.  So here we can say that there is a strong association between the objects. So this Strong Association is called Composition .
  • Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor’s). So here is the weak association between the objects. And this weak association is called Aggregation .

4. How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

The checking() function will return true as the same content is referenced by both the variables.

core java assignments for practice

Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

The checking() function will return false as the same content is not referenced by both the variables.

core java assignments for practice

5. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?

Both ‘ new ’ and ‘ newInstance() ’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘ newInstance() ’ operator.

The ‘ newInstance() ’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.

6. Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

7. Why is synchronization necessary? Explain with the help of a relevant example.

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

core java assignments for practice

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

core java assignments for practice

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

8. In the given code below, what is the significance of ... ?

  • Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
  • The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
  • For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

9. What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?

The Output we get by executing this program will be

Static Block 1. Value of j = 0 Static method.  Static Block 2. Value of j = 10 Instance Block 1. Value of i = 0 Instance Block 2. Value of i = 5 Instance method.  Welcome to InterviewBit

This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are - 

  • Identification of Static Members from top to bottom.
  • Execution of Static variable assignment and a Static block from top to bottom.
  • Execution of the main method.
  • Identification of Instance Members from top to bottom.
  • Execution of Instance variable assignment and Instance block from top to bottom.
  • Execution of Constructor.

In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be performed.

Now from the above code, the execution will happen like this - 

1. In the step of identification of static members. It is found that -

  • static int j.
  • static block.
  • main method.
  • static method_2.

During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned.

2. In the next step, it will execute the static block and assign the value in static variables.

  • First static block it will print and because execution from top to bottom and original value in j is not assigned. So it will print the default value of 0.
  • After executing static block 1. It will execute the static method_1 because it is called from the static block 1.
  • Then it will assign the original value of 5 in the j variable. And executes the remaining static block.

3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of instances will happen.

4. Identify the instance variables and blocks from top to bottom. 

  • Instance block 1.
  • Instance method_1.

Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly.

5. It will execute the instance methods and assign the original value to the instance variable.

  • Prints the Instance block 1. And the current value of i is not assigned till now, so it will print 0.
  • Assign the original value to i. Then print instance block 2. And after that instance method will be called and printed because it is being called in the instance block.

6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor.

This is how the java program gets executed.

10. Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package . Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

11. Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:

  • New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
  • Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
  • Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

The following flowchart clearly explains the lifecycle of the thread in Java.

core java assignments for practice

12. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

  • The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n) .
  • The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1).
  • Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

13. Is it possible to import the same class or package twice in Java and what happens to it during runtime?

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

14. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

15. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

16. What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

17. Explain the term “Double Brace Initialisation” in Java?

This is a convenient means of initializing any collections in Java. Consider the below example.

In the above example, we see that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

18. Why is it said that the length() method of String class doesn't return accurate results?

  • The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below.
  • Code Point: This represents an integer denoting a character in the code space.
  • Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
  • The code points from the first plane are encoded using one 16-bit code unit
  • The code points from the remaining planes are encoded using two code units.

Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected.

In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

19. What is the output of the below code and why?

“bit” would have been the result printed if the letters were used in double-quotes (or the string literals). But the question has the character literals (single quotes) being used which is why concatenation wouldn't occur. The corresponding ASCII values of each character would be added and the result of that sum would be printed. The ASCII values of ‘b’, ‘i’, ‘t’ are:

98 + 105 + 116 = 319

Hence 319 would be printed.

20. What are the possible ways of making object eligible for garbage collection (GC) in Java?

First Approach: Set the object references to null once the object creation purpose is served.

Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.

Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.

21. In the below Java Program, how many objects are eligible for garbage collection?

In the above program, a total of 7 objects will be eligible for garbage collection. Let’s visually understand what's happening in the code.

core java assignments for practice

In the above figure on line 3, we can see that on each array index we are declaring a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection.

22. What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - 

Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

23. How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes:

  • Global-session

24. What are the different categories of Java Design patterns?

Java Design patterns are categorized into the following different types. And those are also further categorized as 

Structural patterns:

Behavioral patterns:

  • Interpreter
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Strategy pattern
  • Visitor pattern

J2EE patterns:

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Creational patterns:

  • Factory method/Template
  • Abstract Factory

25. What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Example - Consider a linked list like the structure below -

core java assignments for practice

In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced object. So this can be the situation of memory leak.

Some common causes of Memory leaks are - 

  • When there are Unbounded caches.
  • Excessive page swapping is done by the operating system.
  • Improper written custom data structures.
  • Inserting into a collection object without first deleting it. etc.

26. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

A thread that has a lock won't be released even after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will not be released.

1. Check if a given string is palindrome using recursion.

/* * Java program to check if a given inputted string is palindrome or not using recursion. */ import java.util.*; public class InterviewBit { public static void main (String args[]) { Scanner s = new Scanner(System.in); String word = s.nextLine(); System.out.println( "Is " +word+ " palindrome? - " +isWordPalindrome(word)); } public static boolean isWordPalindrome (String word) { String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if (word.equals(reverseWord)){ return true ; } return false ; } public static String getReverseWord (String word) { if (word == null || word.isEmpty()){ return word; } return word.charAt(word.length()- 1 ) + getReverseWord(word.substring( 0 , word.length() - 1 )); } }

2. Write a Java Program to print Fibonacci Series using Recursion.

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.

3. Write a Java program to check if the two strings are anagrams.

The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.

4. Write a Java Program to find the factorial of a given number.

public class FindFactorial { public static void main (String[] args) { int num = 10 ; long factorialResult = 1l ; for ( int i = 1 ; i <= num; ++i) { factorialResult *= i; } System.out.println( "Factorial: " +factorialResult); } }

5. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.

6. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

  • Step 1: 163 => 1+6+3 = 10
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

7. Write a Java program to create and throw custom exceptions.

We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.

8. Write a Java program to reverse a string.

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

9. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

In the above code, for rotating the matrix to  90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.

10. Write a java program to check if any number given as input is the sum of 2 prime numbers.

18 = 13 + 5 18 = 11 + 7

In the above code, for any number n , we find all the 2 pairs of numbers that are added together resulting in n . And each checking number if it is prime. If it is prime then we are printing that.

11. Write a Java program for solving the Tower of Hanoi Problem.

In the above code we are first moving the n-1 disk from Tower A to Tower B , then moving that nth disk from Tower A to Tower C , and finally, the remaining n-1 disk from Tower B to Tower C . And we are doing this recursively for the n-1 disk.

12. Implement Binary Search in Java using recursion.

In the above code, we are finding the middle element each time and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

1. Conclusion

Java is one of the simple high-level languages that provides powerful tools and impressive standards required for application development. It was also one of the first languages to provide amazing threading support for tackling concurrency-based problems. The easy-to-use syntax and the built-in features of Java combined with the stability it provides to applications are the main reasons for this language has ever-growing usage in the software community.

Interview Preparation Resources

  • How to Become a Java Developer?
  • How much does a Java Developer earn in India?
  • Java Projects
  • Java Programming Questions for Interview
  • Java 8 Interview Questions
  • Java String Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • Java Collections Interview Questions
  • Array Interview Questions
  • Design Patterns Interview Questions
  • Multithreading Interview Questions
  • Java Tutorial
  • Advance Java MCQ
  • Difference Between C++ and Java
  • Difference Between C and Java
  • Difference Between Java and Javascript
  • Hashmap vs Hashtable in Java
  • Kotlin Vs Java
  • Java Vs Python
  • Features of Java 9
  • Java 8 Features
  • Java Frameworks
  • Java Developer Skills
  • Java 11 Features
  • Additional Technical Interview Questions
  • JAVA SE Download

Coding Problems

What is the output of the below code?

What component does the task of bytecode to machine code conversion?

Which of the following happens when the garbage collection process kicks off during the execution of the thread?

What is the functionality of Class.getInstance() ?

What is the output of the below piece of code?

What is the output of the following code?

Which of the following is the functionality of the java interpreter?

What is the component used for compiling, debugging, and executing java programs?

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

Study.com

In order to continue enjoying our site, we ask that you confirm your identity as a human. Thank you very much for your cooperation.

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

Difference Between Destructuring Assignment and Dot Notation in JavaScript

JavaScript offers various ways to access and assign values from the objects and arrays. Two common methods are destructuring assignment and dot notation. Understanding the differences between these methods can help us write more efficient and readable code.

These are the following topics that we are going to discuss:

Table of Content

What is Destructuring Assignment?

What is dot notation, difference between destructuring assignment and dot notation in javascript.

The Destructuring assignment is a JavaScript feature introduced in the ES6 that allows you to extract values from the arrays or properties from the objects into the distinct variables. This syntax provides a more concise and readable way to unpack values.

Characteristics:

  • Concise Syntax: It allows for the shorter and more readable code.
  • Pattern Matching: Can extract multiple properties or elements in one statement.
  • Default Values: We can assign default values if the unpacked value is undefined.
  • Nested Destructuring: It supports extracting properties from the nested objects and arrays.

Applications:

  • Simplifying variable assignments.
  • Extracting multiple properties from an object at once.
  • Using in the function parameters to directly extract properties.

Example: In this example, Object Destructuring extracts ‘name’, ‘age’, and ’email’ from the ‘user’ object and the Array Destructuring extracts the first two elements and collects the rest into an array.

The Dot notation is a straightforward way to access object properties by using the dot followed by the property name. It is the most commonly used method to read and assign properties in JavaScript objects.

  • Simplicity: Easy to read and understand.
  • Direct Access: Directly access nested properties.
  • Property Names: Can only be used with the valid JavaScript identifiers.
  • The Accessing and assigning single properties.
  • The Navigating through object properties.
  • The Simple and straightforward property access.

Example: In this example, Accesses and logs properties of the ‘user’ object, then updates and logs the ‘age’ property.

Characteristics

Destructuring assignment

Dot notation

Syntax

The Concise and allows unpacking the multiple properties at once

The Simple and direct accesses single properties

Readability

The More readable for the multiple assignments

The More readable for the single property access

Use Case

Ideal for the extracting multiple properties or elements

Ideal for the accessing or updating single properties

Default Values

The Supports assigning default values

Does not support default values

Nested Structures

Supports nested destructuring for the objects and arrays

Requires multiple dot notations for nested access

Property Names

Can use any valid JavaScript identifier

Can only use valid JavaScript identifiers

Code Example

const {name, age} = user;

const name = user.name;

Complexity

The Slightly complex for beginners but powerful for the complex objects

The Simple and intuitive

Both destructuring assignment and dot notation are useful tools in JavaScript for the accessing and assigning values from the objects and arrays. The Destructuring assignment is particularly powerful when dealing with the multiple properties or nested structures offering a concise and readable syntax. Dot notation on the other hand is straightforward and ideal for the accessing single properties. Understanding when and how to the use each can significantly improve the efficiency and readability of the code.

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. practice notes123

    core java assignments for practice

  2. Core Java Training Day 05 Team Practice Assignments SDET Training

    core java assignments for practice

  3. Core Java Assignments

    core java assignments for practice

  4. Core Java Assignments: Day #2: Inheritance and Polymorphism

    core java assignments for practice

  5. Day 1 Core Java Assignments

    core java assignments for practice

  6. GitHub

    core java assignments for practice

VIDEO

  1. "Java Practice Questions

  2. Java Practice It

  3. Mastering Java Interview Questions: Common Challenges and Expert Answers

  4. Core Java Tutorial || Methods || Video-1 || Introduction || By Ratan Sir

  5. Core Java Tutorial || String Manipulation || Video-4 || Equals( ) Method, = Operator || By Ratan Sir

  6. Core java Tutorials || Collections Framework || video-38|| All Collection Classes || By Ratan sir

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. A sample solution is provided for each exercise. It is recommended to do these exercises by yourself first before checking ...

  2. Java Exercises

    That covers various Java Core Topics that can help users with Java Practice. So, with ado further take a look at our free Java Exercises to practice and develop your Java programming skills. Our Java programming exercises Practice Questions from all the major topics like loops, object-oriented programming, exception handling, and many more.

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

  4. 800+ Java Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this: public static boolean returnTrue () { } All you have to do is type return true; between the curly braces { } and then click the Check button. If you did this correctly, the button will turn re ...

  5. Practice Java

    Complete your Java coding practice with our online Java practice course on CodeChef. Solve over 180 coding problems and challenges to get better at Java. ... But believe me, you can do it without any assistance! One thing to remember is to come prepared with a knowledge of core and advanced concepts. #CodeWell! (4.0) inaamulh66. Student.

  6. Core Java MCQ

    Welcome to this comprehensive guide featuring 100 Multiple-Choice Questions (MCQs) on Core Java. Java remains one of the most popular, versatile, and widely-used programming languages in the world, and understanding its core concepts is essential for anyone aspiring to become proficient in it. Whether you are a beginner, an intermediate ...

  7. Java Exercises

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

  8. Java Basic Programming Exercises

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

  9. Solve Java

    Java Stdin and Stdout I. Easy Java (Basic) Max Score: 5 Success Rate: 96.86%. Solve Challenge. Java If-Else. Easy Java (Basic) Max Score: 10 Success Rate: 91.37%. Solve Challenge. Java Stdin and Stdout II. Easy Java (Basic) Max Score: 10 Success Rate: 92.71%. Solve Challenge. Java Output Formatting.

  10. Fundamentals of Java Programming

    The Core Java module is a comprehensive training program that covers the fundamental concepts of the Java programming language. This module provides a deep understanding of Java programming and its key components. ... Practice Quiz • 30 minutes; Core Java ... To access graded assignments and to earn a Certificate, you will need to purchase ...

  11. 50 Java Projects with Source Code for All Skill Levels

    Source Code. Click Here. The Breakout Game project is an exhilarating Java application that challenges players to smash through rows of bricks using a bouncing ball and a paddle. This project offers programmers an opportunity to apply their Java skills while recreating the timeless and addictive gameplay of Breakout.

  12. Java Coding Practice

    Description. Get starting with your java coding practice with these java exercises. There is a wide range of java problems to solve. Mailchimp. Personalize product recommendations and discount offers based on behavior data and lifetime value.Start Free Trial. Ads via Carbon.

  13. Java Array exercises: Array Exercises

    Java Array Exercises [79 exercises with solution] [ An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Write a Java program to sort a numeric array and a string array. Click me to see the solution. 2. Write a Java program to sum values of an array. Click me to see the solution.

  14. Core Java Quiz

    Core Java Quiz | Java Online Test. There are a list of core java quizzes such as basics quiz, oops quiz, string handling quiz, array quiz, exception handling quiz, collection framework quiz etc. After clearing the exam, play our Belt Series Quiz and earn points. These points will be displayed on your profile page.

  15. Java exercises on Exercism

    Code practice and mentorship for everyone. Develop fluency in 70 programming languages with our unique blend of learning, practice and mentoring. Exercism is fun, effective and 100% free, forever. Explore the 147 Java exercises on Exercism.

  16. Best Way To Start Learning Core Java

    Make yourself self-motivated to learn Java and build some awesome projects using Java. Do it regularly and also start learning one by one new concepts on Java. It will be very better to join some workshops or conferences on Java before you start your journey. 1) Data Types and Variables.

  17. Java Programs

    Java, With the help of this course, students can now get a confidant to write a basic program to in-depth algorithms in C Programming or Java Programming to understand the basics one must visit the list 500 Java programs to get an idea. Users can now download the top 100 Basic Java programming examples in a pdf format to practice.

  18. Java Programming Exercises with Solutions

    Java Programming Exercises to Improve your Coding Skills with Solutions. All you need to excel on a Java interview ! Now with Java 8 Lamdbas and Streams exercises. ... 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 ...

  19. Java practical assignments questions

    Q.1 WAP in java to create Box class with parameterized constructor with an object arguement. to initialize length, breadth and height also create a function volume which returns the volume. of the box and print it in main method. Q.2 Write a program in java with class Employee and do the following operations on it.

  20. java-practice · GitHub Topics · GitHub

    Java-Programs---For-Practice is one of the Java Programming Practice Series By Shaikh Minhaj ( minhaj-313 ). This Series will help you to level up your Programming Skills. This Java Programs are very much helpful for Beginners. If You Have any doubt or query you can ask me here or you can also ask me on My LinkedIn Profile : https://www.linkedin…

  21. Java Tutorial for Beginners: Learn Core Java Programming

    Java Tutorial Summary. This Java tutorial for beginners is taught in a practical GOAL-oriented way. It is recommended you practice the code assignments given after each core Java tutorial to learn Java from scratch. This Java programming for beginners course will help you learn basics of Java and advanced concepts.

  22. I give you the best 200+ assignments I have ever created (Java)

    A subreddit for all questions related to programming in any language. I give you the best 200+ assignments I have ever created (Java) I'm a public school teacher who has taught the basics of programming to nearly 2,000 ordinary students over the past fifteen years. I have seen a lot of coding tutorials online, but most of them go too fast!

  23. Best Java Programs for Practice: Beginners and Experienced

    6. Write a Java program to connect to a SQL DataBase. JDBC is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. This application program interface lets you encode the access request statements, in Structured Query Language ( SQL ).

  24. Core Java Interview Questions and Answers (2024)

    Learn and Practice on almost all coding interview questions asked historically and get referred to the best tech companies ... to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java. ... Execution of Static variable assignment and a Static block from ...

  25. Assignment 2: Searching Text & String Data

    The application must address the following requirements: The application uses the names of 50 states in the United States as the input text. It uses the bad character rule of the Boyer-Moore ...

  26. Difference Between Destructuring Assignment and Dot Notation in

    Destructuring assignment is a feature introduces in EcmaScript2015 which lets you extract the contents of array, properties of object into distinct variables without writing repetitive code. Example 1: Here in this example we declared two variables a and b unassigned and an array with two strings "First" and "Second" int it.