publicclassMain{ publicstaticvoidmain(String[] args){ // using the sqrt() method System.out.print("Square root of 4 is: " + Math.sqrt(4)); } } // Square root of 4 is: 2.0
用户自定义方法
我们还可以创建自己选择的方法来执行某些任务。这种方法称为用户定义方法。
自定义方法例子:
1 2 3
publicstaticvoidmyMethod(){ System.out.println("My Function called"); }
method body - 它包括用于执行某些任务的编程语句。The method body is enclosed inside the curly braces { }.
执行方法
Java中执行方法很简单:方法名+(parameters).
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classMain{ publicstaticvoidmain(String[] args){ System.out.println("About to encounter a method.");
// method call myMethod();
System.out.println("Method was executed successfully!"); }
// method definition privatestaticvoidmyMethod(){ System.out.println("Printing from inside myMethod()!"); } } // 输出 // About to encounter a method. // Printing from inside myMethod(). // Method was executed successfully!
带返回值例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSquareMain{ publicstaticvoidmain(String[] args){ int result;
// call the method and store returned value result = square(); System.out.println("Squared value of 10 is: " + result); }
publicstaticintsquare(){ // return statement return10 * 10; } } // 输出 // Squared value of 10 is: 100
带参数并且有返回值的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassMain{ publicstaticvoidmain(String[] args){ int result, n; n = 3; result = square(n); System.out.println("Square of 3 is: " + result); n = 4; result = square(n); System.out.println("Square of 4 is: " + result); }
// method staticintsquare(int i){ return i * i; } }
// constructor privateMain(){ System.out.println("Constructor Called"); x = 5; }
publicstaticvoidmain(String[] args){ // constructor is called while creating object Main obj = new Main(); System.out.println("Value of x = " + obj.x); } } // 输出 // Constructor Called // Value of x = 5
构造函数类型
在Java中构造函数有3种类型:
无参数构造函数
默认构造函数
参数化构造函数
无参数构造函数
如果构造函数没有参数则称为无参数构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classCompany{ String domainName;
// public constructor publicCompany(){ domainName = "programiz.com"; } }
// create a string String type = "java programming";
在Java中通过""表示字符串.
⚠️所有字符串都是 String类的实例.
String 方法
方法名
描述
concat()
将两个字符串连接起来
equals()
比较两个字符串的值
charAt()
返回字符串指定的字符
getBytes()
将字符串转换成字节数组
indexOf()
返回字符串中指定字符的位置
length()
返回指定字符串的大小
replace()
将指定的旧字符串替换为指定的新字符
substring()
返回字符串的子字符串
split()
将字符串分成字符串数组
toLowerCase()
将字符串转成小写
toUpperCase()
将字符串转成大写
valueOf()
返回指定数据的字符串表示形式
获取字符串长度
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classMain{ publicstaticvoidmain(String[] args){
// create a string String greet = "Hello! World"; System.out.println("The string is: " + greet);
//checks the string length System.out.println("The length of the string: " + greet.length()); } } // 输出 // The string is: Hello! World // The length of the string: 12
String name = "World"; System.out.println("Second String: " + name);
// join two strings String joinedString = greet.concat(name); System.out.println("Joined String: " + joinedString); } } // 输出 // First String: Hello! // Second String: World // Joined String: Hello! World
// create strings String first = "java programming"; String second = "java programming"; String third = "python programming";
// compare first and second strings boolean result1 = first.equals(second); System.out.println("Strings first and second are equal: " + result1);
//compare first and third strings boolean result2 = first.equals(third); System.out.println("Strings first and third are equal: " + result2); } } // 输出 // Strings first and second are equal: true // Strings first and third are equal: false
equals()方法比较两个字符串
也可以用==操作符和compareTo()方法比较两个字符串
获取一个字符串的字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classMain{ publicstaticvoidmain(String[] args){
// create string using the string literal String greet = "Hello! World"; System.out.println("The string is: " + greet);
// returns the character at 3 System.out.println("The character at 3: " + greet.charAt(3));
// returns the character at 7 System.out.println("The character at 7: " + greet.charAt(7)); } } // 输出 // The string is: Hello! World // The character at 3: l // The character at 7: W
// create string using the new keyword String example = new String("Hello! World");
// returns the substring World System.out.println("Using the subString(): " + example.substring(7));
// converts the string to lowercase System.out.println("Using the toLowerCase(): " + example.toLowerCase());
// converts the string to uppercase System.out.println("Using the toUpperCase(): " + example.toUpperCase());
// replaces the character '!' with 'o' System.out.println("Using the replace(): " + example.replace('!', 'o')); } } // 输出 // Using the subString(): World // Using the toLowerCase(): hello! world // Using the toUpperCase(): HELLO! WORLD // Using the replace(): Helloo World
字符串是不可变的
Java中字符串如果创建成功则不能进行修改.将两个字符串合并的操作其实是内存中创建新的字符串.
1 2 3 4
// create a string String example = "Hello"; // adds another string to the string example = example.concat(" World");
上面👆代码的实际在内存中的执行步骤是:
在JVM内存创建字符串”Hello”
将创建的”Hello”引用给变量example
在”Hello”后面添加” World”.
JVM在内存创建新的字符串”Hello World”
将变量引用新创建的字符串”Hello World”.
原来的字符串”Hello”并没有被修改
用 new关键字创建字符串
Java中可以用new String()创建字符串.
1 2
// create a string using the new keyword String name = new String("java string");
importpackage.name.ClassName; // To import a certain class only importpackage.name.* // To import the whole package import java.util.Date; // imports only Date class import java.io.*; // imports everything inside java.io package
publicstaticvoidmain( String[] args ){ // creating object of Complex class // calls the constructor with 2 parameters Complex c1 = new Complex(2, 3); // calls the constructor with a single parameter Complex c2 = new Complex(3);
// calls the constructor with no parameters Complex c3 = new Complex();
classThisExample{ // declare variables int x; int y;
ThisExample(int x, int y) { // assign values of variables inside constructor this.x = x; this.y = y;
// value of x and y before calling add() System.out.println("Before passing this to addTwo() method:"); System.out.println("x = " + this.x + ", y = " + this.y);
// call the add() method passing this as argument add(this);
// value of x and y after calling add() System.out.println("After passing this to addTwo() method:"); System.out.println("x = " + this.x + ", y = " + this.y); }
classMain{ publicstaticvoidmain(String[] args){ String name = "Programiz"; Integer age = 22;
System.out.println("Is name an instance of String: "+ (name instanceof String)); System.out.println("Is age an instance of Integer: "+ (age instanceof Integer)); } }
输出:
1 2
Is name an instance of String: true Is age an instance of Integer: true
// Dog class is a subclass of Animal classDogextendsAnimal{ }
classMain{ publicstaticvoidmain(String[] args){ Dog d1 = new Dog();
// checks if d1 is an object of Dog System.out.println("Is d1 an instance of Dog: "+ (d1 instanceof Dog)); // checks if d1 is an object of Animal System.out.println("Is d1 an instance of Animal: "+ (d1 instanceof Animal)); } }
输出:
1 2
Is d1 is an instance of Dog: true Is d1 an instance of Animal: true
classCat{ } classMain{ publicstaticvoidmain(String[] args){ Dog d1 = new Dog(); Animal a1 = new Animal(); Cat c1 = new Cat();
System.out.println("Is d1 an instance of the Object class: "+ (d1 instanceof Object)); System.out.println("Is a1 an instance of the Object class: "+ (a1 instanceof Object)); System.out.println("Is c1 an instance of the Object class: "+ (c1 instanceof Object)); } }
输出:
1 2 3
Is d1 an instance of the Object class: true Isa1aninstanceoftheObjectclass: true Isc1aninstanceoftheObjectclass: true
Object向上转换和向下转换
在Java中,子类的对象可以视为超类的对象。这称为向上转换。Java编译器自动执行向上转换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classAnimal{ publicvoiddisplayInfo(){ System.out.println("I am an animal."); } }
classDogextendsAnimal{ }
classMain{ publicstaticvoidmain(String[] args){ Dog d1 = new Dog(); Animal a1 = d1; a1.displayInfo(); } }
publicvoideat(){ System.out.println("I can eat"); }
publicvoidsleep(){ System.out.println("I can sleep"); }
public String getColor(){ return color; }
publicvoidsetColor(String col){ color = col; } }
classDogextendsAnimal{ publicvoiddisplayInfo(String c){ System.out.println("I am a " + type); System.out.println("My color is " + c); } publicvoidbark(){ System.out.println("I can bark"); } }
classMain{ publicstaticvoidmain(String[] args){
Dog dog1 = new Dog(); dog1.eat(); dog1.sleep(); dog1.bark(); dog1.type = "mammal"; dog1.setColor("black"); dog1.displayInfo(dog1.getColor()); } }
输出:
1 2 3 4 5
I can eat I can sleep I can bark I am a mammal My color is black
// create an interface interfacePolygon{ voidgetArea(int length, int breadth); }
// implement the Polygon interface classRectangleimplementsPolygon{
// implementation of abstract method publicvoidgetArea(int length, int breadth){ System.out.println("The area of the rectangle is " + (length * breadth)); } }
classMain{ publicstaticvoidmain(String[] args){ // create an object Rectangle r1 = new Rectangle(); r1.getArea(5, 6); } } // 输出 // The area of the rectangle is 30
**注意:**一个类可以实现多个接口
1 2 3 4 5 6 7 8 9 10 11 12
interfaceA{ // members of A }
interfaceB{ // members of B }
classCimplementsA, B{ // abstract members of A // abstract members of B }
扩展接口
与类相似,接口可以扩展其他接口。 extend关键字用于扩展接口。
1 2 3 4 5 6 7 8 9
interfaceLine{ // members of Line interface }
// extending interface interfacePolygonextendsLine{ // members of Polygon interface // members of Line interface }
// default method defaultvoidgetSides(){ System.out.println("I can get sides of a polygon."); } }
// implements the interface classRectangleimplementsPolygon{ publicvoidgetArea(){ int length = 6; int breadth = 5; int area = length * breadth; System.out.println("The area of the rectangle is " + area); }
// overrides the getSides() publicvoidgetSides(){ System.out.println("I have 4 sides."); } }
// implements the interface classSquareimplementsPolygon{ publicvoidgetArea(){ int length = 5; int area = length * length; System.out.println("The area of the square is " + area); } }
classMain{ publicstaticvoidmain(String[] args){
// create an object of Rectangle Rectangle r1 = new Rectangle(); r1.getArea(); r1.getSides();
// create an object of Square Square s1 = new Square(); s1.getArea(); s1.getSides(); } }
// 输出 // The area of the rectangle is 30 // I have 4 sides. // The area of the square is 25 // I can get sides of a polygon.
// To use the sqrt function import java.lang.Math;
interfacePolygon{ voidgetArea(); // calculate the perimeter of a Polygon defaultvoidgetPerimeter(int... sides){ int perimeter = 0; for (int side: sides) { perimeter += side; }
classTriangleimplementsPolygon{ privateint a, b, c; privatedouble s, area;
// initializing sides of a triangle Triangle(int a, int b, int c) { this.a = a; this.b = b; this.c = c; s = 0; }
// calculate the area of a triangle publicvoidgetArea(){ s = (double) (a + b + c)/2; area = Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.println("Area: " + area); } }
classMain{ publicstaticvoidmain(String[] args){ Triangle t1 = new Triangle(2, 3, 4);
// calls the method of the Triangle class t1.getArea();
// calls the method of Polygon t1.getPerimeter(2, 3, 4); } }
// create an object of Java class Java j1 = new Java(); j1.displayInfo();
// create an object of Language class Language l1 = new Language(); l1.displayInfo(); } } // 输出 // Java Programming Language // Common English Language
// create an object of the outer class Car Car car1 = new Car("Mazda", "8WD");
// create an object of inner class using the outer class Car.Engine engine = car1.new Engine(); engine.setEngine(); System.out.println("Engine Type for 8WD= " + engine.getEngineType());
Car car2 = new Car("Crysler", "4WD"); Car.Engine c2engine = car2.new Engine(); c2engine.setEngine(); System.out.println("Engine Type for 4WD = " + c2engine.getEngineType()); } } // 输出 // Engine Type for 8WD= Bigger // Engine Type for 4WD = Smaller
// create an object of the static nested class // using the name of the outer class MotherBoard.USB usb = new MotherBoard.USB(); System.out.println("Total Ports = " + usb.getTotalPorts()); } } // 输出 // Total Ports = 3
// static nested class staticclassUSB{ int usb2 = 2; int usb3 = 1; intgetTotalPorts(){ // accessing the variable model of the outer classs if(MotherBoard.this.model.equals("MSI")) { return4; } else { return usb2 + usb3; } } } } publicclassMain{ publicstaticvoidmain(String[] args){
// create an object of the static nested class MotherBoard.USB usb = new MotherBoard.USB(); System.out.println("Total Ports = " + usb.getTotalPorts()); } } // 输出 // error: non-static variable this cannot be referenced from a static context
classPolygon{ publicvoiddisplay(){ System.out.println("Inside the Polygon class"); } }
classAnonymousDemo{ publicvoidcreateClass(){
// creation of anonymous class extending class Polygon Polygon p1 = new Polygon() { publicvoiddisplay(){ System.out.println("Inside an anonymous class."); } }; p1.display(); } }
classMain{ publicstaticvoidmain(String[] args){ AnonymousDemo an = new AnonymousDemo(); an.createClass(); } } // 输出 // Inside an anonymous class.
classTest{ Size pizzaSize; publicTest(Size pizzaSize){ this.pizzaSize = pizzaSize; } publicvoidorderPizza(){ switch(pizzaSize) { case SMALL: System.out.println("I ordered a small size pizza."); break; case MEDIUM: System.out.println("I ordered a medium size pizza."); break; default: System.out.println("I don't know which one to order."); break; } } }
classMain{ publicstaticvoidmain(String[] args){ Test t1 = new Test(Size.MEDIUM); t1.orderPizza(); } } // 输出 // I ordered a medium size pizza.
// this will refer to the object SMALL switch(this) { case SMALL: return"small";
case MEDIUM: return"medium";
case LARGE: return"large";
case EXTRALARGE: return"extra large";
default: returnnull; } }
publicstaticvoidmain(String[] args){
// call getSize() // using the object SMALL System.out.println("The size of the pizza is " + Size.SMALL.getSize()); } } // 输出 // The size of the pizza is small
// enum constants calling the enum constructors SMALL("The size is small."), MEDIUM("The size is medium."), LARGE("The size is large."), EXTRALARGE("The size is extra large.");
classReflectionDemo{ publicstaticvoidmain(String[] args){ try { // create an object of Dog class Dog d1 = new Dog();
// create an object of Class using getClass() Class obj = d1.getClass(); // find the interfaces implemented by Dog Class[] objInterface = obj.getInterfaces(); for(Class c : objInterface) {
// print the name of interfaces System.out.println("Interface Name: " + c.getName()); } }
classReflectionDemo{ publicstaticvoidmain(String[] args){ try{ Dog d1 = new Dog(); // create an object of the class Class Class obj = d1.getClass();
// manipulating the public field type of Dog Field field1 = obj.getField("type"); // set the value of field field1.set(d1, "labrador"); // get the value of field by converting in String String typeValue = (String)field1.get(d1); System.out.println("type: " + typeValue);
// get the access modifier of type int mod1 = field1.getModifiers(); String modifier1 = Modifier.toString(mod1); System.out.println("Modifier: " + modifier1); System.out.println(" "); } catch(Exception e) { e.printStackTrace(); } } }
classReflectionDemo{ publicstaticvoidmain(String[] args){ try { Dog d1 = new Dog(); // create an object of the class Class Class obj = d1.getClass();
// accessing the private field Field field2 = obj.getDeclaredField("color"); // making the private field accessible field2.setAccessible(true); // set the value of color field2.set(d1, "brown"); // get the value of type converting in String String colorValue = (String)field2.get(d1); System.out.println("color: " + colorValue);
// get the access modifier of color int mod2 = field2.getModifiers(); String modifier2 = Modifier.toString(mod2); System.out.println("modifier: " + modifier2); } catch(Exception e) { e.printStackTrace(); } } }
classReflectionDemo{ publicstaticvoidmain(String[] args){ try { Dog d1 = new Dog();
// create an object of Class Class obj = d1.getClass(); // get all the methods using the getDeclaredMethod() Method[] methods = obj.getDeclaredMethods();
// get the name of methods for(Method m : methods) { System.out.println("Method Name: " + m.getName()); // get the access modifier of methods int modifier = m.getModifiers(); System.out.println("Modifier: " + Modifier.toString(modifier)); // get the return types of method System.out.println("Return Types: " + m.getReturnType()); System.out.println(" "); } } catch(Exception e) { e.printStackTrace(); } } }
输出
1 2 3 4 5 6 7 8 9 10 11
Method Name: display Modifier: public Return type: void
classReflectionDemo{ publicstaticvoidmain(String[] args){ try { Dog d1 = new Dog(); Class obj = d1.getClass();
// get all the constructors in a class using getDeclaredConstructor() Constructor[] constructors = obj.getDeclaredConstructors();
for(Constructor c : constructors) { // get names of constructors System.out.println("Constructor Name: " + c.getName());
// get access modifier of constructors int modifier = c.getModifiers(); System.out.println("Modifier: " + Modifier.toString(modifier));
// get the number of parameters in constructors System.out.println("Parameters: " + c.getParameterCount()); } } catch(Exception e) { e.printStackTrace(); } } }
输出
1 2 3 4 5 6 7 8 9 10 11
Constructor Name: Dog Modifier: public Parameters: 0
Constructor Name: Dog Modifier: public Parameters: 1
Constructor Name: Dog Modifier: private Parameters: 2