National Day and Mid-Autumn Festival Special (6) 30 Common Treasure Programming Interview Questions for College Students

Insert image description here

The following are 30 common programming interview questions and answers for college students' Java interviews, including complete codes:

  1. What is main method in Java?
    Answer: The main method is the entry point of a Java program. It is a special method and does not need to be declared. When the Java runtime system executes a Java program, it first runs the main method. The main method should have the following signature: public static void main(String[] args).
  2. How to create a new object in Java?
    Answer: In Java, you can use the keyword "new" to create a new object. For example, to create a new object named "myObject", you would use the following code:
MyClass myObject = new MyClass();  
  1. What is a constructor in Java?
    Answer: A constructor is a special method used to create and initialize objects. It has the same name as the class and has no return type. Java automatically calls constructors when creating new objects of a class.
class MyClass {
    
      
   int a;
   MyClass() {
    
      
       a = 10;  
   }  
}
  1. How to access properties of a class in Java?
    Answer: In Java, you can access the properties of a class using the dot (.) operator. For example, if a class has attributes name and age, they can be accessed like this:
MyClass obj = new MyClass();  
obj.name = "John";  
obj.age = 30;  
  1. What are access modifiers in Java?
    Answer: Access modifiers are modifiers used to restrict other classes from accessing members (properties and methods) in a class. There are four access modifiers in Java: public, protected, default (that is, no modifiers) and private.
// public  
public class PublicClass {
    
      
   public int publicProperty = 10;
   public void publicMethod() {
    
      
       System.out.println("This is a public method.");  
   }  
}
// protected  
protected class ProtectedClass {
    
      
   protected int protectedProperty = 20;
   protected void protectedMethod() {
    
      
       System.out.println("This is a protected method.");  
   }  
}
// default (no modifier)  
class DefaultClass {
    
      
   int defaultProperty = 30;
   void defaultMethod() {
    
      
       System.out.println("This is a default method.");  
   }  
}
// private  
class PrivateClass {
    
      
   private int privateProperty = 40;
   private void privateMethod() {
    
      
       System.out.println("This is a private method.");  
   }  
}
  1. How to implement singleton pattern in Java?
    Answer: The singleton pattern is a design pattern that ensures that a class has only one instance. You can use the lazy style (thread-safe) and the hungry style (thread-unsafe) to implement the singleton pattern.
// 懒汉式 (线程安全)  
class Singleton {
    
      
   private static Singleton instance;
   private Singleton() {
    
      
       // private constructor to prevent instantiation  
   }
   public static synchronized Singleton getInstance() {
    
      
       if (instance == null) {
    
      
           instance = new Singleton();  
       }  
       return instance;  
   }  
}
// 饿汉式 (线程不安全)  
class Singleton {
    
      
   private static final Singleton instance = new Singleton();
   private Singleton() {
    
      
       // private constructor to prevent instantiation  
   }
   public static Singleton getInstance() {
    
      
       return instance;  
   }  
}
  1. What are static variables and static methods in Java?
    Answer: Static variables and static methods belong to classes, not instances of classes. Static variables allocate memory when the class is loaded and are allocated only once and are not released until the end of the program. Static methods can be called directly through the class name without creating an instance of the class.
class MyClass {
    
      
   static int staticProperty = 10;
   static void staticMethod() {
    
      
       System.out.println("This is a static method.");  
   }  
}
public class Main {
    
      
   public static void main(String[] args) {
    
      
       System.out.println("Static property: " + MyClass.staticProperty);  
       MyClass.staticMethod();  
   }  
}
  1. What is inheritance in Java?
    Answer: Inheritance is a feature in Java object-oriented programming that allows one class (subclass) to inherit the properties and methods of another class (parent class).
    Inheritance in Java is a code reuse mechanism that allows one class (subclass) to inherit the properties and methods of another class (parent class). Subclasses can extend the functions of the parent class, and can also override or add new methods according to their own needs. The keyword for inheritance is "extends".
    The following is a simple Java inheritance code example:
// 父类  
class Animal {
    
      
   String name;
   // 父类构造方法  
   public Animal(String name) {
    
      
       this.name = name;  
   }
   // 父类方法  
   public void makeSound() {
    
      
       System.out.println(name + " makes a sound");  
   }  
}
// 子类,继承自 Animal  
class Dog extends Animal {
    
      
   String breed;
   // 子类构造方法,调用父类构造方法  
   public Dog(String name, String breed) {
    
      
       super(name); // 调用父类构造方法  
       this.breed = breed;  
   }
   // 子类方法,覆盖父类方法  
   @Override  
   public void makeSound() {
    
      
       System.out.println(name + " barks");  
   }
   // 子类新增方法  
   public void doTrick() {
    
      
       System.out.println(name + " does a trick");  
   }  
}
public class Main {
    
      
   public static void main(String[] args) {
    
      
       Dog myDog = new Dog("Buddy", "Golden Retriever");  
       myDog.makeSound(); // 输出:Buddy barks  
       myDog.doTrick(); // 输出:Buddy does a trick  
   }  
}

In this example, we define a parent class Animaland a child class Dog, and the child class inherits the properties and methods of the parent class. We create an Dogobject and call its methods and properties.

  1. Calculate the sum of two numbers
public class Sum {
    
      
   public static void main(String[] args) {
    
      
       int a = 10;  
       int b = 20;  
       int sum = a + b;  
       System.out.println("两数之和为:" + sum);  
   }  
}
  1. Calculate the difference between two numbers
public class Difference {
    
      
   public static void main(String[] args) {
    
      
       int a = 10;  
       int b = 20;  
       int difference = a - b;  
       System.out.println("两数之差为:" + difference);  
   }  
}
  1. Calculate the product of two numbers
public class Product {
    
      
   public static void main(String[] args) {
    
      
       int a = 10;  
       int b = 20;  
       int product = a * b;  
       System.out.println("两数之积为:" + product);  
   }  
}
  1. Calculate the quotient of two numbers
public class Quotient {
    
      
   public static void main(String[] args) {
    
      
       int a = 10;  
       int b = 20;  
       int quotient = a / b;  
       System.out.println("两数之商为:" + quotient);  
   }  
}
  1. Determine whether a number is even
public class EvenNumber {
    
      
   public static void main(String[] args) {
    
      
       int number = 20;  
       if (isEven(number)) {
    
      
           System.out.println(number + " 是偶数");  
       } else {
    
      
           System.out.println(number + " 不是偶数");  
       }  
   }
   public static boolean isEven(int number) {
    
      
       return number % 2 == 0;  
   }  
}
  1. Determine whether a number is odd
public class OddNumber {
    
      
   public static void main(String[] args) {
    
      
       int number = 20;  
       if (isOdd(number)) {
    
      
           System.out.println(number + " 是奇数");  
       } else {
    
      
           System.out.println(number + " 不是奇数");  
       }  
   }
   public static boolean isOdd(int number) {
    
      
       return number % 2!= 0;  
   }  
}
  1. Print multiplication table
public class MultiplicationTable {
    
      
   public static void main(String[] args) {
    
      
       for (int i = 1; i <= 9; i++) {
    
      
           for (int j = 1; j <= i; j++) {
    
      
               System.out.print(j + " * " + i + " = " + (i * j) + "\t");  
           }  
           System.out.println();  
       }  
   }  
}
  1. Replace spaces in string
public class StringReplacer {
    
      
   public static void main(String[] args) {
    
      
       String input = "Hello World";  
       String output = replaceSpace(input);  
       System.out.println(output);  
   }
   public static String replaceSpace(String input) {
    
      
       return input.replace(" ", "_");  
   }  
}
  1. Count the number of characters in a string
public class StringCounter {
    
      
   public static void main(String[] args) {
    
      
       String input = "Hello World";  
       int count = countCharacters(input);  
       System.out.println("字符数量:" + count);  
   }
   public static int countCharacters(String input) {
    
      
       return input.length();  
   }  
}
  1. Determine whether a string is a palindrome string
public class Palindrome {
    
      
   public static void main(String[] args) {
    
      
       String input = "madam";  
       if (isPalindrome(input)) {
    
      
           System.out.println(input + " 是回文字符串");  
       } else {
    
      
           System.out.println(input + " 不是回文字符串
      }    
  }    
  public static boolean isPalindrome(String input) {
    
        
      int left = 0;    
      int right = input.length() - 1;    
      while (left < right) {
    
        
          if (input.charAt(left)!= input.charAt(right)) {
    
        
              return false;    
          }    
          left++;    
          right--;    
      }    
      return true;    
  }    
}
  1. Topic: Implement a simple Java multi-threaded program.
    Answer:
public class MultiThreading {
    
      
   public static void main(String[] args) {
    
      
       Thread t1 = new Thread(new PrintName("Thread-1"));  
       Thread t2 = new Thread(new PrintName("Thread-2"));  
       t1.start();  
       t2.start();  
   }
   static class PrintName implements Runnable {
    
      
       private String name;
       public PrintName(String name) {
    
      
           this.name = name;  
       }
       @Override  
       public void run() {
    
      
           for (int i = 0; i < 10; i++) {
    
      
               System.out.println(name + " - " + i);  
               try {
    
      
                   Thread.sleep(100);  
               } catch (InterruptedException e) {
    
      
                   e.printStackTrace();  
               }  
           }  
       }  
   }  
}
  1. Question: Implement a Java class that has a private constructor and a public static method that returns an instance of the class.
    Answer:
public class Singleton {
    
      
   private Singleton() {
    
      
   }
   public static Singleton getInstance() {
    
      
       return new Singleton();  
   }  
}
  1. Question: Implement a Java class that has a string and a method that returns the reverse string of the string.
    Answer:
public class StringReverse {
    
      
   private String str;
   public StringReverse(String str) {
    
      
       this.str = str;  
   }
   public String reverse() {
    
      
       StringBuilder sb = new StringBuilder();  
       for (int i = str.length() - 1; i >= 0; i--) {
    
      
           sb.append(str.charAt(i));  
       }  
       return sb.toString();  
   }  
}
  1. Question: Implement a Java interface. The interface has a method that returns a string that represents the implementation of the interface.
    Answer:
public interface MyInterface {
    
      
   String getString();  
}
  1. Question: Implement a Java abstract class. The class has two abstract methods and one concrete method. The concrete method implements two abstract methods.
    Answer:
public abstract class MyAbstractClass {
    
      
   public abstract void abstractMethod1();  
   public abstract void abstractMethod2();
   public void specificMethod() {
    
      
       abstractMethod1();  
       abstractMethod2();  
   }  
}
  1. Question: Implement a Java class that has a string and a method that converts the string to uppercase.
    Answer:
public class StringToUpperCase {
    
      
   private String str;
   public StringToUpperCase(String str) {
    
      
       this.str = str;  
   }
   public String toUpperCase() {
    
      
       StringBuilder sb = new StringBuilder();  
       for (int i = 0; i < str.length(); i++) {
    
      
           sb.append(Character.toUpperCase(str.charAt(i)));  
       }  
       return sb.toString();  
   }  
}
  1. Question: Implement a Java class that has an integer and a method that converts the integer to a string.
    Answer:
public class IntegerToString {
    
      
   private int num;
   public IntegerToString(int num) {
    
      
       this.num = num;  
   }
   public String toString() {
    
      
       return Integer.toString(num);  
   }  
}
  1. Question: Implement a Java class that has a string and a method that converts the string to an integer.
    Answer:
public class StringToInteger {
    
      
   private String str;
   public StringToInteger(String str) {
    
      
       this.str = str;  
   }
   public int toInteger() {
    
      
       return Integer.parseInt(str);  
   }  
}
  1. Question: Implement a Java class that has a string and a method that splits the string into an array of substrings.
    Answer:
    Here is a Java class that implements this requirement:
public class StringSplitter {
    
    
   private String str;
   public StringSplitter(String str) {
    
      
       this.str = str;  
   }
   public String[] split(int maxLength) {
    
      
       if (maxLength <= 0) {
    
      
           throw new IllegalArgumentException("Max length must be greater than 0");  
       }
       String[] substrings = new String[str.length() / maxLength];  
       int index = 0;
       for (int i = 0; i < str.length(); i += maxLength) {
    
      
           substrings[index++] = str.substring(i, Math.min(i + maxLength, str.length()));  
       }
       return substrings;  
   }
   public static void main(String[] args) {
    
      
       StringSplitter splitter = new StringSplitter("This is a test string");  
       String[] substrings = splitter.split(4);
       for (String substring : substrings) {
    
      
           System.out.println(substring);  
       }  
   }  
}

This class has a string property strand a splitmethod that accepts an integer parameter maxLengththat specifies the maximum length of the substring. splitMethod splits a string into an array of substrings and returns that array. In mainthe method, we create an StringSplitterobject and use splitthe method to split the string into an array of substrings with a maximum length of 4. Then, we loop through and print these substrings.

  1. Write a Java class to implement the clone function.
public class Cloneable {
    
      
   private int id;  
   private String name;
   public Cloneable(int id, String name) {
    
      
       this.id = id;  
       this.name = name;  
   }
   public Object clone() throws CloneNotSupportedException {
    
      
       return super.clone();  
   }
   @Override  
   protected void finalize() throws Throwable {
    
      
       super.finalize();  
       System.out.println("Cloneable object " + this.id + " has been cloned");  
   }  
}
  1. Implement deep copy and shallow copy in Java.
public class Cloneable {
    
      
   private int id;  
   private String name;
   public Cloneable(int id, String name) {
    
      
       this.id = id;  
       this.name = name;  
   }
   public Object deepClone() {
    
      
       if (this instanceof Cloneable) {
    
      
           try {
    
      
               return (Cloneable) super.clone();  
           } catch (CloneNotSupportedException e) {
    
      
               throw new RuntimeException("Failed to deep clone", e);  
           }  
       }  
       return null;  
   }
   public Object shallowClone() {
    
      
       return super.clone();  
   }  
}
  1. Implement abstract classes and abstract methods in Java.
public abstract class Animal {
    
      
   private String name;
   public abstract void makeSound();
   public Animal(String name) {
    
      
       this.name = name;  
   }
   public String getName() {
    
      
       return name;  
   }  
}
public class Dog extends Animal {
    
      
   private String breed;
   public Dog(String name, String breed) {
    
      
       super(name);  
       this.breed = breed;  
   }
   @Override  
   public void makeSound() {
    
      
       System.out.println(name + " barks");  
   }
   public String getBreed() {
    
      
       return breed;  
   }  
}

Guess you like

Origin blog.csdn.net/superdangbo/article/details/133514231