Chapter 3- Introduction to Strings



A string is a sequence of characters. A string is instantiated as follows:

String name;
name = new String(“Aryadeep”);
package com.company;

public class strings {
public static void main(String[] args) {
String name=new String("Aryadeep"); // you can also write as, String name="Aryadeep";
System.out.println(name);

}
}

/*
Aryadeep
*/

String is a class but can be used as a data type.
Strings are immutable and cannot be changed.

String name="Aryadeep"
(Here, name is a reference, and “Aryadeep” is an object.)


Different ways to print in Java

We can use the following ways to print in Java:
  • System.out.print() // No newline at the end
  • System.out.println() // Prints a new line at the end
  • System.out.printf()
  • System.out.format()
System.out.printf("%c",ch)

  %d for int
  %f for float
  %c for char
  %s for string


Code as written in the video
package com.company;
import java.util.Scanner;

public class cwh_13_strings {
public static void main(String[] args) {
// String name = new String("Harry");
// String name = "Harry";
// System.out.print("The name is: ");
// System.out.print(name);
int a = 6;
float b = 5.6454f;
System.out.printf("The value of a is %d and value of b is %8.2f", a, b);
//System.out.format("The value of a is %d and value of b is %f", a, b);
Scanner sc = new Scanner(System.in);
// String st = sc.next();
// String st = sc.nextLine();
// System.out.println(st);

}
}




Aryadeep

Welcome to CodeWithARYA. It's My Personal Reference Website. Where You Can Get Amazing Codes. Have a Look.

Post a Comment

Previous Post Next Post