In Java, instances of a class are known as objects. Every object has state and behavior in the form of instance fields and methods respectively.
public class Person { // state of an object int age; String name; // behavior of an object public void set_value() { age = 20; name = "Robin"; } public void get_value() { System.out.println("Age is " + age); System.out.println("Name is " + name); } // main method public static void main(String [] args) { // creates a new Person object Person p = new Person(); // changes state through behavior p.set_value(); } }
Java instances are objects that are based on classes. For example, Bob may be an instance of the class Person.
public class Person { int age; String name; // Constructor method public Person(int age, String name) { this.age = age; this.name = name; } public static void main(String[] args) { Person Bob = new Person(31, "Bob"); Person Alice = new Person(27, "Alice"); } }
Every instance has access to its own set of variables which are known as instance fields. Values for instance fields are assigned within the constructor method.
public class Person { int age; public static void main(String [] args) { Person p = new Person(); // use dot notation to set age p.age = 20; // use dot notation to access age and print System.out.println("Age is " + p.age); // Output: Age is 20 } }
In Java, a constructor is a special method used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
public class Maths { public Maths() { System.out.println("I am constructor"); } public static void main(String [] args) { System.out.println("I am main"); Maths obj1 = new Maths(); } }
In Java, a new class instance is created using the `new` keyword followed by a call to the class constructor. This allocates memory for the object and returns a reference to it.
public class Person { int age; // Constructor: public Person(int a) { age = a; } public static void main(String [] args) { // Create a new instance of the Person class: Person p = new Person(20); System.out.println("Age is " + p.age); // Prints: Age is 20 } }
Reference data types use the structure instanceOrClassName.fieldOrMethodName.
public class Cat { public Cat() { // instructions for creating a Cat instance } public static void main(String[] args) { // garfield is declared with reference data type `Cat` Cat garfield = new Cat(); System.out.println(garfield); // Prints: Cat@76ed5528 } }
Java classes contain a constructor method which is used to create instances of the class.
// The signature is `Cat(String furLength, boolean hasClaws)`. public class Cat { String furType; boolean containsClaws; public Cat(String furLength, boolean hasClaws) { furType = furLength; containsClaws = hasClaws; } public static void main(String[] args) { Cat garfield = new Cat("Long-hair", true); } }
The constructor is named after the class. If no constructor is defined, a default empty constructor is used.
public class Bear { String species; public Bear(String speciesOfBear) { species = speciesOfBear; } public static void main(String[] args) { Bear baloo = new Bear("Sloth bear"); System.out.println(baloo); // Prints: Bear@4517d9a3 // set object to null baloo = null; System.out.println(baloo); // Prints: null } }
The body of a Java method contains the statements that define what the method does. It is enclosed in curly braces `{}` and follows the method declaration.
public class Maths { public static void sum(int a, int b) { // Start of sum int result = a + b; System.out.println("Sum is " + result); } // End of sum public static void main(String [] args) { // Here, we call the sum method sum(10, 20); // Output: Sum is 30 } }
The constructor can be used to provide initial values to instance fields.
public class Maths { public int sum(int a, int b) { int k = a + b; return k; } public static void main(String [] args) { Maths m = new Maths(); int result = m.sum(10, 20); System.out.println("sum is " + result); // prints - sum is 30 } }
A variable with a reference data type has a value that references the memory address of an instance. During variable declaration, the class name is used as the variable’s type.
//For example, `i` and `j` variables are available in the `main` method only: public class Maths { public static void main(String [] args) { int i, j; System.out.println("These two variables are available in main method only"); } }
A class can contain multiple constructors as long as they have different parameter values. A signature helps the compiler differentiate between the different constructors.
public class Maths { // return type is int public int sum(int a, int b) { int k; k = a + b; // sum is returned using the return keyword return k; } public static void main(String [] args) { Maths m = new Maths(); int result; result = m.sum(10, 20); System.out.println("Sum is " + result); // Output: Sum is 30 } }
A method signature is made up of the method’s name and a list of its parameters.
// Here is a public method named sum whose return type is int and has two int parameters a and b public int sum(int a, int b) { return(a + b); }
Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double.
// These are all examples of autoboxing Double wrapper1 = 23.456; Integer wrapper2 = 3; Double wrapper3 = new Double(13.57); Integer wrapper4 = new Integer(7); Double wrapper5 = Double.valueOf(30.59); Integer wrapper6 = Integer.valueOf(15);
Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double.
int num1 = wrapper2; // Unbox by calling the intValue method: int num2 = wrapper2.intValue(); // Auto unboxing: int num3 = wrapper1;
The `Integer` class and `Double` class in Java are wrapper classes for the primitive types `int` and `double`, respectively. You can convert an `Integer` to a `double` using the `doubleValue()` method.
Integer intObj = 100; double doubleValue = intObj.doubleValue(); System.out.println(doubleValue); // Output: 100.0
The Math.random() method generates a random double number between 0.0 and 1.0.
System.out.println("Random number: " + Math.random());
To convert a String to an int value, use the parseInt method.
String numStr = "1234"; int num = Integer.parseInt(numStr); System.out.println(num); // Output: 1234
To convert a String to a double value, use the parseDouble method.
String str = "123.45"; double num = Double.parseDouble(str); System.out.println(num); // Output: 123.45
Java’s Math class contains methods for performing basic numeric operations such as exponentiation, logarithms, square roots, and trigonometric functions.
System.out.println("Square root of 9 is " + Math.sqrt(9)); // Output: Square root of 9 is 3.0
The String class represents a sequence of characters.
String str = "Hello, World!"; System.out.println(str.length()); // Output: 13
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!