- ▼Java Exercises
- ▼Java Basics
- Basic Part-I
- Basic Part-II
- ▼Java Data Types
- Java Enum Types
- ▼Java Control Flow
- Conditional Statement
- Recursive Methods
- ▼Java Math and Numbers
- ▼Object Oriented Programming
- Java Constructor
- Java Static Members
- Java Nested Classes
- Java Inheritance
- Java Abstract Classes
- Java Interface
- Java Encapsulation
- Java Polymorphism
- Object-Oriented Programming
- ▼Exception Handling
- Exception Handling Home
- ▼Functional Programming
- Java Lambda expression
- ▼Multithreading
- Java Thread
- Java Multithreading
- ▼Data Structures
- ▼Strings and I/O
- File Input-Output
- ▼Date and Time
- ▼Advanced Concepts
- Java Generic Method
- ▼Algorithms
- ▼Regular Expressions
- Regular Expression Home
- ▼JavaFx Exercises
- JavaFx Exercises Home
- ▼Java Projects
- Java Projects for Beginners
- ..More to come..
Java Basic Programming : Exercises, Practice, Solution
Java basic exercises [150 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 print 'Hello' on screen and your name on a separate line. Expected Output : Hello Alexandra Abramov
Click me to see the solution
2. Write a Java program to print the sum of two numbers. Test Data: 74 + 36 Expected Output : 110
3. Write a Java program to divide two numbers and print them on the screen. Test Data : 50/3 Expected Output : 16
4. Write a Java program to print the results of the following operations. Test Data: a. -5 + 8 * 6 b. (55+9) % 9 c. 20 + -3*5 / 8 d. 5 + 15 / 3 * 2 - 8 % 3 Expected Output : 43 1 19 13
5. Write a Java program that takes two numbers as input and displays the product of two numbers. Test Data: Input first number: 25 Input second number: 5 Expected Output : 25 x 5 = 125
6. Write a Java program to print the sum (addition), multiply, subtract, divide and remainder of two numbers. Test Data: Input first number: 125 Input second number: 24 Expected Output : 125 + 24 = 149 125 - 24 = 101 125 x 24 = 3000 125 / 24 = 5 125 mod 24 = 5
7. Write a Java program that takes a number as input and prints its multiplication table up to 10. Test Data: Input a number: 8 Expected Output : 8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 ... 8 x 10 = 80
8. Write a Java program to display the following pattern. Sample Pattern :
9. Write a Java program to compute the specified expressions and print the output. Test Data: ((25.5 * 3.5 - 3.5 * 3.5) / (40.5 - 4.5)) Expected Output 2.138888888888889
10. Write a Java program to compute a specified formula. Specified Formula : 4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11)) Expected Output 2.9760461760461765
11. Write a Java program to print the area and perimeter of a circle. Test Data: Radius = 7.5 Expected Output Perimeter is = 47.12388980384689 Area is = 176.71458676442586
12. Write a Java program that takes three numbers as input to calculate and print the average of the numbers. Click me to see the solution
13. Write a Java program to print the area and perimeter of a rectangle. Test Data: Width = 5.5 Height = 8.5
Expected Output Area is 5.6 * 8.5 = 47.60 Perimeter is 2 * (5.6 + 8.5) = 28.20
14. Write a Java program to print an American flag on the screen. Expected Output
15. Write a Java program to swap two variables. Click me to see the solution
16. Write a Java program to print a face. Expected Output
17. Write a Java program to add two binary numbers. Input Data: Input first binary number: 10 Input second binary number: 11 Expected Output
18. Write a Java program to multiply two binary numbers. Input Data: Input the first binary number: 10 Input the second binary number: 11 Expected Output
19. Write a Java program to convert an integer number to a binary number. Input Data: Input a Decimal Number : 5 Expected Output
20. Write a Java program to convert a decimal number to a hexadecimal number. Input Data: Input a decimal number: 15 Expected Output
21. Write a Java program to convert a decimal number to an octal number. Input Data: Input a Decimal Number: 15 Expected Output
22. Write a Java program to convert a binary number to a decimal number. Input Data: Input a binary number: 100 Expected Output
23. Write a Java program to convert a binary number to a hexadecimal number. Input Data: Input a Binary Number: 1101 Expected Output
24. Write a Java program to convert a binary number to an octal number. Input Data: Input a Binary Number: 111 Expected Output
25. Write a Java program to convert a octal number to a decimal number. Input Data: Input any octal number: 10 Expected Output
26. Write a Java program to convert a octal number to a binary number. Input Data: Input any octal number: 7 Expected Output
27. Write a Java program to convert a octal number to a hexadecimal number. Input Data: Input a octal number : 100 Expected Output
28. Write a Java program to convert a hexadecimal value into a decimal number. Input Data: Input a hexadecimal number: 25 Expected Output
29. Write a Java program to convert a hexadecimal number into a binary number. Input Data: Enter Hexadecimal Number : 37 Expected Output
30. Write a Java program to convert a hexadecimal value into an octal number. Input Data: Input a hexadecimal number: 40 Expected Output
31. Write a Java program to check whether Java is installed on your computer. Expected Output
32. Write a Java program to compare two numbers. Input Data: Input first integer: 25 Input second integer: 39 Expected Output
33. Write a Java program and compute the sum of an integer's digits. Input Data: Input an integer: 25 Expected Output
34. Write a Java program to compute hexagon area. Area of a hexagon = (6 * s^2)/(4*tan(π/6)) where s is the length of a side Input Data: Input the length of a side of the hexagon: 6 Expected Output
35. Write a Java program to compute the area of a polygon. Area of a polygon = (n*s^2)/(4*tan(π/n)) where n is n-sided polygon and s is the length of a side Input Data: Input the number of sides on the polygon: 7 Input the length of one of the sides: 6 Expected Output
36. Write a Java program to compute the distance between two points on the earth's surface. Distance between the two points [ (x1,y1) & (x2,y2)] d = radius * arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) Radius of the earth r = 6371.01 Kilometers Input Data: Input the latitude of coordinate 1: 25 Input the longitude of coordinate 1: 35 Input the latitude of coordinate 2: 35.5 Input the longitude of coordinate 2: 25.5 Expected Output
37. Write a Java program to reverse a string. Input Data: Input a string: The quick brown fox Expected Output
38. Write a Java program to count letters, spaces, numbers and other characters in an input string. Expected Output
39. Write a Java program to create and display a unique three-digit number using 1, 2, 3, 4. Also count how many three-digit numbers are there. Expected Output
40. Write a Java program to list the available character sets in charset objects. Expected Output
41. Write a Java program to print the ASCII value of a given character. Expected Output
42. Write a Java program to input and display your password. Expected Output
43. Write a Java program to print the following string in a specific format (see output). Sample Output
44. Write a Java program that accepts an integer (n) and computes the value of n+nn+nnn. Sample Output:
45. Write a Java program to find the size of a specified file. Sample Output:
46. Write a Java program to display system time. Sample Output:
47. Write a Java program to display the current date and time in a specific format. Sample Output:
48. Write a Java program to print odd numbers from 1 to 99. Prints one number per line. Sample Output:
49. Write a Java program to accept a number and check whether the number is even or not. Prints 1 if the number is even or 0 if odd. Sample Output:
50. Write a Java program to print numbers between 1 and 100 divisible by 3, 5 and both. Sample Output:
51. Write a Java program to convert a string to an integer. Sample Output:
52. Write a Java program to calculate the sum of two integers and return true if the sum is equal to a third integer. Sample Output:
53. Write a Java program that accepts three integers from the user. It returns true if the second number is higher than the first number and the third number is larger than the second number. If "abc" is true, the second number does not need to be larger than the first number. Sample Output:
54. Write a Java program that accepts three integers from the user and returns true if two or more of them (integers) have the same rightmost digit. The integers are non-negative. Sample Output:
55. Write a Java program to convert seconds to hours, minutes and seconds. Sample Output:
56. Write a Java program to find the number of values in a given range divisible by a given value. For example x = 5, y=20 and p =3, find the number of integers within the range x..y and that are divisible by p i.e. { i :x ≤ i ≤ y, i mod p = 0 } Sample Output:
57. Write a Java program to accept an integer and count the factors of the number. Sample Output:
58. Write a Java program to capitalize the first letter of each word in a sentence. Sample Output:
59. Write a Java program to convert a string into lowercase. Sample Output:
60. Write a Java program to find the penultimate (next to the last) word in a sentence. Sample Output:
61. Write a Java program to reverse a word. Sample Output:
62. Write a Java program that accepts three integer values and returns true if one is 20 or more less than the others' subtractions. Sample Output:
63. Write a Java program that accepts two integer values from the user and returns the largest value. However if the two values are the same, return 0 and find the smallest value if the two values have the same remainder when divided by 6. Sample Output:
64. Write a Java program that accepts two integer values between 25 and 75 and returns true if there is a common digit in both numbers. Sample Output:
65. Write a Java program to calculate the modules of two numbers without using any inbuilt modulus operator. Sample Output:
66. Write a Java program to compute the sum of the first 100 prime numbers. Sample Output:
67. Write a Java program to insert a word in the middle of another string. Insert "Tutorial" in the middle of "Python 3.0", so the result will be Python Tutorial 3.0. Sample Output:
68. Write a Java program to create another string of 4 copies of the last 3 characters of the original string. The original string length must be 3 and above. Sample Output:
70. Write a Java program to create a string in the form of short_string + long_string + short_string from two strings. The strings must not have the same length. Test Data: Str1 = Python Str2 = Tutorial Sample Output:
71. Write a Java program to create the concatenation of the two strings except removing the first character of each string. The length of the strings must be 1 and above. Test Data: Str1 = Python Str2 = Tutorial Sample Output:
72. Write a Java program to create a string taking the first three characters from a given string. If the string length is less than 3 use "#" as substitute characters. Test Data: Str1 = " " Sample Output:
73. Write a Java program to create a string taking the first and last characters from two given strings. If the length of each string is 0 use "#" for missing characters. Test Data: str1 = "Python" str2 = " " Sample Output:
74. Write a Java program to test if 10 appears as the first or last element of an array of integers. The array length must be broader than or equal to 2. Sample Output: Test Data: array = 10, -20, 0, 30, 40, 60, 10
75. Write a Java program to test if the first and last elements of an array of integers are the same. The array length must be broader than or equal to 2. Test Data: array = 50, -20, 0, 30, 40, 60, 10 Sample Output:
76. Write a Java program to test if the first and last element of two integer arrays are the same. The array length must be greater than or equal to 2. Test Data: array1 = 50, -20, 0, 30, 40, 60, 12 array2 = 45, 20, 10, 20, 30, 50, 11 Sample Output:
77. Write a Java program to create an array of length 2 from two integer arrays with three elements. The newly created array will contain the first and last elements from the two arrays. Test Data: array1 = 50, -20, 0 array2 = 5, -50, 10 Sample Output:
78. Write a Java program to test that a given array of integers of length 2 contains a 4 or a 7. Sample Output:
79. Write a Java program to rotate an array (length 3) of integers in the left direction. Sample Output:
80. Write a Java program to get the largest value between the first and last elements of an array (length 3) of integers. Sample Output:
81. Write a Java program to swap the first and last elements of an array (length must be at least 1) and create another array. Sample Output:
82. Write a Java program to find the largest element between the first, last, and middle values in an array of integers (even length). Sample Output:
83. Write a Java program to multiply the corresponding elements of two integer arrays. Sample Output:
84. Write a Java program to take the last three characters from a given string. It will add the three characters at both the front and back of the string. String length must be greater than three and more. Test data: "Python" will be "honPythonhon" Sample Output:
85. Write a Java program to check if a string starts with a specified word. Sample Data: string1 = "Hello how are you?" Sample Output:
88. Write a Java program to get the current system environment and system properties. Click me to see the solution
89. Write a Java program to check whether a security manager has already been established for the current application or not. Click me to see the solution
90. Write a Java program to get the value of environment variables PATH, TEMP, USERNAME. Click me to see the solution
91. Write a Java program to measure how long code executes in nanoseconds. Click me to see the solution
92. Write a Java program to count the number of even and odd elements in a given array of integers. Click me to see the solution
93. 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. Write a Java program to create an array (length # 0) of string values. The elements will contain "0", "1", "2" … through ... n-1. Click me to see the solution
96. Write a Java program to check if there is a 10 in an array of integers with a 20 somewhere later on. Click me to see the solution
97. Write a Java program to check if an array of integers contains a specified number next to each other or two same numbers separated by one element. Click me to see the solution
98. Write a Java program to check if the value 20 appears three times and no 20's are next to each other in the array of integers. Click me to see the solution
99. Write a Java program that checks if a specified number appears in every pair of adjacent integers of a given array of integers. Click me to see the solution
100. Write a Java program to count the elements that differ by 1 or less between two given arrays of integers with the same length. Click me to see the solution
101. Write a Java program to determine whether the number 10 in a given array of integers exceeds 20. Click me to see the solution
102. Write a Java program to check if a specified array of integers contains 10 or 30. Click me to see the solution
103. Write a Java program to create an array from a given array of integers. The newly created array will contain elements from the given array after the last element value is 10. Click me to see the solution
104. Write a Java program to create an array from a given array of integers. The newly created array will contain the elements from the given array before the last element value of 10. Click me to see the solution
105. Write a Java program to check if a group of numbers (l) at the start and end of a given array are the same. Click me to see the solution
106. Write a Java program to create an array left shifted from a given array of integers. Click me to see the solution
107. Write a Java program to check if an array of integers contains three increasing adjacent numbers. Click me to see the solution
108. Write a Java program to add all the digits of a given positive integer until the result has a single digit. Click me to see the solution
109. Write a Java program to form a staircase shape of n coins where every k-th row must have exactly k coins. Click me to see the solution
110. Write a Java program to check whether the given integer is a power of 4 or not. Given num = 64, return true. Given num = 6, return false. Click me to see the solution
111. Write a Java program to add two numbers without arithmetic operators. Given x = 10 and y = 12; result = 22 Click me to see the solution
112. Write a Java program to compute the number of trailing zeros in a factorial. 7! = 5040, therefore the output should be 1 Click me to see the solution
113. Write a Java program to merge two given sorted arrays of integers and create another sorted array. array1 = [1,2,3,4] array2 = [2,5,7, 8] result = [1,2,2,3,4,5,7,8] Click me to see the solution
114. Write a Java program that rotates a string by an offset (rotate from left to right. Click me to see the solution
115. Write a Java program to check if a positive number is a palindrome or not. Input a positive integer: 151 Is 151 is a palindrome number? true Click me to see the solution
116. Write a Java program that iterates integers from 1 to 100. For multiples of three print "Fizz" instead of the number and print "Buzz" for five. When the number is divided by three and five, print "fizz buzz". Click me to see the solution
117. Write a Java program to compute the square root of a given number. Input a positive integer: 25 Square root of 25 is: 5 Click me to see the solution
118. Write a Java program to get the first occurrence (Position starts from 0.) of a string within a given string. Click me to see the solution
119. Write a Java program to get the first occurrence (Position starts from 0.) of an element of a given array. Click me to see the solution
120. Write a Java program that searches for a value in an m x n matrix. Click me to see the solution
121. Write a Java program to reverse a linked list. Example: For linked list 20->40->60->80, the reversed linked list is 80->60->40->20 Click me to see the solution
122. Write a Java program to find a contiguous subarray with the largest sum from a given array of integers. Note: In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum. For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6. The subarray should contain one integer at least. Click me to see the solution
123. Write a Java program to find the subarray with smallest sum from a given array of integers. Click me to see the solution
124. Write a Java program to find the index of a value in a sorted array. If the value does not find return the index where it would be if it were inserted in order. Example: [1, 2, 4, 5, 6] 5(target) -> 3(index) [1, 2, 4, 5, 6] 0(target) -> 0(index) [1, 2, 4, 5, 6] 7(target) -> 5(index) Click me to see the solution
125. Write a Java program to get the preorder traversal of the values of the nodes in a binary tree. Example: 10 / \ 20 30 / \ 40 50 Expected output: 10 20 40 50 30 Click me to see the solution
126. Write a Java program to get the in-order traversal of its nodes' values in a binary tree. 10 / \ 20 30 / \ 40 50 Example:{10, 20, 30, 40, 50} Output: 40 20 50 10 30 Click me to see the solution
127. Write a Java program to get the Postorder traversal of its nodes' values in a binary tree. 10 / \ 20 30 / \ 40 50 Click me to see the solution
128. Write a Java program to calculate the median of a non-sorted array of integers. Original array: [10, 2, 38, 22, 38, 23] Median of the said array of integers: 30 Original array: [10, 2, 38, 23, 38, 23, 21] Median of the said array of integers: 23 Click me to see the solution
129. Write a Java program to find a number that appears only once in a given array of integers. All numbers occur twice. Source Array : [10, 20, 10, 20, 30, 40, 40, 30, 50] 50 appears only once Click me to see the solution
130. Write a Java program to find the maximum depth of a given binary tree. Sample Output: The Maximum depth of the binary tree is: 3 Click me to see the solution
131. Write a Java program to find the updated length of a sorted array where each element appears only once (remove duplicates). Original array: [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7] The length of the original array is: 11 After removing duplicates, the new length of the array is: 7 Click me to see the solution
132. Write a Java program to find the updated length of a given sorted array where duplicate elements appear at most twice. Original array: [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7, 7, 7] The length of the original array is: 13 After removing duplicates, the new length of the array is: 10 Click me to see the solution
133. Write a Java program to find a path from top left to bottom in the right direction which minimizes the sum of all numbers along its path. Note: Move either down or right at any point in time. Sample Output: Sum of all numbers along its path: 13 Click me to see the solution
134. Write a Java program to find distinct ways to climb to the top (n steps to reach the top) of stairs. Each time you climb, you can climb 1 or 2 steps. Example: n = 5 a) 1+1+1+1+1 = 5 b) 1+1+1+2 = 5 c) 1+2+2 = 5 d) 2+2+1 = 5 e) 2+1+1+1 = 5 f) 2+1+2 = 5 g) 1+2+1+1 = 5 h) 1+1+2+1 = 5 Sample Output: Distinct ways can you climb to the top: 8 Click me to see the solution
135. Write a Java program to remove duplicates from a sorted linked list. Original List with duplicate elements: 12->12->13->14->15->15->16->17->17 After removing duplicates from the said list: 12->13->14->15->16->17 Click me to see the solution
136. Write a Java program to find possible distinct paths from the top-left corner to the bottom-right corner of a given grid (m x n). Note: You can move either down or right at any point in time. Sample Output: Unique paths from top-left corner to bottom-right corner of the said grid: 3 Click me to see the solution
137. Write a Java program to find possible unique paths considering some obstacles, from top-left corner to bottom-right corner of a given grid (m x n). Note: You can move either down or right at any point in time and an obstacle and empty space is marked as 1 and 0 respectively in the grid. Sample grid: int[][] obstacle_Grid ={ {0, 0, 0}, {0, 1, 0}, {0, 0, 0}, }; Sample Output: Unique paths from top-left corner to bottom-right corner of the said grid (considering some obstacles): 2 Click me to see the solution
138. Write a Java program to find the longest words in a dictionary. Example-1: { "cat", "flag", "green", "country", "w3resource" } Result: "w3resource" Example-2: { "cat", "dog", "red", "is", "am" } Result: "cat", "dog", "red" Click me to see the solution
139. Write a Java program to get the index of the first and the last number of a subarray where the sum of numbers is zero. This is from a given array of integers. Original Array : [1, 2, 3, -6, 5, 4] Index of the subarray of the said array where the sum of numbers is zero: [0, 3] Click me to see the solution
140. Write a Java program to merge all overlapping intervals from a given collection of intervals. Sample Output: 1 6 8 10 15 20 Click me to see the solution
141. Write a Java program to check if a given string has all distinct characters. Sample Output: Original String : xyyz String has all unique characters: false Click me to see the solution
142. Write a Java program to check if two strings are anagrams or not. According to Wikipedia "An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram can be rearranged into nag a ram, or the word binary into brainy." Sample Output: String-1 : wxyz String-2 : zyxw Check if two given strings are anagrams or not?: true Click me to see the solution
143. Write a Java program to merge the two sorted linked lists. Sample Output: Merge Two Sorted ListsT: 1 2 3 7 9 13 40 Click me to see the solution
144. Write a Java program to remove all occurrences of a specified value in a given array of integers. Return the updated array length. Sample Output: Original array: [1, 4, 6, 7, 6, 2] The length of the new array is: 4 Click me to see the solution
145. Write a Java program to remove the nth element from the end of a given list. Sample Output: Original node: 1 2 3 4 5 After removing 2nd element from end: 1 2 3 5 Click me to see the solution
146. Write a Java program to convert an array of sorted items into a binary search tree. Maintain the minimal height of the tree. Sample Output: 2 1 4 6 5 3 Click me to see the solution
147. Write a Java program to find the number of bits required to flip to convert two given integers. Sample Output: 2 Click me to see the solution
148. Write a Java program to find the index of the first unique character in a given string. Assume that there is at least one unique character in the string. Sample Output: Original String: wresource First unique character of the above: 0 Click me to see the solution
149. Write a Java program to check if a given string is a permutation of another given string. Sample Output: Original strings: xxyz yxzx true Click me to see the solution
150. Write a Java program to test if a binary tree is a subtree of another binary tree. Sample Output: Original strings: xxyz yxzx true Click me to see the solution
Java Code Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
Follow us on Facebook and Twitter for latest update.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/index.php
- Weekly Trends and Language Statistics
Java Tutorial
Java methods, java classes, java file handling, java how to's, java reference, java examples, java exercises.
Test your Java skills with exercises from all categories:
Output Text
Output numbers, print variables, multiple variables, variable names, boolean types, type casting, string concatenation, strings and numbers, special characters, short hand if else, while loops, do while loops, nested loops, for-each loops, break and continue, arrays and loops, multidimensional arrays, method parameters, return values, method overloading, classes/objects, class attributes, class methods, constructors, encapsulation, inheritance, polymorphism, inner classes, abstraction, list sorting, wrapper classes, regular expressions, lambda expressions, advanced sorting, create and write to files, delete files, log in to track your progress.
If you haven't already, sign up to become a W3Schooler, and get points for every exercise you complete.
As a logged on W3Schools user you will have access to many features like having your own web page , track your learning progress , receive personal guided paths , and more .
The Exercise
The exercises are a mix of "multiple choice" and "fill in the blanks" questions. There are between 3 and 9 questions in each category. The answer can be found in the corresponding tutorial chapter. If you're stuck, or answer wrong, you can try again or hit the "Show Answer" button to see the correct answer.
Kickstart your career
Get certified by completing the course
COLOR PICKER
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.
- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Spring Boot
Java Tutorial
This Java Tutorial is designed for beginners as well as experienced professionals. Whether you’re starting your Java journey and looking to understand the basics of Java or its advanced concepts, this free Java tutorial is the perfect resource for you.
What is Java?
Developed by Sun Microsystems in 1995, Java is a highly popular, object-oriented programming language. This platform independent programming language is utilized for Android development, web development, artificial intelligence, cloud applications, and much more.
In this tutorial, we will cover everything from the basics of Java syntax to advanced topics like object-oriented programming and exception handling. So, by the end of this tutorial, you will have a strong understanding of Java and be ready to start writing your own Java applications. So let’s get started on this comprehensive Free Java programming Tutorial!
First Java Program
For full explanation of the above Program –
Table of Content
Overview of Java
Basics of java, input/output in java, flow control in java, operators in java, arrays in java, strings in java, oops in java, classes of java, interfaces in java, methods in java, packages in java, collection framework in java, collection classes in java, memory allocation in java, exception handling in java, multithreading in java, synchronization in java, file handling in java, java networking, java se 8 features, java date & time, java miscellaneous, interview questions on java, java practice problems, java jobs & opportunity, get started with free java tutorial.
Here in this section, you will find all the free resources that you need to become zero to mastery in the process of learning Java programming language .
As you get started with Java, it’s crucial to have a solid foundation in place. Concepts like data types, control flow, and functions are essential for any Java developer. To explore these topics more thoroughly, the Java Programming Course offers a great blend of theory and practical exercises to help solidify your understanding before moving on to advanced topics
- Introduction to Java
- History of Java
- Java vs C++ vs Python
- How to Download and Install Java?
- Setting Up the Environment in Java
- How to Download and Install Eclipse on Windows?
- Java Development Kit (JDK) in Java
- JVM and its architecture
- JDK Vs JRE Vs JVM
- Just In Time Compiler
- Byte Code Vs Machine Code
- Java Basic Syntax
- First Java Program (Hello World)
- Datatypes in Java
- Primitive Vs Non-Primitive Datatypes
- Java Identifiers
- Java Variables
- Java Keywords
- Scope of Variables
- Wrapper Classes in Java
- How to take Input from users in Java
- Scanner class in Java
- BufferedReader class in Java
- Scanner vs BufferedReader in Java
- Ways to Read Input from Console in Java
- Print Output in Java
- print() Vs println() in Java
- Formatted Outputs in Java
- Decision making in Java
- If Statement in Java
- If-Else Statement in java
- If-Else-If ladder in Java
- Loops in Java
- Do while loop
- For each loop
- Continue Statement in java
- Break Statement In Java
- Usage of Break in Java
- Return Statement in Java
- Arithmetic Operator
- Unary Operator
- Assignment Operator
- Relational Operator
- Logical Operator
- Ternary Operator
- Bitwise Operator
- Introduction to Arrays in Java
- Arrays class in Java
- Multi-Dimensional Array in Java
- How to declare and initialize 2D arrays in Java
- Jagged array in Java
- Final Arrays in Java
- Reflect Arrays in Java
- Java util.Arrays Vs reflect.Arrays
- Java Array Programs
- Introduction of Strings in Java
- String class in Java Set-1 | Set-2
- Why strings are immutable in Java?
- StringBuffer class in Java
- StringBuilder class in Java
- Strings vs StringBuffer vs StringBuilder in Java
- StringTokenizer class in Java Set-1 | Set-2
- StringJoiner in Java
- Java String Programs
OOPS in Java refers to Object-Oriented Programming concepts implemented in the Java programming language. Java’s OOP features include classes, objects, inheritance, polymorphism, and encapsulation, enabling modular and efficient code development. Understanding OOPS in Java is essential for building robust, scalable, and maintainable software applications.
- OOPS Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects
- Naming Convention in Java
- Access Modifiers in Java
- Constructors in Java
- Four pillars of OOPS in Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- This reference in Java
Classes in Java are the blueprint for creating objects and defining their properties and behaviors. They are the fundamental building blocks of Java programs, enabling the creation of reusable and modular code. Classes can contain fields, methods, constructors, and nested classes, providing a wide range of functionality and flexibility.
- Understanding classes and objects in Java
- Class vs interface
- Singleton class in java
- Object class in java
- Inner class in java
- Abstract classes in java
- Throwable class in java
Interfaces in Java are abstract types that define a set of methods that a class must implement. They provide a way to achieve abstraction, multiple inheritance, and loose coupling in Java programs. Interfaces are useful for defining common behaviors and functionalities that can be shared across different classes, leading to more modular and reusable code. Mastering interfaces in Java is crucial for building flexible and extensible software applications.
- Java Interfaces
- Interfaces and Inheritance in Java
- Class Vs Interface in Java
- Functional Interface
- Nested Interface
- Marker Interface
- Comparator Interface
- Introduction to methods in Java
- Different method calls in Java
- Static methods Vs Instance methods in Java
- Abstract methods in Java
- Method Overriding in Java
- Method Overloading in Java
- Method Overloading Vs Method Overriding
- Java Packages
- How to create a package in Java
- java.util package
- java.lang package
- java.io package
- Java Collection Framework
- Collections class in Java
- Collection Interface in Java
- List Interface in Java
- Queue Interface in Java
- Map Interface in Java
- Set Interface in Java
- SortedSet Interface in Java
- Deque Interface in Java
- Comparator in Java
- Comparator Vs Comparable in Java
- Iterator in Java
- ArrayList in Java
- Vector class in Java
- Stack class in Java
- LinkedList in Java
- Priority Queue in Java
- HashMap in Java
- LinkedHashMap in Java
- Dictionary in Java
- HashTable in Java
- HashSet in Java
- TreeSet in Java
- LinkedHashSet in Java
- Java Memory Management
- How are Java objects stored in memory
- Stack vs Heap memory allocation
- Types of memory areas allocated by JVM
- Garbage Collection in Java
- Heap and Stack memory allocation
- Types of JVM Garbage Collectors in Java
- Memory leaks in Java
- Java Virtual Machine(JVM) Stack Area
- Exceptions in java
- Types of Exceptions
- Checked Vs Unchecked Exceptions
- Try, Catch, Finally, throw, and throws
- Flow control in Try catch block
- Throw vs Throws
- Final vs Finally vs Finalize
- User-defined custom exception
- Chained Exceptions
- Null pointer Exceptions
- Exception handling with method Overriding
- Introduction to Multithreading in Java
- Lifecycle and Stages of a Thread
- Thread Priority in Java
- Main Thread in Java
- Thread class
- Runnable interface
- How to name a thread
- start() method in thread
- run() vs start() Method in Java
- sleep() method
- Daemon thread
- Thread Pool in Java
- Thread Group in Java
- Thread Safety in Java
- ShutdownHook
- Multithreading Tutorial
- Java Synchronization
- Importance of Thread synchronization in Java
- Method and Block Synchronization in Java
- Local frameworks vs thread synchronization
- Atomic Vs Volatile in Java
- Atomic Vs Synchronized in Java
- Deadlock in Multithreading
- Deadlock Prevention and Avoidance
- Lock Vs Monitor in Concurrency
- Reentrant Lock
- File Class in java
- How to create files in java
- How to read files in java
- How to write on files in java
- How to delete a file in java
- File Permissions
- File Writer
- FileDescriptor class
- RandomAccessFile class
- Introduction to Java Regex
- How to write Regex expressions
- Matcher class
- Pattern class
- Quantifiers
- Character class
- Introduction to Java IO
- Reader Class
- Writer Class
- FileInput stream
- File Output stream
- BufferedReader Input Stream
- BufferedReader Output stream
- BufferedReader vs Scanner
- Fast I/O in Java
- Introduction to Java Networking
- TCP architecture
- UDP architecture
- IPV4 Vs IPV6
- Connection-oriented Vs connectionless protocols
- Socket programming in Java
- Server Socket class
- URL class and methods
- Lambda Expressions
- Streams API
- New Date/Time API
- Default Methods
- Functional Interfaces
- Method references
- Optional class
- Stream Filter
- Type Annotations
- String Joiner
- Date Class in Java
- Methods of the Date class
- Java Current Date and time
- Compare dates in Java
- Introduction to Java JDBC
- JDBC Driver
- JDBC Connection
- Types of Statements in JDBC
- JDBC Tutorial
- Introduction to Reflection API
- Java IO Tutorial
- JavaFX Tutorial
- How to Run Java RMI application?
- Java 17 New Features
- Core Java Interview Questions
- Java Multiple Choice Questions
Features of Java
- Java has been one of the most popular programming languages for many years.
- Java is Object Oriented. However, it is not considered as pure object-oriented as it provides support for primitive data types (like int, char, etc)
- The Java codes are first compiled into byte code (machine-independent code). Then the byte code runs on Java Virtual Machine (JVM) regardless of the underlying architecture.
- Java syntax is similar to C/C++. But Java does not provide low-level programming functionalities like pointers. Also, Java codes are always written in the form of classes and objects.
- Java is used in all kinds of applications like Mobile Applications (Android is Java-based), desktop applications, web applications, client-server applications, enterprise applications, and many more.
- When compared with C++, Java codes are generally more maintainable because Java does not allow many things which may lead to bad/inefficient programming if used incorrectly. For example, non-primitives are always references in Java. So we cannot pass large objects (like we can do in C++) to functions, we always pass references in Java. One more example, since there are no pointers, bad memory access is also not possible.
- When compared with Python, Java kind of fits between C++ and Python. The programs are written in Java typically run faster than corresponding Python programs and slower than C++. Like C++, Java does static type checking, but Python does not.
Applications of Java
Here in this section, we have added some of the applications that were developed using the Java programming language.
- Mobile Applications
- Desktop GUI Applications
- Artificial intelligence
- Scientific Applications
- Cloud Applications
- Embedded Systems
- Gaming Applications
Keep up your pace and try hard till you excel in it. This will need some motivation and resources to Practice Java. So, there are few resources mentioned below this will help you in your journey:
Java Interview Questions and Answers Java Programming Examples Java Exercises – Basic to Advanced Java Practice Programs with Solutions Java Language MCQs with Answers Java Practice Quiz
According to report of Statista.com Java is most demanded programming languages after JavaScript by recruiters worldwide in 2024. Major MNC companies are recruiting Java Programmers.
- Deloitte India
- Many more…
Java Latest & Upcoming Features
Java SE 21 Released: September 2023 Java SE 21 is the latest stable release, featuring:
- Hidden Classes (Preview): Introduces a mechanism to restrict access to specific members of a class, enhancing modularity and code maintainability.
- Improved Garbage Collector Ergonomics (JEP 429): Simplifies configuration and monitoring of the garbage collection process.
- API Updates : Enhancements to existing APIs, including java.io.file for better file handling capabilities.
Java SE 22 Released: March 19, 2024 Java SE 22 introduces:
- Foreign Function & Memory API (JEP 454): Enhances interoperability with native code.
- Unnamed Variables & Patterns (JEP 456): Adds support for unnamed variables and patterns.
- Structured Concurrency (JEP 462, Second Preview): Simplifies multithreaded programming by structuring concurrency.
- String Templates (JEP 459, Second Preview): Provides a new syntax for creating and manipulating strings.
- Vector API (JEP 460, Seventh Incubator): Offers a portable and low-level abstraction for SIMD programming.
Upcoming Features (Expected in Java SE 23 – September 2024)
- Vector API (Incubator): A new API designed for high-performance vector computations, potentially beneficial for scientific computing and machine learning applications.
- Project Panama (Preview): Aims to improve interoperability between Java and native code, simplifying interactions with non-Java libraries and frameworks.
Trends in Java Development:
- Java continues to prioritize features that enhance application performance and developer experience.
- Java’s strong position in cloud environments is expected to hold as cloud computing remains a dominant trend.
- Java’s suitability for building scalable and modular systems aligns well with the popularity of microservices architectures.
- Expect to see Java evolving to integrate more seamlessly with technologies like artificial intelligence, big data, and the Internet of Things (IoT).
Java Programming Tutorial: FAQs
Why use java .
Java is simple to understand programming language because doesn’t contain concepts like : Pointers and operator overloading and it is secure and portable.
What are the major concepts in Java?
There are 4 major concept in Java that is abstraction, encapsulation, polymorphism, and inheritance. Along with this Java also works with three OOPs concept
How Java different to C++ ?
C++ | JAVA |
---|---|
C++ is platform dependent. | Java is platform independent. |
C++ uses compiler only. | Java uses compiler and interpreter both. |
C++ support pointers and operator overloading. | Java doesn’t support pointers and operator overloading concept. |
C++ not support multithreading concept. | Java supports multithreading concept. |
Why Java is so popular programming language?
Java is based on object model hence it is one the popular programming language.
What are the scope of Java Technologies for Web Applications?
Java Technologies for Web Applications are a set of Java-based technologies that are used to develop web applications. These technologies include: Java Servlet API JavaServer Pages JavaServer Faces Enterprise JavaBeans JDBC (Java Database Connectivity) Java Messaging Service (JMS): JavaMail API: JAX-WS
Check More Resources Related to Java Programming
Similar reads, please login to comment....
- Free Music Recording Software in 2024: Top Picks for Windows, Mac, and Linux
- Best Free Music Maker Software in 2024
- What is Quantum AI? The Future of Computing and Artificial Intelligence Explained
- Noel Tata: Ratan Tata's Brother Named as a new Chairman of Tata Trusts
- GeeksforGeeks Practice - Leading Online Coding Platform
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Java Coding 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
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.
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:
- C Program To Count The Total Number Of Notes In A Amount | C Programs
- C Program To Check If Vowel Or Consonant | 4 Simple Ways
- C Program To Check Whether A Number Is Even Or Odd | C Programs
- C Program To Print Number Of Days In A Month | Java Tutoring
- C Program To Find Maximum Between Three Numbers | C Programs
- C Program To Check If Alphabet, Digit or Special Character | C Programs
- C Program To Input Any Alphabet And Check Whether It Is Vowel Or Consonant
- C Program To Check Character Is Uppercase or Lowercase | C Programs
- C Program To Check A Number Is Negative, Positive Or Zero | C Programs
- C Program To Find Reverse Of An Array – 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 Calculate Profit or Loss In 2 Ways | C Programs
- C Program To Check Whether A Year Is Leap Year Or Not | C Programs
- C Program Area Of Triangle | 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
- Mirrored Rhombus Star Pattern Program In c | Patterns
- C Program Hollow Diamond Star Pattern | C Programs
- X Star Pattern C Program 3 Simple Ways | C Star Patterns
- C Program To Find Area Of Semi Circle | C Programs
- C Program To Find Volume of Sphere | C Programs
- C Program Area Of Isosceles Triangle | C Programs
- C Program Area Of Trapezium – 3 Ways | C Programs
- C Program Area Of Rhombus – 4 Ways | C Programs
- C Program Area Of Rectangle | C Programs
- C Program Check A Character Is Upper Case Or Lower Case
- C Program Area Of Parallelogram | C Programs
- C Program Area Of Square | C Programs
- Hollow Rhombus Star Pattern Program In C | Patterns
- C Program To Calculate Volume Of Cube | C Programs
- C Program to find the Area Of a Circle
- C Program Area Of Equilateral Triangle | 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 Rectangle | C Programs
- C Program To Calculate Perimeter Of Rhombus | C Programs
- C Program Volume Of Cuboid | C Programs
- C Program To Calculate Perimeter Of Square | C Programs
- C Program To Left Rotate An Array | C Programs
- C Program Count Number Of Words In A String | 4 Ways
- C Program To Search All Occurrences Of A Character In String | 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 Program To Copy All Elements From An Array | C Programs
- C Mirrored Right Triangle Star Pattern Program – Pattern Programs
- C Program To Toggle Case Of Character Of A String | C Programs
- C Square Star Pattern Program – C Pattern Programs | C Programs
- C Program To Compare Two Strings – 3 Easy Ways | C Programs
- C Program Volume Of Cylinder | C Programs
- C Program To Delete An Element From An Array At Specified Position | C Programs
- C Program To Search All Occurrences Of A Word In String | C Programs
- C Program To Find Reverse Of A string | 4 Ways
- Hollow Square Pattern Program in C | C Programs
- C Program To Reverse Words In A String | C Programs
- C Program Inverted Right Triangle Star Pattern – Pattern Programs
- Rhombus Star Pattern Program In C | 4 Multiple Ways
- C Programs – 500+ Simple & Basic Programming Examples & Outputs
- C Program To Count Frequency Of Each Character In String | C Programs
- C Plus Star Pattern Program – Pattern Programs | C
- C Program To Remove Last Occurrence Of A Character From String
- C Program To Find Maximum & Minimum Element In Array | C Prorams
- C Program To Search An Element In An Array | C Programs
- C Program Replace First Occurrence Of A Character With Another String
- C Program To Trim Leading & Trailing White Space Characters From String
- C Program Right Triangle Star Pattern | Pattern Programs
- Merge Two Arrays To Third Array C Program | 4 Ways
- C Program Replace All Occurrences Of A Character With Another In String
- C Program To Copy One String To Another String | 4 Simple Ways
- C Program To Find Last Occurrence Of A Word In A String | C Programs
- C Program To Trim Trailing White Space Characters From String | C Programs
- C Pyramid Star Pattern Program – Pattern Programs | C
- C Program Number Of Alphabets, Digits & Special Character In String | Programs
- C Program Count Number Of Vowels & Consonants In A String | 4 Ways
- Highest Frequency Character In A String C Program | 4 Ways
- C Program To Convert Lowercase String To Uppercase | 4 Ways
- C Program To Trim White Space Characters From String | C Programs
- C Program To Count Number Of Even & Odd Elements In Array | C Programs
- C Program To Sort Array Elements In Ascending Order | 4 Ways
- C Program To Find Last Occurrence Of A Character In A Given String
- C Program To Concatenate Two Strings | 4 Simple Ways
- C Program To Remove Repeated Characters From String | 4 Ways
- C Program To Remove Blank Spaces From String | C Programs
- C Program To Count Frequency Of Each Element In Array | C Programs
- C Program To Find First Occurrence Of A Word In String | C Programs
- C Program To Put Even And Odd Elements Of Array Into Two Separate Arrays
- C Program To Remove First Occurrence Of A Word From String | 4 Ways
- C Program To Sort Even And Odd Elements Of Array | C Programs
- C Program To Print Number Of Days In A Month | 5 Ways
- C Program To Count Occurrences Of A Character In String | C Programs
- C Program To Check A String Is Palindrome Or Not | C Programs
- C Program To Print All Unique Elements In The Array | C Programs
- C Program Find Maximum Between Two Numbers | C Programs
- C Program To Convert Uppercase String To Lowercase | 4 Ways
- C Program Hollow Inverted Mirrored Right Triangle
- C Program To Input Week Number And Print Week Day | 2 Ways
- C Program To Replace Last Occurrence Of A Character In String | C Programs
- C Program Hollow Mirrored Rhombus Star Pattern | C Programs
- C Program Hollow Inverted Right Triangle Star Pattern
- C Program To Insert Element In An Array At Specified Position
- Diamond Star Pattern C Program – 4 Ways | C Patterns
- C Program To Find Sum Of All Array Elements | 4 Simple Ways
- C Program Count Number of Duplicate Elements in An Array | C Programs
- C Program To Sort Array Elements In Descending Order | 3 Ways
- C Program Hollow Mirrored Right Triangle Star Pattern
- C Program To Find Lowest Frequency Character In A String | C Programs
- C Program Half Diamond Star Pattern | C Pattern Programs
- C Program To Remove All Occurrences Of A Character From String | C Programs
- C Program To Read & Print Elements Of Array | C Programs
- C Program To Right Rotate An Array | 4 Ways
- C Program To Find First Occurrence Of A Character In A String
- C Program To Count Number Of Negative Elements In Array
- C Program To Print All Negative Elements In An Array
- 8 Star Pattern – C Program | 4 Multiple Ways
- Hollow Inverted Pyramid Star Pattern Program in C
- Right Arrow Star Pattern Program In C | 4 Ways
- C Program : Check if Two Strings Are Anagram or Not
- C Program To Find Length Of A String | 4 Simple Ways
- C Program : Check if Two Arrays Are the Same or Not | C Programs
- C Program Hollow Right Triangle Star Pattern
- C Program : Capitalize First & Last Letter of A String | C Programs
- Left Arrow Star Pattern Program in C | C Programs
- C Program Inverted Mirrored Right Triangle Star Pattern
- C Program Mirrored Half Diamond Star Pattern | C Patterns
- Hollow Pyramid Star Pattern Program in C
- 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 Lower Triangular Matrix or Not | C Programs
- C Program : Convert An Array Into a Zig-Zag Fashion
- C Program Merge Two Sorted Arrays – 3 Ways | C Programs
- C Program : To Reverse the Elements of An Array | C Programs
- C Program : Minimum Scalar Product of Two Vectors | C Programs
- C Program : Check If Arrays are Disjoint or Not | C Programs
- C Program Transpose of a Matrix 2 Ways | C Programs
- C Program : Maximum Scalar Product of Two Vectors
- C Program : Find Missing Elements of a Range – 2 Ways | C Programs
- C program : Find Median of Two Sorted Arrays | 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 : To Find Maximum Element in A Row | C Programs
- C Program : Check if An Array Is a Subset of Another Array
- C Program : Non-Repeating Elements of An Array | C Programs
- 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 Sum of Each Row and Column of A Matrix | C Programs
- C Program : Sorting a String in Alphabetical Order – 2 Ways
- C Program : Remove All Characters in String Except Alphabets
- C Program : Remove Vowels from A String | 2 Ways
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 October 17, 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 !
Java Program To Display Transpose Matrix | 3 Ways
October 19, 2024
Merge Sort Java – Program 2 Ways | Sortings
Java mirrored right triangle star pattern programs | patterns, java program to add two matrices – 4 ways | programs, java inverted mirrored right triangle star pattern, gcd of two numbers in java – programs | 5 ways.
Insertion Sort Java Algorithm – 2 Ways | Java Sortings
Implement Insertion Sort Algorithm In Java – We will discuss the various methods to Implement ...
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- AI assistance for guided coding help
- Projects to apply new skills
- Quizzes to test your knowledge
- A certificate of completion
Skill level
Time to complete
Prerequisites
About this course
Popular for its versatility and ability to create a wide variety of applications, learning Java opens up your possibilities when coding. With it, you’ll be able to develop large systems, software, and mobile applications — and even create mobile apps for Android. Learn important Java coding fundamentals and practice your new skills with real-world projects.
Skills you'll gain
Build core programming concepts
Learn object-oriented concepts
Create Java projects
Hello World
Welcome to the world of Java programming! Java is a popular object-oriented programming language that is used in many different industries.
Learn about datatypes in Java and how we use them. Then, practice your skills with two projects where you create and manipulate variables.
Object-Oriented Java
Learn about object-oriented programming in Java. Explore syntax for defining classes and creating instances.
Conditionals and Control Flow
Conditionals and control flow in Java programs.
Arrays and ArrayLists
Build lists of data with Java arrays and ArrayLists.
Use loops to iterate through lists and repeat code.
String Methods
The Java String class provides a lot of useful methods for performing operations on strings and data manipulation.
Certificate of completion available with Plus or Pro
The platform
Hands-on learning
Projects in this course
Planting a tree, java variables: mad libs, earn a certificate of completion.
- Show proof Receive a certificate that demonstrates you've completed a course or path.
- Build a collection The more courses and paths you complete, the more certificates you collect.
- Share with your network Easily add certificates of completion to your LinkedIn profile to share your accomplishments.
Learn Java course ratings and reviews
- 5 stars 59%
- 4 stars 28%
Our learners work at
- Google Logo
- Amazon Logo
- Microsoft Logo
- Reddit Logo
- Spotify Logo
- YouTube Logo
- Instagram Logo
Frequently asked questions about Java
What is java.
Java is an open-source, general-purpose programming language known for its versatility and stability. It’s used for everything from building websites to operating systems and wearable devices. You can even find Java in outer space, running the Mars rover.
What does Java do?
What kind of jobs can java get me, are java and javascript the same, what do i need to know before learning java, join over 50 million learners and start learn java today, looking for something else, related resources, java and the command line, java program structure, java style guide, related courses and paths, study for the ap computer science a exam (java), intro to java, java for programmers, browse more topics.
- Cloud Computing 2,246,361 learners enrolled
- For Business 3,254,013 learners enrolled
- Mobile Development 1,315,970 learners enrolled
- Code Foundations 7,266,622 learners enrolled
- Computer Science 5,720,962 learners enrolled
- Java 1,173,850 learners enrolled
- Web Development 4,862,819 learners enrolled
- Data Science 4,378,623 learners enrolled
- Python 3,537,348 learners enrolled
Unlock additional features with a paid plan
Practice projects, assessments, certificate of completion.
IMAGES
VIDEO
COMMENTS
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 the solution.
Enhance Java Skills with this Java exercises with detailed solutions for programming proficiency. This Java practice programs ranging from basic to advanced levels questions.
Practice with solution of exercises on Java basic: examples on variables, date, operator, input, output and more from w3resource.
Exercises. Test your Java skills with exercises from all categories: Syntax. Output Text. Output Numbers. Comments. Variables. Print Variables. Multiple Variables. Variable Names. Data Types. Numbers. Boolean Types. Characters. Type Casting. Operators. Strings. String Concatenation. Strings and Numbers. Special Characters. Math. Booleans. If Else.
The 100 days of Java plan have been carefully divided into stages which are thoughtfully designed to give an all-round practical approach to mastering Java Language. This structured framework ensures comprehensive coverage and application from basics to advanced techniques. Detailed Phase Breakdown: Table of Content. Days 1-5: Introduction to Java.
This Java Tutorial is designed for beginners as well as experienced professionals. Whether you’re starting your Java journey and looking to understand the basics of Java or its advanced concepts, this free Java tutorial is the perfect resource for you. What is Java?
This is a free set of tasks for your Java practice by CodeGym. If you’re a beginner, you can start learning the basics and get immediate feedback on your progress. If you’re a seasoned learner, it will help you estimate your current level of knowledge with additional Java challenges.
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.
Learn the Java programming language in this complete beginner's course. You will learn all the main features of Java (version 17) and how to use Java for you...
1. Hello World. Welcome to the world of Java programming! Java is a popular object-oriented programming language that is used in many different industries. 2. Variables. Learn about datatypes in Java and how we use them.