Simple codes in java

Simple Java Programs for Beginners Example

Simple Java Programs for Beginners Example: If you’re looking to get into coding, learning Java is a great place to start. It’s a stable and popular programming language that can be used in many different industries. And once you know how to code in Java, it becomes easier to reuse that code for other purposes.

In this article, we will explore some of the Simple Java Programs for understanding the fundamentals of basic Java programming. Java is a versatile language that can be used for building a variety of applications. In order to code in Java, everything must be contained within a class. Once you have created your class, you can save it with a .java extension.

Coding-related questions are common in interviews, so it is beneficial to have a strong foundation in the basics of Java programming. In order to increase your coding skills or knowledge, you can check this Simple Java Program for Beginners with Examples and output.

Post Type: Java Programs For Beginners
Published On: www.softwaretestingo.com
Applicable For: Freshers & Experience
Get Updates: Join Our Telegram Group

Simple Java Programs for Beginners

How to Write Text File Using Jautva Selenium With Example Program?

package com.selenium.mix; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteTextFile < public static void main(String[] args) throws IOException < // TODO Auto-generated method stub File f=new File("G:\\Git_Base_Folder\\softwaretestingblog\\Selenium\\src\\com\\selenium\\mix\\Selenium Text"); FileWriter fw=new FileWriter(f); BufferedWriter bw=new BufferedWriter(fw); bw.write("Welcome to My Testing Blof"); bw.newLine(); bw.write("www.softwareteastingblog.in"); bw.close(); >>

Write a Program To Find out Parent Reference Implementation.

package com.java.Softwaretestingblog; class ab < public void a() < System.out.println("Inside Method A"); >> public class ParentReference extends ab < public void a() < System.out.println("Inside Overriding Method A"); >public void b() < System.out.println("Inside Method B"); >@SuppressWarnings("unused") public static void main(String[] args) < //ab obj=new ab(); //obj.a(); ab abc=new ParentReference(); abc.a(); ParentReference abx=new ParentReference(); //abx.a(); //abx.b(); //ParentReference aby=new ab(); >>

Execution: The Parent Reference Final output link

Inside Overriding Method A

How to Remove Spaces From Sentence In Java With Example?

package com.java.Softwaretestingblog; public class RemoveSpaceInASentence < public static void main(String[] args) < // Remove Spaces Java Program String str = "For More Testing Interview Questions Visit Software Testing Blog "; System.out.println("Entered String:- "+str); //1. Using replaceAll() Method String strWithoutSpace = str.replaceAll("\\s", ""); System.out.println("Remove Space With Using Replaceall Method:- "+strWithoutSpace); //Output : ForMoreTestingInterviewQuestionsVisitSoftwareTestingBlog //2. Without Using replaceAll() Method char[] strArray = str.toCharArray(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < strArray.length; i++) < if( (strArray[i] != ' ') && (strArray[i] != '\t') ) < sb.append(strArray[i]); >> System.out.println("After Remove The Space From The Sentence:- "+sb); //Output : CoreJavajspservletsjdbcstrutshibernatespring > >
Entered String:- For More Testing Interview Questions Visit Software Testing Blog Remove Space With Using Replaceall Method:- ForMoreTestingInterviewQuestionsVisitSoftwareTestingBlog After Remove The Space From The Sentence:- ForMoreTestingInterviewQuestionsVisitSoftwareTestingBlog

Write a Program to Find out Widening In Java Example Program?

package com.java.Softwaretestingblog; public class WideningExample < public static void main(String[] args) < // TODO Auto-generated method stub //Conversion lower ro higher is called wideining //byte->short->int->float->long->double int i = 100; //automatic type conversion long l = i; //automatic type conversion float f = l; System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); > >
Int value 100 Long value 100 Float value 100.0

Non-Repeated & First Repeated Character Using HashMap

How to Find First Repeated & Non-Repeated Character In Java?

package com.softwaretestingblog.programs; import java.util.HashMap; import java.util.Scanner; public class Non_Repeated_Character < static void firstRepeatedNonRepeatedChar(String inputString) < //Creating a HashMap containing char as a key and occurrences as a value HashMapcharCountMap = new HashMap(); //Converting inputString to char array char[] strArray = inputString.toCharArray(); //Checking each char of strArray for (char c : strArray) < if(charCountMap.containsKey(c)) < //If char is present in charCountMap, incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c)+1); >else < //If char is not present in charCountMap, //adding this char in charCountMap with 1 as it's value charCountMap.put(c, 1); >> //checking for first non-repeated character for (char c : strArray) < if (charCountMap.get(c) == 1) < System.out.println("First Non-Repeated Character In '"+inputString+"' is '"+c+"'"); break; >> //checking for first repeated character for (char c : strArray) < if (charCountMap.get(c) >1) < System.out.println("First Repeated Character In '"+inputString+"' is '"+c+"'"); break; >> > public static void main(String[] args) < @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); System.out.println("Enter the string :"); String input = sc.next(); firstRepeatedNonRepeatedChar(input); >>

Differential Object Java Program

Simple Java Program Object With Example?

package com.java.Softwaretestingblog; class top < int b=20; void m1() < System.out.println("Inside Super Class"); >> public class DifferentialObject < public static void main(String[] args) < // TODO Auto-generated method stub new top(); new top().b=30; //System.out.println(b); //Differential Objects Can't be Outside top obj=new top(); obj.b=30; System.out.println("The Value Of B:- "+obj.b); >>

How to Find Pair Elements In an Array In Java With Example Program?

package com.softwaretestingblog.programs; public class PairOfElementsInArray < static void findThePairs(int inputArray[], int inputNumber) < System.out.println("Pairs of elements whose sum is "+inputNumber+" are : "); for (int i = 0; i < inputArray.length; i++) < for (int j = i+1; j < inputArray.length; j++) < if(inputArray[i]+inputArray[j] == inputNumber) < System.out.println(inputArray[i]+" + "+inputArray[j]+" EnlighterJSRAW" data-enlighter-language="null" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Pairs of elements whose sum is 10 are : 4 + 6 = 10 5 + 5 = 10 -10 + 20 = 10

Write a Program to Find Distinct Element Using POJO [Getter & Setter] Class Java?

package com.java.Softwaretestingblog; import java.util.HashSet; public class FindDistinctElement < public static void main(String[] args) < // TODO Auto-generated method stub HashSetlhm = new HashSet(); lhm.add(new Price("Banana", 20)); lhm.add(new Price("Apple", 40)); lhm.add(new Price("Orange", 30)); for(Price pr:lhm) < System.out.println(pr); >Price duplicate = new Price("Banana", 20); System.out.println("inserting duplicate object. "); lhm.add(duplicate); System.out.println("After insertion:"); for(Price pr:lhm) < System.out.println(pr); >> > class Price < private String item; private int price; public Price(String itm, int pr)< this.item = itm; this.price = pr; >public int hashCode() < System.out.println("In hashcode"); int hashcode = 0; hashcode = price*20; hashcode += item.hashCode(); return hashcode; >public boolean equals(Object obj) < System.out.println("In equals"); if (obj instanceof Price) < Price pp = (Price) obj; return (pp.item.equals(this.item) && pp.price == this.price); >else < return false; >> public String getItem() < return item; >public void setItem(String item) < this.item = item; >public int getPrice() < return price; >public void setPrice(int price) < this.price = price; >public String toString() < return "item: "+item+" price: "+price; >>
In hashcode In hashcode In hashcode item: Apple price: 40 item: Orange price: 30 item: Banana price: 20 inserting duplicate object. In hashcode In equals After insertion: item: Apple price: 40 item: Orange price: 30 item: Banana price: 20

Write a Program to Find Out Sum Of Digits In Java Program?

package com.java.Softwaretestingblog; import java.util.Scanner; public class SumOfDigits < public static void main(String[] args) < // TODO Auto-generated method stub Scanner in=new Scanner(System.in); System.out.println("Enter the number"); int sum=0,n,a; n=in.nextInt(); while(n>0) < a=n%10; n=n/10; sum=sum+a; >System.out.println("Sum of digits EnlighterJSRAW" data-enlighter-language="null" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Enter the number: 1254 Sum of digits=12

How To Open Exe Files In Java Example Program?

package com.java.interviewFAQ; import java.io.IOException; public class RunExeFiles < public static void main(String[] args) throws IOException < Runtime.getRuntime().exec("C:\\Windows\\notepad.exe"); >>

This Java interview questions and answers tutorial will help you crack your next Java interview. We’ve covered Simple Java Programs questions and answers that are frequently asked by interviewer. With this guide, you’ll be ready to tackle any question thrown your way.

Читайте также:  Комментарий

If you’re struggling with these java programs, please leave a comment below. In addition to this article on Simple Java Programs for Beginners, if you come across any other interview questions, please let us know in the comment section and we’ll update the article accordingly.

Источник

Simple codes in java

Various Java programs to illustrate various concepts

  • A Hello World! Java program.
  • Calling Methods. A sample of how to call methods in the same class.
  • For loop. A simple example of using for loops to calculate factorial. Uses the built in int data type so only good to 13!
  • Enhanced for loop
  • Value Parameters: An example that shows the behavior of value parameters. In Java all parameters are passed by value.
  • String Example. A few brief examples of String manipulations.
  • BinaryConverter. A program with examples of various Java syntax that converts a base 10 int to base 2 String.
  • PrimeEx A program with various approaches to determine if an int is prime or not. Used to demonstrate Java syntax. You need the Stopwatch class, a non standard Java class, as well.
  • Pointers as Value parameters
  • Array Examples
  • 2D array Example. A simplified version of filtering a picture represented by ints.
  • 2D array example. Very simple version of the Conway’s Game of Life.
  • Getting input from Keyboard with Scanner class
  • Reading ints from file with Scanner class
  • Writing ints to file
  • Connecting to and reading from a web page.
  • Program to create ASCII frequency table from file and url. Demonstration of try / catch blocks. The CIA 2008 Factbook may be downloaded from Project Gutenberg.
  • IntListVer1 First version of the IntList class developed in class. Developing class to illustrate various class design and implementation issues in Java.
  • IntListTesterVer1
  • IntListVer2 Added default add method, equals method, and toString methods. Includes versions of toString using String concatenation and StringBuffer to illustarte performance differences.
  • IntListTesterVer2
  • IntListVer3. Added insert and remove methods.
  • SortedIntList. Inherits from InListVer3 to create a SortedIntList. Class is «broken» because random insertions still allowed.
  • GenericList. Altered the list to store anything, not just ints.
  • Die class. A class that models a playing die.
  • DemoClass: This illustrates some of the more confusing concepts in class syntax and mechanics such as constructors, static vs. instance methods, and method overloading.
  • Stopwatch class. A class for measuring how long it takes for a program to run.
    • Documentation for Stopwatch class.

    Источник

    Java for Beginners – How to Create Your First «Hello World» Program

    Md. Fahim Bin Amin

    Md. Fahim Bin Amin

    Java for Beginners – How to Create Your First

    If you are learning a programming language, the first thing you do is print something in the terminal/command prompt.

    And that first thing is likely printing «Hello World» in the terminal. So that’s what I’ll show you how to do here if you are learning Java for the first time.

    🫵 What You Need to Know First

    Before you start writing Java code, there are a few things you should know.

    First of all, Java source files have the extension .java . An extension is something that is appended at the end of the file name, and it indicates which type of file it really is.

    Different programming languages have different file extensions which help the compilers/interpreters identify which type of programming data the file contains. These extensions also help identify whether that specific compiler/interpreter can support that file format or not.

    Second, you have to ensure that you have properly installed the Java compiler (JDK) on your computer. If you do not know anything about that, then simply check out this article (if you are a Windows user).

    Also, when we compile the Java source code ( .java file), it generates a .class file. Later we run the .class file. Since Java is a platform-independent language (which means you can run the Java program from any operating system if you have installed the necessary components there), you can simply run this .class file from any operating system you want!

    You can use any text editors / IDEs you want. But I prefer Visual Studio Code or IntelliJ IDEA IDE.

    And finally, the Java file name and the public class name should be identical.

    ✍️ How to Create Your First Java File

    Now you’ll learn how to create a Java file. In this example, I am going to create a file named Main.java .

    You can write the following code in that file:

    Then simply run the code. If you use the Code Runner extension to run this code using VS Code, it will compile the code first and then create the Main.class file. Later it will run the Main.class file.

    As it does this automatically, you almost won’t see any time delays. But if you want to become a better programmer and run the code from your terminal, then make sure to check out this article.

    😉 Code Explanation

    In the code above, we used the public class, and the public class name needs to be identical to the .java filename. If you used a different file name, then the public class name will also need to be different.

    For example, if you are using MyJavaFile.java , then the public class would be like this: public class MyJavaFile . Java is a case-sensitive language, so make sure to check that the uppercase-lowercase letters are also identical.

    Then we need the main method. The Java compiler always starts compiling from the main method. The main method is public static void main(String[] args) .

    For printing something in the terminal, we use the print method. Here the print method is System.out.println(«») . You have to provide the thing that you want to print in the terminal in the double quotations.

    We use the semicolon ( ; ) to specify the end of a statement. So we use the semicolon after each statement’s end.

    There you go! I’ll discuss more tweaks and advanced cool topics in other articles. 😁

    📹 Video Walkthrough

    If you’re the type of person who enjoys learning from videos, then I have also created a video just for you! Make sure to check it out:

    Hello World in Java video

    Also, I am putting together a playlist where I am publishing all Java-related content. Make sure to check the playlist from here and get all the code from this GitHub repository.

    😀 Conclusion

    Thanks for reading this entire article. I hope this helps you get started on your Java programming journey.

    If you want to support me, then you can also buy me a coffee!

    Источник

Оцените статью