In programming, variables are used to store data values. In JavaScript, you can declare variables using the keywords `var`, `let`, or `const`.
import java.io.*;
class Main{
public static void main(String args[])
{
String name = "John"; // Declare a variable with a string
double age = 30; // Declare a constant with a number
String city = "New York"; // Declare a variable with var
System.out.println("Name : "+name+"\nAge : "+age+"\nCity : "+city);
}
}
A function is a block of code designed to perform a particular task. Functions are defined using the `function` keyword in JavaScript.
import java.io.*;
public class Greet {
public static String greet(String name) {
return "Hello, " + name + "!";
}
public static void main(String[] args) {
System.out.println(greet("Alice")); // Output: Hello, Alice!
}
}
Conditionals allow you to execute code based on whether a condition is true or false. In JavaScript, `if`, `else if`, and `else` are used.
import java.io.*;
public class AgeCheck {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
}
}
Loops are used to execute a block of code multiple times. The `for` and `while` loops are commonly used in JavaScript.
import java.io.*;
public class NumberPrinter {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i); // Prints numbers from 0 to 4
}
}
}
Arrays are used to store multiple values in a single variable. In JavaScript, arrays are defined using square brackets `[]`.
import java.io.*;
public class FruitArray {
public static void main(String[] args) {
// Declare and initialize the array
String[] fruits = {"Apple", "Banana", "Cherry"};
// Access and print elements from the array
System.out.println(fruits[0]); // Output: Apple
System.out.println(fruits[1]); // Output: Banana
}
}
Objects are used to store collections of data in key-value pairs. In JavaScript, objects are defined using curly braces `{}`.
import java.io.*;
public class Person {
// Define the properties
String name;
int age;
String city;
// Constructor to initialize the properties
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
public static void main(String[] args) {
// Create a Person object and initialize it with values
Person person = new Person("John", 30, "New York");
// Access the property and print it
System.out.println(person.name); // Output: John
}
}