Access Modifier: Myclass (Main ( Args) (System - Out.Println ) )
Access Modifier: Myclass (Main ( Args) (System - Out.Println ) )
Public -It is an Access Modifier, which defines who can access this Method. Public means that this Method
will be accessible by any Class (If other Classes can access this Class.).
Static -Static is a keyword which identifies the class related thing. It means the given Method or variable is
not instance related but Class related. It can be accessed without creating the instance of a Class.
Void -Is used to define the Return Type of the Method. It defines what the method can return. Void means
the Method will not return any value.
Main- Main is the name of the Method. This Method name is searched by JVM as a starting point for an
application with a particular signature only.
String args[] / String… args - It is the parameter to the main Method. Argument name could be anything.
Program2 :
Program 3:
Program 4:
System.out.println(fullName);
Program5:
String x = "10";
int y = 20;
String z = x + y;
System.out.println(z);
import java.util.Arrays;
Result
The above code sample will produce the following result.
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
Encapsulation
. To achieve Encapsulation, you must:
declare class variables/attributes as private (only accessible within the same class)
provide public setter and getter methods to access and update the value of a private variable
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable,
with the first letter in upper case:
Example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
The set method takes a parameter (newName) and assigns it to the name variable. The this
keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this
class:
Example
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}
If the variable was declared as public, we would expect the following output:
John
Instead, we use the getName() and setName() methods to acccess and update the variable:
Example
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}
// Outputs "John"