Java que
Created By: chatGPT
Java is a versatile programming language that enables developers to create a wide range of applications. It is object-oriented, platform-independent, and has a rich API that makes development easier. Here's a simple example to get you started.
In this code, we define a class named HelloWorld. The main method is the entry point for any Java application. When you run this code, it will print Hello, World! to the console.public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Java also supports the concept of variables. You can declare variables to store data. Here's how you can declare and use different types of variables in Java.
In this example, we declare three variables: an integer for age, a double for salary, and a String for name. The public class VariablesDemo {
public static void main(String[] args) {
int age = 25;
double salary = 55000.50;
String name = "John Doe";
System.out.println(name + " is " + age + " years old and earns " + salary);
}
}
System.out.println
method is used to output the concatenated message.Java also provides powerful control flow statements which include if, else, and for loops. Here’s an example using an if statement to check if a number is even or odd.
In this code, we use the modulus operator public class EvenOdd {
public static void main(String[] args) {
int number = 10;
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
%
to determine if the number is even or odd. If the result of number % 2
is zero, it indicates that the number is even, otherwise, it is odd.For iterating over a collection of items or a range of numbers, you can use a for loop. Here’s an example that prints numbers from 1 to 5.
This for loop initializes public class ForLoopDemo {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
i
to 1 and continues to increment it until it reaches 5. Each iteration prints the current value of i
to the console.Lastly, understand the importance of methods. Methods encapsulate code for reuse and better organization. Here’s how you can define and call a method in Java.
In this example, we define a method called greet that takes a String parameter and prints a greeting message. The method is called in the main method, passing the argument Alice.public class MethodDemo {
public static void main(String[] args) {
greet("Alice");
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
}